@mastra/core 0.2.0-alpha.99 → 0.2.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/agent/index.d.ts +6 -8
  2. package/dist/agent/index.js +1 -7
  3. package/dist/{telemetry-oCUM52DG.d.ts → base-BbtPAA6f.d.ts} +50 -8
  4. package/dist/{index-Cwb-5AzX.d.ts → base-C7R9FwZ6.d.ts} +450 -403
  5. package/dist/base.d.ts +3 -43
  6. package/dist/base.js +1 -3
  7. package/dist/bundler/index.d.ts +3 -4
  8. package/dist/bundler/index.js +1 -4
  9. package/dist/{chunk-MCB4M5W4.js → chunk-22LC46YN.js} +3 -9
  10. package/dist/chunk-4ZRHVG25.js +402 -0
  11. package/dist/{chunk-KNPBNSJ7.js → chunk-55GTEVHJ.js} +13 -14
  12. package/dist/chunk-5HXXWLRX.js +626 -0
  13. package/dist/chunk-6TCTOQ3G.js +1204 -0
  14. package/dist/{chunk-ZJOMHCWE.js → chunk-AN562ICT.js} +98 -151
  15. package/dist/chunk-AWEACB2T.js +66 -0
  16. package/dist/chunk-BB4KXGBU.js +83 -0
  17. package/dist/chunk-C6A6W6XS.js +77 -0
  18. package/dist/{chunk-EO3TIPGQ.js → chunk-CUIUUULJ.js} +375 -254
  19. package/dist/chunk-HT63PEVD.js +37 -0
  20. package/dist/chunk-K36NSQWH.js +10 -0
  21. package/dist/chunk-NUDAZEOG.js +35 -0
  22. package/dist/{chunk-ICMEXHKD.js → chunk-O2VP5JBC.js} +48 -55
  23. package/dist/{chunk-42DYOLDV.js → chunk-PNZK456O.js} +13 -21
  24. package/dist/chunk-RG66XEJT.js +8 -0
  25. package/dist/chunk-SIFBBGY6.js +190 -0
  26. package/dist/{chunk-A7SNFYQB.js → chunk-V4WSAQOP.js} +7 -15
  27. package/dist/chunk-V5UMPUKC.js +218 -0
  28. package/dist/{chunk-DHCULRJM.js → chunk-VE4JJJSW.js} +126 -78
  29. package/dist/chunk-ZINPRHAN.js +22 -0
  30. package/dist/{chunk-C55JWGDU.js → chunk-ZJOXJFJI.js} +42 -15
  31. package/dist/deployer/index.d.ts +3 -5
  32. package/dist/deployer/index.js +1 -5
  33. package/dist/eval/index.d.ts +8 -13
  34. package/dist/eval/index.js +1 -3
  35. package/dist/filter/index.js +1 -2
  36. package/dist/hooks/index.d.ts +13 -18
  37. package/dist/hooks/index.js +1 -2
  38. package/dist/{index-CBZ2mk2H.d.ts → index-B2JCcAQt.d.ts} +1 -1
  39. package/dist/index.d.ts +16 -16
  40. package/dist/index.js +37 -67
  41. package/dist/integration/index.d.ts +8 -10
  42. package/dist/integration/index.js +1 -3
  43. package/dist/llm/index.d.ts +6 -8
  44. package/dist/llm/index.js +1 -1
  45. package/dist/logger/index.d.ts +1 -1
  46. package/dist/logger/index.js +1 -2
  47. package/dist/mastra/index.d.ts +23 -25
  48. package/dist/mastra/index.js +1 -9
  49. package/dist/memory/index.d.ts +8 -10
  50. package/dist/memory/index.js +1 -9
  51. package/dist/relevance/index.js +1 -8
  52. package/dist/storage/index.d.ts +21 -10
  53. package/dist/storage/index.js +3 -7
  54. package/dist/telemetry/index.d.ts +35 -5
  55. package/dist/telemetry/index.js +1 -2
  56. package/dist/telemetry/otel-vendor.d.ts +7 -0
  57. package/dist/telemetry/otel-vendor.js +7 -0
  58. package/dist/tools/index.d.ts +6 -8
  59. package/dist/tools/index.js +1 -2
  60. package/dist/tts/index.d.ts +2 -4
  61. package/dist/tts/index.js +1 -5
  62. package/dist/{metric-BWeQNZt6.d.ts → types-m9RryK9a.d.ts} +6 -1
  63. package/dist/utils.js +1 -2
  64. package/dist/vector/index.d.ts +4 -6
  65. package/dist/vector/index.js +1 -4
  66. package/dist/vector/libsql/index.d.ts +2 -4
  67. package/dist/vector/libsql/index.js +1 -6
  68. package/dist/{workflow-DTtv7_Eq.d.ts → workflow-7xHmmFH5.d.ts} +3 -6
  69. package/dist/workflows/index.d.ts +7 -9
  70. package/dist/workflows/index.js +1 -4
  71. package/package.json +22 -18
  72. package/dist/chunk-4LJFWC2Q.js +0 -216
  73. package/dist/chunk-4ZUSEHLH.js +0 -285
  74. package/dist/chunk-AJJZUHB4.js +0 -14
  75. package/dist/chunk-G4MCO7XF.js +0 -70
  76. package/dist/chunk-HBTQNIAX.js +0 -90
  77. package/dist/chunk-HPXWJBQK.js +0 -222
  78. package/dist/chunk-JJ57BXQR.js +0 -16
  79. package/dist/chunk-JP37ODNX.js +0 -36
  80. package/dist/chunk-K3N7KJHH.js +0 -52
  81. package/dist/chunk-MDM2JS2U.js +0 -1288
  82. package/dist/chunk-VOUPGVRD.js +0 -27
  83. package/dist/chunk-Z7JFMQZZ.js +0 -551
  84. /package/dist/{chunk-AE3H2QEY.js → chunk-ZDWFBE5L.js} +0 -0
@@ -0,0 +1,626 @@
1
+ import { TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_MESSAGES, TABLE_THREADS, TABLE_TRACES } from './chunk-RG66XEJT.js';
2
+ import { MastraBase } from './chunk-AWEACB2T.js';
3
+ import { createClient } from '@libsql/client';
4
+ import { join } from 'node:path';
5
+
6
+ // src/storage/base.ts
7
+ var MastraStorage = class extends MastraBase {
8
+ /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */
9
+ static TABLE_WORKFLOW_SNAPSHOT = TABLE_WORKFLOW_SNAPSHOT;
10
+ /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */
11
+ static TABLE_EVALS = TABLE_EVALS;
12
+ /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */
13
+ static TABLE_MESSAGES = TABLE_MESSAGES;
14
+ /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */
15
+ static TABLE_THREADS = TABLE_THREADS;
16
+ /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */
17
+ static TABLE_TRACES = TABLE_TRACES;
18
+ hasInitialized = null;
19
+ constructor({ name }) {
20
+ super({
21
+ component: "STORAGE",
22
+ name
23
+ });
24
+ }
25
+ async __batchInsert({
26
+ tableName,
27
+ records
28
+ }) {
29
+ await this.init();
30
+ return this.batchInsert({ tableName, records });
31
+ }
32
+ async __getThreadById({ threadId }) {
33
+ await this.init();
34
+ return this.getThreadById({ threadId });
35
+ }
36
+ async __getThreadsByResourceId({ resourceId }) {
37
+ await this.init();
38
+ return this.getThreadsByResourceId({ resourceId });
39
+ }
40
+ async __saveThread({ thread }) {
41
+ await this.init();
42
+ return this.saveThread({ thread });
43
+ }
44
+ async __updateThread({
45
+ id,
46
+ title,
47
+ metadata
48
+ }) {
49
+ await this.init();
50
+ return this.updateThread({ id, title, metadata });
51
+ }
52
+ async __deleteThread({ threadId }) {
53
+ await this.init();
54
+ return this.deleteThread({ threadId });
55
+ }
56
+ async __getMessages({ threadId, selectBy, threadConfig }) {
57
+ await this.init();
58
+ return this.getMessages({ threadId, selectBy, threadConfig });
59
+ }
60
+ async __saveMessages({ messages }) {
61
+ await this.init();
62
+ return this.saveMessages({ messages });
63
+ }
64
+ async __getTraces({
65
+ scope,
66
+ page,
67
+ perPage,
68
+ attributes
69
+ }) {
70
+ await this.init();
71
+ return this.getTraces({ scope, page, perPage, attributes });
72
+ }
73
+ async init() {
74
+ if (await this.hasInitialized) {
75
+ return;
76
+ }
77
+ this.hasInitialized = Promise.all([
78
+ this.createTable({
79
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
80
+ schema: {
81
+ workflow_name: {
82
+ type: "text"
83
+ },
84
+ run_id: {
85
+ type: "text"
86
+ },
87
+ snapshot: {
88
+ type: "text"
89
+ },
90
+ createdAt: {
91
+ type: "timestamp"
92
+ },
93
+ updatedAt: {
94
+ type: "timestamp"
95
+ }
96
+ }
97
+ }),
98
+ this.createTable({
99
+ tableName: TABLE_EVALS,
100
+ schema: {
101
+ input: {
102
+ type: "text"
103
+ },
104
+ output: {
105
+ type: "text"
106
+ },
107
+ result: {
108
+ type: "jsonb"
109
+ },
110
+ agent_name: {
111
+ type: "text"
112
+ },
113
+ metric_name: {
114
+ type: "text"
115
+ },
116
+ instructions: {
117
+ type: "text"
118
+ },
119
+ test_info: {
120
+ type: "jsonb",
121
+ nullable: true
122
+ },
123
+ global_run_id: {
124
+ type: "text"
125
+ },
126
+ run_id: {
127
+ type: "text"
128
+ },
129
+ created_at: {
130
+ type: "timestamp"
131
+ }
132
+ }
133
+ }),
134
+ this.createTable({
135
+ tableName: TABLE_THREADS,
136
+ schema: {
137
+ id: { type: "text", nullable: false, primaryKey: true },
138
+ resourceId: { type: "text", nullable: false },
139
+ title: { type: "text", nullable: false },
140
+ metadata: { type: "text", nullable: true },
141
+ createdAt: { type: "timestamp", nullable: false },
142
+ updatedAt: { type: "timestamp", nullable: false }
143
+ }
144
+ }),
145
+ this.createTable({
146
+ tableName: TABLE_MESSAGES,
147
+ schema: {
148
+ id: { type: "text", nullable: false, primaryKey: true },
149
+ thread_id: { type: "text", nullable: false },
150
+ content: { type: "text", nullable: false },
151
+ role: { type: "text", nullable: false },
152
+ type: { type: "text", nullable: false },
153
+ createdAt: { type: "timestamp", nullable: false }
154
+ }
155
+ }),
156
+ this.createTable({
157
+ tableName: TABLE_TRACES,
158
+ schema: {
159
+ id: { type: "text", nullable: false, primaryKey: true },
160
+ parentSpanId: { type: "text", nullable: true },
161
+ name: { type: "text", nullable: false },
162
+ traceId: { type: "text", nullable: false },
163
+ scope: { type: "text", nullable: false },
164
+ kind: { type: "integer", nullable: false },
165
+ attributes: { type: "jsonb", nullable: true },
166
+ status: { type: "jsonb", nullable: true },
167
+ events: { type: "jsonb", nullable: true },
168
+ links: { type: "jsonb", nullable: true },
169
+ other: { type: "text", nullable: true },
170
+ startTime: { type: "bigint", nullable: false },
171
+ endTime: { type: "bigint", nullable: false },
172
+ createdAt: { type: "timestamp", nullable: false }
173
+ }
174
+ })
175
+ ]).then(() => true);
176
+ await this.hasInitialized;
177
+ }
178
+ async persistWorkflowSnapshot({
179
+ workflowName,
180
+ runId,
181
+ snapshot
182
+ }) {
183
+ await this.init();
184
+ const data = {
185
+ workflow_name: workflowName,
186
+ run_id: runId,
187
+ snapshot,
188
+ createdAt: /* @__PURE__ */ new Date(),
189
+ updatedAt: /* @__PURE__ */ new Date()
190
+ };
191
+ this.logger.debug("Persisting workflow snapshot", { workflowName, runId, data });
192
+ await this.insert({
193
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
194
+ record: data
195
+ });
196
+ }
197
+ async loadWorkflowSnapshot({
198
+ workflowName,
199
+ runId
200
+ }) {
201
+ if (!this.hasInitialized) {
202
+ await this.init();
203
+ }
204
+ this.logger.debug("Loading workflow snapshot", { workflowName, runId });
205
+ const d = await this.load({
206
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
207
+ keys: { workflow_name: workflowName, run_id: runId }
208
+ });
209
+ return d ? d.snapshot : null;
210
+ }
211
+ async __getEvalsByAgentName(agentName, type) {
212
+ await this.init();
213
+ return this.getEvalsByAgentName(agentName, type);
214
+ }
215
+ };
216
+ function safelyParseJSON(jsonString) {
217
+ try {
218
+ return JSON.parse(jsonString);
219
+ } catch {
220
+ return {};
221
+ }
222
+ }
223
+ var DefaultStorage = class extends MastraStorage {
224
+ client;
225
+ constructor({ config }) {
226
+ super({ name: `MastraStorageLibSql` });
227
+ this.client = createClient({
228
+ url: this.rewriteDbUrl(config.url),
229
+ authToken: config.authToken
230
+ });
231
+ }
232
+ rewriteDbUrl(url) {
233
+ if (url.startsWith("file:") && !url.startsWith("file:/")) {
234
+ const cwd = process.cwd();
235
+ const relativePath = url.slice("file:".length);
236
+ if (cwd.endsWith(".mastra") || cwd.endsWith(".mastra/")) {
237
+ const baseDir = join(cwd, `..`);
238
+ const fullPath = join(baseDir, relativePath);
239
+ this.logger.debug(
240
+ `Initializing LibSQL db with url ${url} with relative file path from inside .mastra directory. Rewriting relative file url to "file:${fullPath}". This ensures it's outside the .mastra directory. If the db is stored inside .mastra it will be deleted when Mastra re-bundles code.`
241
+ );
242
+ return `file:${fullPath}`;
243
+ }
244
+ }
245
+ return url;
246
+ }
247
+ getCreateTableSQL(tableName, schema) {
248
+ const columns = Object.entries(schema).map(([name, col]) => {
249
+ let type = col.type.toUpperCase();
250
+ if (type === "TEXT") type = "TEXT";
251
+ if (type === "TIMESTAMP") type = "TEXT";
252
+ const nullable = col.nullable ? "" : "NOT NULL";
253
+ const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
254
+ return `${name} ${type} ${nullable} ${primaryKey}`.trim();
255
+ });
256
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
257
+ const stmnt = `CREATE TABLE IF NOT EXISTS ${tableName} (
258
+ ${columns.join(",\n")},
259
+ PRIMARY KEY (workflow_name, run_id)
260
+ )`;
261
+ return stmnt;
262
+ }
263
+ return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
264
+ }
265
+ async createTable({
266
+ tableName,
267
+ schema
268
+ }) {
269
+ try {
270
+ this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
271
+ const sql = this.getCreateTableSQL(tableName, schema);
272
+ await this.client.execute(sql);
273
+ } catch (error) {
274
+ this.logger.error(`Error creating table ${tableName}: ${error}`);
275
+ throw error;
276
+ }
277
+ }
278
+ async clearTable({ tableName }) {
279
+ try {
280
+ await this.client.execute(`DELETE FROM ${tableName}`);
281
+ } catch (e) {
282
+ if (e instanceof Error) {
283
+ this.logger.error(e.message);
284
+ }
285
+ }
286
+ }
287
+ prepareStatement({ tableName, record }) {
288
+ const columns = Object.keys(record);
289
+ const values = Object.values(record).map((v) => {
290
+ if (typeof v === `undefined`) {
291
+ return null;
292
+ }
293
+ return typeof v === "object" ? JSON.stringify(v) : v;
294
+ });
295
+ const placeholders = values.map(() => "?").join(", ");
296
+ return {
297
+ sql: `INSERT OR REPLACE INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
298
+ args: values
299
+ };
300
+ }
301
+ async insert({ tableName, record }) {
302
+ try {
303
+ await this.client.execute(this.prepareStatement({ tableName, record }));
304
+ } catch (error) {
305
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
306
+ throw error;
307
+ }
308
+ }
309
+ async batchInsert({ tableName, records }) {
310
+ if (records.length === 0) return;
311
+ try {
312
+ const batchStatements = records.map((r) => this.prepareStatement({ tableName, record: r }));
313
+ await this.client.batch(batchStatements, "write");
314
+ } catch (error) {
315
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
316
+ throw error;
317
+ }
318
+ }
319
+ async load({ tableName, keys }) {
320
+ const conditions = Object.entries(keys).map(([key]) => `${key} = ?`).join(" AND ");
321
+ const values = Object.values(keys);
322
+ const result = await this.client.execute({
323
+ sql: `SELECT * FROM ${tableName} WHERE ${conditions} LIMIT 1`,
324
+ args: values
325
+ });
326
+ if (!result.rows || result.rows.length === 0) {
327
+ return null;
328
+ }
329
+ const row = result.rows[0];
330
+ const parsed = Object.fromEntries(
331
+ Object.entries(row || {}).map(([k, v]) => {
332
+ try {
333
+ return [k, typeof v === "string" ? JSON.parse(v) : v];
334
+ } catch {
335
+ return [k, v];
336
+ }
337
+ })
338
+ );
339
+ return parsed;
340
+ }
341
+ async getThreadById({ threadId }) {
342
+ const result = await this.load({
343
+ tableName: TABLE_THREADS,
344
+ keys: { id: threadId }
345
+ });
346
+ if (!result) {
347
+ return null;
348
+ }
349
+ return {
350
+ ...result,
351
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
352
+ };
353
+ }
354
+ async getThreadsByResourceId({ resourceId }) {
355
+ const result = await this.client.execute({
356
+ sql: `SELECT * FROM ${TABLE_THREADS} WHERE resourceId = ?`,
357
+ args: [resourceId]
358
+ });
359
+ if (!result.rows) {
360
+ return [];
361
+ }
362
+ return result.rows.map((thread) => ({
363
+ id: thread.id,
364
+ resourceId: thread.resourceId,
365
+ title: thread.title,
366
+ createdAt: thread.createdAt,
367
+ updatedAt: thread.updatedAt,
368
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
369
+ }));
370
+ }
371
+ async saveThread({ thread }) {
372
+ await this.insert({
373
+ tableName: TABLE_THREADS,
374
+ record: {
375
+ ...thread,
376
+ metadata: JSON.stringify(thread.metadata)
377
+ }
378
+ });
379
+ return thread;
380
+ }
381
+ async updateThread({
382
+ id,
383
+ title,
384
+ metadata
385
+ }) {
386
+ const thread = await this.getThreadById({ threadId: id });
387
+ if (!thread) {
388
+ throw new Error(`Thread ${id} not found`);
389
+ }
390
+ const updatedThread = {
391
+ ...thread,
392
+ title,
393
+ metadata: {
394
+ ...thread.metadata,
395
+ ...metadata
396
+ }
397
+ };
398
+ await this.client.execute({
399
+ sql: `UPDATE ${TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
400
+ args: [title, JSON.stringify(updatedThread.metadata), id]
401
+ });
402
+ return updatedThread;
403
+ }
404
+ async deleteThread({ threadId }) {
405
+ await this.client.execute({
406
+ sql: `DELETE FROM ${TABLE_THREADS} WHERE id = ?`,
407
+ args: [threadId]
408
+ });
409
+ }
410
+ parseRow(row) {
411
+ let content = row.content;
412
+ try {
413
+ content = JSON.parse(row.content);
414
+ } catch (e) {
415
+ }
416
+ return {
417
+ id: row.id,
418
+ content,
419
+ role: row.role,
420
+ type: row.type,
421
+ createdAt: new Date(row.createdAt),
422
+ threadId: row.thread_id
423
+ };
424
+ }
425
+ async getMessages({ threadId, selectBy }) {
426
+ try {
427
+ const messages = [];
428
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
429
+ if (selectBy?.include?.length) {
430
+ const includeIds = selectBy.include.map((i) => i.id);
431
+ const maxPrev = Math.max(...selectBy.include.map((i) => i.withPreviousMessages || 0));
432
+ const maxNext = Math.max(...selectBy.include.map((i) => i.withNextMessages || 0));
433
+ const includeResult = await this.client.execute({
434
+ sql: `
435
+ WITH numbered_messages AS (
436
+ SELECT
437
+ id,
438
+ content,
439
+ role,
440
+ type,
441
+ "createdAt",
442
+ thread_id,
443
+ ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
444
+ FROM "${TABLE_MESSAGES}"
445
+ WHERE thread_id = ?
446
+ ),
447
+ target_positions AS (
448
+ SELECT row_num as target_pos
449
+ FROM numbered_messages
450
+ WHERE id IN (${includeIds.map(() => "?").join(", ")})
451
+ )
452
+ SELECT DISTINCT m.*
453
+ FROM numbered_messages m
454
+ CROSS JOIN target_positions t
455
+ WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
456
+ ORDER BY m."createdAt" ASC
457
+ `,
458
+ args: [threadId, ...includeIds, maxPrev, maxNext]
459
+ });
460
+ if (includeResult.rows) {
461
+ messages.push(...includeResult.rows.map((row) => this.parseRow(row)));
462
+ }
463
+ }
464
+ const excludeIds = messages.map((m) => m.id);
465
+ const remainingSql = `
466
+ SELECT
467
+ id,
468
+ content,
469
+ role,
470
+ type,
471
+ "createdAt",
472
+ thread_id
473
+ FROM "${TABLE_MESSAGES}"
474
+ WHERE thread_id = ?
475
+ ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
476
+ ORDER BY "createdAt" DESC
477
+ LIMIT ?
478
+ `;
479
+ const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
480
+ const remainingResult = await this.client.execute({
481
+ sql: remainingSql,
482
+ args: remainingArgs
483
+ });
484
+ if (remainingResult.rows) {
485
+ messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
486
+ }
487
+ messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
488
+ return messages;
489
+ } catch (error) {
490
+ this.logger.error("Error getting messages:", error);
491
+ throw error;
492
+ }
493
+ }
494
+ async saveMessages({ messages }) {
495
+ if (messages.length === 0) return messages;
496
+ const tx = await this.client.transaction("write");
497
+ try {
498
+ const threadId = messages[0]?.threadId;
499
+ if (!threadId) {
500
+ throw new Error("Thread ID is required");
501
+ }
502
+ for (const message of messages) {
503
+ const time = message.createdAt || /* @__PURE__ */ new Date();
504
+ await tx.execute({
505
+ sql: `INSERT INTO ${TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
506
+ VALUES (?, ?, ?, ?, ?, ?)`,
507
+ args: [
508
+ message.id,
509
+ threadId,
510
+ typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
511
+ message.role,
512
+ message.type,
513
+ time instanceof Date ? time.toISOString() : time
514
+ ]
515
+ });
516
+ }
517
+ await tx.commit();
518
+ return messages;
519
+ } catch (error) {
520
+ this.logger.error("Failed to save messages in database: " + error?.message);
521
+ await tx.rollback();
522
+ throw error;
523
+ }
524
+ }
525
+ transformEvalRow(row) {
526
+ const resultValue = JSON.parse(row.result);
527
+ const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
528
+ if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
529
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
530
+ }
531
+ return {
532
+ input: row.input,
533
+ output: row.output,
534
+ result: resultValue,
535
+ agentName: row.agent_name,
536
+ metricName: row.metric_name,
537
+ instructions: row.instructions,
538
+ testInfo: testInfoValue,
539
+ globalRunId: row.global_run_id,
540
+ runId: row.run_id,
541
+ createdAt: row.created_at
542
+ };
543
+ }
544
+ async getEvalsByAgentName(agentName, type) {
545
+ try {
546
+ const baseQuery = `SELECT * FROM ${TABLE_EVALS} WHERE agent_name = ?`;
547
+ const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR test_info->>'testPath' IS NULL)" : "";
548
+ const result = await this.client.execute({
549
+ sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
550
+ args: [agentName]
551
+ });
552
+ return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
553
+ } catch (error) {
554
+ if (error instanceof Error && error.message.includes("no such table")) {
555
+ return [];
556
+ }
557
+ this.logger.error("Failed to get evals for the specified agent: " + error?.message);
558
+ throw error;
559
+ }
560
+ }
561
+ // TODO: add types
562
+ async getTraces({
563
+ name,
564
+ scope,
565
+ page,
566
+ perPage,
567
+ attributes
568
+ } = {
569
+ page: 0,
570
+ perPage: 100
571
+ }) {
572
+ const limit = perPage;
573
+ const offset = page * perPage;
574
+ const args = [];
575
+ const conditions = [];
576
+ if (name) {
577
+ conditions.push("name LIKE CONCAT(?, '%')");
578
+ }
579
+ if (scope) {
580
+ conditions.push("scope = ?");
581
+ }
582
+ if (attributes) {
583
+ Object.keys(attributes).forEach((key) => {
584
+ conditions.push(`attributes->>'$.${key}' = ?`);
585
+ });
586
+ }
587
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
588
+ if (name) {
589
+ args.push(name);
590
+ }
591
+ if (scope) {
592
+ args.push(scope);
593
+ }
594
+ if (attributes) {
595
+ for (const [_key, value] of Object.entries(attributes)) {
596
+ args.push(value);
597
+ }
598
+ }
599
+ args.push(limit, offset);
600
+ const result = await this.client.execute({
601
+ sql: `SELECT * FROM ${TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
602
+ args
603
+ });
604
+ if (!result.rows) {
605
+ return [];
606
+ }
607
+ return result.rows.map((row) => ({
608
+ id: row.id,
609
+ parentSpanId: row.parentSpanId,
610
+ traceId: row.traceId,
611
+ name: row.name,
612
+ scope: row.scope,
613
+ kind: row.kind,
614
+ status: safelyParseJSON(row.status),
615
+ events: safelyParseJSON(row.events),
616
+ links: safelyParseJSON(row.links),
617
+ attributes: safelyParseJSON(row.attributes),
618
+ startTime: row.startTime,
619
+ endTime: row.endTime,
620
+ other: safelyParseJSON(row.other),
621
+ createdAt: row.createdAt
622
+ }));
623
+ }
624
+ };
625
+
626
+ export { DefaultStorage, MastraStorage };