@mastra/core 0.0.0-commonjs-20250227130920

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -0
  3. package/dist/agent/index.cjs +1865 -0
  4. package/dist/agent/index.d.cts +15 -0
  5. package/dist/agent/index.d.ts +15 -0
  6. package/dist/agent/index.js +1 -0
  7. package/dist/base-D90KQ4XI.d.ts +139 -0
  8. package/dist/base-hs9NDAZ2.d.cts +139 -0
  9. package/dist/base-nKCMCNrM.d.ts +920 -0
  10. package/dist/base-nhesrHv3.d.cts +920 -0
  11. package/dist/base.cjs +138 -0
  12. package/dist/base.d.cts +6 -0
  13. package/dist/base.d.ts +6 -0
  14. package/dist/base.js +1 -0
  15. package/dist/bundler/index.cjs +158 -0
  16. package/dist/bundler/index.d.cts +28 -0
  17. package/dist/bundler/index.d.ts +28 -0
  18. package/dist/bundler/index.js +1 -0
  19. package/dist/chunk-33GSTUNK.js +620 -0
  20. package/dist/chunk-4YRYBCOZ.js +10 -0
  21. package/dist/chunk-55NFNRKO.js +10 -0
  22. package/dist/chunk-5XPCMNGW.js +215 -0
  23. package/dist/chunk-B3M27AMP.js +1479 -0
  24. package/dist/chunk-BB4KXGBU.js +83 -0
  25. package/dist/chunk-C6A6W6XS.js +77 -0
  26. package/dist/chunk-HQ55LN2U.js +318 -0
  27. package/dist/chunk-KNVTCZW7.js +416 -0
  28. package/dist/chunk-LH47WVJL.js +61 -0
  29. package/dist/chunk-NGD2HQYW.js +346 -0
  30. package/dist/chunk-NUDAZEOG.js +35 -0
  31. package/dist/chunk-OZ4XVJ6F.js +49 -0
  32. package/dist/chunk-PHMSPCTC.js +145 -0
  33. package/dist/chunk-PNZK456O.js +88 -0
  34. package/dist/chunk-QAAJAHDB.js +37 -0
  35. package/dist/chunk-RG66XEJT.js +8 -0
  36. package/dist/chunk-SIFBBGY6.js +190 -0
  37. package/dist/chunk-SVEAENO7.js +22 -0
  38. package/dist/chunk-SY5244IR.js +1499 -0
  39. package/dist/chunk-W5HVJX45.js +402 -0
  40. package/dist/chunk-WIBGG4X6.js +173 -0
  41. package/dist/chunk-ZDWFBE5L.js +1 -0
  42. package/dist/chunk-ZINPRHAN.js +22 -0
  43. package/dist/deployer/index.cjs +165 -0
  44. package/dist/deployer/index.d.cts +19 -0
  45. package/dist/deployer/index.d.ts +19 -0
  46. package/dist/deployer/index.js +1 -0
  47. package/dist/eval/index.cjs +110 -0
  48. package/dist/eval/index.d.cts +28 -0
  49. package/dist/eval/index.d.ts +28 -0
  50. package/dist/eval/index.js +1 -0
  51. package/dist/filter/index.cjs +192 -0
  52. package/dist/filter/index.d.cts +90 -0
  53. package/dist/filter/index.d.ts +90 -0
  54. package/dist/filter/index.js +1 -0
  55. package/dist/hooks/index.cjs +87 -0
  56. package/dist/hooks/index.d.cts +33 -0
  57. package/dist/hooks/index.d.ts +33 -0
  58. package/dist/hooks/index.js +1 -0
  59. package/dist/index-mKY1XrpK.d.cts +90 -0
  60. package/dist/index-mKY1XrpK.d.ts +90 -0
  61. package/dist/index.cjs +6844 -0
  62. package/dist/index.d.cts +97 -0
  63. package/dist/index.d.ts +97 -0
  64. package/dist/index.js +119 -0
  65. package/dist/integration/index.cjs +113 -0
  66. package/dist/integration/index.d.cts +52 -0
  67. package/dist/integration/index.d.ts +52 -0
  68. package/dist/integration/index.js +1 -0
  69. package/dist/llm/index.cjs +2 -0
  70. package/dist/llm/index.d.cts +15 -0
  71. package/dist/llm/index.d.ts +15 -0
  72. package/dist/llm/index.js +1 -0
  73. package/dist/logger/index.cjs +159 -0
  74. package/dist/logger/index.d.cts +3 -0
  75. package/dist/logger/index.d.ts +3 -0
  76. package/dist/logger/index.js +1 -0
  77. package/dist/mastra/index.cjs +1741 -0
  78. package/dist/mastra/index.d.cts +67 -0
  79. package/dist/mastra/index.d.ts +67 -0
  80. package/dist/mastra/index.js +1 -0
  81. package/dist/memory/index.cjs +1907 -0
  82. package/dist/memory/index.d.cts +15 -0
  83. package/dist/memory/index.d.ts +15 -0
  84. package/dist/memory/index.js +1 -0
  85. package/dist/relevance/index.cjs +1927 -0
  86. package/dist/relevance/index.d.cts +21 -0
  87. package/dist/relevance/index.d.ts +21 -0
  88. package/dist/relevance/index.js +1 -0
  89. package/dist/storage/index.cjs +361 -0
  90. package/dist/storage/index.d.cts +15 -0
  91. package/dist/storage/index.d.ts +15 -0
  92. package/dist/storage/index.js +2 -0
  93. package/dist/storage/libsql/index.cjs +770 -0
  94. package/dist/storage/libsql/index.d.cts +81 -0
  95. package/dist/storage/libsql/index.d.ts +81 -0
  96. package/dist/storage/libsql/index.js +1 -0
  97. package/dist/telemetry/index.cjs +413 -0
  98. package/dist/telemetry/index.d.cts +51 -0
  99. package/dist/telemetry/index.d.ts +51 -0
  100. package/dist/telemetry/index.js +1 -0
  101. package/dist/telemetry/otel-vendor.cjs +52 -0
  102. package/dist/telemetry/otel-vendor.d.cts +7 -0
  103. package/dist/telemetry/otel-vendor.d.ts +7 -0
  104. package/dist/telemetry/otel-vendor.js +7 -0
  105. package/dist/tools/index.cjs +25 -0
  106. package/dist/tools/index.d.cts +29 -0
  107. package/dist/tools/index.d.ts +29 -0
  108. package/dist/tools/index.js +1 -0
  109. package/dist/tts/index.cjs +328 -0
  110. package/dist/tts/index.d.cts +28 -0
  111. package/dist/tts/index.d.ts +28 -0
  112. package/dist/tts/index.js +1 -0
  113. package/dist/types-m9RryK9a.d.cts +14 -0
  114. package/dist/types-m9RryK9a.d.ts +14 -0
  115. package/dist/utils.cjs +179 -0
  116. package/dist/utils.d.cts +26 -0
  117. package/dist/utils.d.ts +26 -0
  118. package/dist/utils.js +1 -0
  119. package/dist/vector/index.cjs +145 -0
  120. package/dist/vector/index.d.cts +30 -0
  121. package/dist/vector/index.d.ts +30 -0
  122. package/dist/vector/index.js +1 -0
  123. package/dist/vector/libsql/index.cjs +951 -0
  124. package/dist/vector/libsql/index.d.cts +29 -0
  125. package/dist/vector/libsql/index.d.ts +29 -0
  126. package/dist/vector/libsql/index.js +1 -0
  127. package/dist/voice/index.cjs +369 -0
  128. package/dist/voice/index.d.cts +67 -0
  129. package/dist/voice/index.d.ts +67 -0
  130. package/dist/voice/index.js +76 -0
  131. package/dist/workflow-DqQ4pON_.d.cts +84 -0
  132. package/dist/workflow-Ng_F_Zaf.d.ts +84 -0
  133. package/dist/workflows/index.cjs +1628 -0
  134. package/dist/workflows/index.d.cts +48 -0
  135. package/dist/workflows/index.d.ts +48 -0
  136. package/dist/workflows/index.js +1 -0
  137. package/package.json +162 -0
@@ -0,0 +1,770 @@
1
+ 'use strict';
2
+
3
+ var path = require('path');
4
+ var client = require('@libsql/client');
5
+ var stream = require('stream');
6
+ var pino = require('pino');
7
+ var pretty = require('pino-pretty');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var pino__default = /*#__PURE__*/_interopDefault(pino);
12
+ var pretty__default = /*#__PURE__*/_interopDefault(pretty);
13
+
14
+ // src/storage/libsql/index.ts
15
+ var RegisteredLogger = {
16
+ LLM: "LLM"};
17
+ var LogLevel = {
18
+ INFO: "info"};
19
+ var Logger = class {
20
+ logger;
21
+ transports;
22
+ constructor(options = {}) {
23
+ this.transports = options.transports || {};
24
+ const transportsAry = Object.entries(this.transports);
25
+ this.logger = pino__default.default(
26
+ {
27
+ name: options.name || "app",
28
+ level: options.level || LogLevel.INFO
29
+ },
30
+ options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? pretty__default.default({
31
+ colorize: true,
32
+ levelFirst: true,
33
+ ignore: "pid,hostname",
34
+ colorizeObjects: true,
35
+ translateTime: "SYS:standard",
36
+ singleLine: false
37
+ }) : pino__default.default.multistream([
38
+ ...transportsAry.map(([_, transport]) => ({
39
+ stream: transport,
40
+ level: options.level || LogLevel.INFO
41
+ })),
42
+ {
43
+ stream: pretty__default.default({
44
+ colorize: true,
45
+ levelFirst: true,
46
+ ignore: "pid,hostname",
47
+ colorizeObjects: true,
48
+ translateTime: "SYS:standard",
49
+ singleLine: false
50
+ }),
51
+ level: options.level || LogLevel.INFO
52
+ }
53
+ ])
54
+ );
55
+ }
56
+ debug(message, args = {}) {
57
+ this.logger.debug(args, message);
58
+ }
59
+ info(message, args = {}) {
60
+ this.logger.info(args, message);
61
+ }
62
+ warn(message, args = {}) {
63
+ this.logger.warn(args, message);
64
+ }
65
+ error(message, args = {}) {
66
+ this.logger.error(args, message);
67
+ }
68
+ // Stream creation for process output handling
69
+ createStream() {
70
+ return new stream.Transform({
71
+ transform: (chunk, _encoding, callback) => {
72
+ const line = chunk.toString().trim();
73
+ if (line) {
74
+ this.info(line);
75
+ }
76
+ callback(null, chunk);
77
+ }
78
+ });
79
+ }
80
+ async getLogs(transportId) {
81
+ if (!transportId || !this.transports[transportId]) {
82
+ return [];
83
+ }
84
+ return this.transports[transportId].getLogs();
85
+ }
86
+ async getLogsByRunId({ runId, transportId }) {
87
+ return this.transports[transportId]?.getLogsByRunId({ runId });
88
+ }
89
+ };
90
+ function createLogger(options) {
91
+ return new Logger(options);
92
+ }
93
+
94
+ // src/base.ts
95
+ var MastraBase = class {
96
+ component = RegisteredLogger.LLM;
97
+ logger;
98
+ name;
99
+ telemetry;
100
+ constructor({ component, name }) {
101
+ this.component = component || RegisteredLogger.LLM;
102
+ this.name = name;
103
+ this.logger = createLogger({ name: `${this.component} - ${this.name}` });
104
+ }
105
+ /**
106
+ * Set the logger for the agent
107
+ * @param logger
108
+ */
109
+ __setLogger(logger) {
110
+ this.logger = logger;
111
+ this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
112
+ }
113
+ /**
114
+ * Set the telemetry for the
115
+ * @param telemetry
116
+ */
117
+ __setTelemetry(telemetry) {
118
+ this.telemetry = telemetry;
119
+ this.logger.debug(`Telemetry updated [component=${this.component}] [tracer=${this.telemetry.tracer}]`);
120
+ }
121
+ /**
122
+ * Get the telemetry on the vector
123
+ * @returns telemetry
124
+ */
125
+ __getTelemetry() {
126
+ return this.telemetry;
127
+ }
128
+ /*
129
+ get experimental_telemetry config
130
+ */
131
+ get experimental_telemetry() {
132
+ return this.telemetry ? {
133
+ // tracer: this.telemetry.tracer,
134
+ tracer: this.telemetry.getBaggageTracer(),
135
+ isEnabled: !!this.telemetry.tracer
136
+ } : void 0;
137
+ }
138
+ };
139
+
140
+ // src/storage/constants.ts
141
+ var TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
142
+ var TABLE_EVALS = "mastra_evals";
143
+ var TABLE_MESSAGES = "mastra_messages";
144
+ var TABLE_THREADS = "mastra_threads";
145
+ var TABLE_TRACES = "mastra_traces";
146
+
147
+ // src/storage/base.ts
148
+ var MastraStorage = class extends MastraBase {
149
+ /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */
150
+ static TABLE_WORKFLOW_SNAPSHOT = TABLE_WORKFLOW_SNAPSHOT;
151
+ /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */
152
+ static TABLE_EVALS = TABLE_EVALS;
153
+ /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */
154
+ static TABLE_MESSAGES = TABLE_MESSAGES;
155
+ /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */
156
+ static TABLE_THREADS = TABLE_THREADS;
157
+ /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */
158
+ static TABLE_TRACES = TABLE_TRACES;
159
+ hasInitialized = null;
160
+ constructor({ name }) {
161
+ super({
162
+ component: "STORAGE",
163
+ name
164
+ });
165
+ }
166
+ async __batchInsert({
167
+ tableName,
168
+ records
169
+ }) {
170
+ await this.init();
171
+ return this.batchInsert({ tableName, records });
172
+ }
173
+ async __getThreadById({ threadId }) {
174
+ await this.init();
175
+ return this.getThreadById({ threadId });
176
+ }
177
+ async __getThreadsByResourceId({ resourceId }) {
178
+ await this.init();
179
+ return this.getThreadsByResourceId({ resourceId });
180
+ }
181
+ async __saveThread({ thread }) {
182
+ await this.init();
183
+ return this.saveThread({ thread });
184
+ }
185
+ async __updateThread({
186
+ id,
187
+ title,
188
+ metadata
189
+ }) {
190
+ await this.init();
191
+ return this.updateThread({ id, title, metadata });
192
+ }
193
+ async __deleteThread({ threadId }) {
194
+ await this.init();
195
+ return this.deleteThread({ threadId });
196
+ }
197
+ async __getMessages({ threadId, selectBy, threadConfig }) {
198
+ await this.init();
199
+ return this.getMessages({ threadId, selectBy, threadConfig });
200
+ }
201
+ async __saveMessages({ messages }) {
202
+ await this.init();
203
+ return this.saveMessages({ messages });
204
+ }
205
+ async __getTraces({
206
+ scope,
207
+ page,
208
+ perPage,
209
+ attributes
210
+ }) {
211
+ await this.init();
212
+ return this.getTraces({ scope, page, perPage, attributes });
213
+ }
214
+ async init() {
215
+ if (await this.hasInitialized) {
216
+ return;
217
+ }
218
+ this.hasInitialized = Promise.all([
219
+ this.createTable({
220
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
221
+ schema: {
222
+ workflow_name: {
223
+ type: "text"
224
+ },
225
+ run_id: {
226
+ type: "text"
227
+ },
228
+ snapshot: {
229
+ type: "text"
230
+ },
231
+ createdAt: {
232
+ type: "timestamp"
233
+ },
234
+ updatedAt: {
235
+ type: "timestamp"
236
+ }
237
+ }
238
+ }),
239
+ this.createTable({
240
+ tableName: TABLE_EVALS,
241
+ schema: {
242
+ input: {
243
+ type: "text"
244
+ },
245
+ output: {
246
+ type: "text"
247
+ },
248
+ result: {
249
+ type: "jsonb"
250
+ },
251
+ agent_name: {
252
+ type: "text"
253
+ },
254
+ metric_name: {
255
+ type: "text"
256
+ },
257
+ instructions: {
258
+ type: "text"
259
+ },
260
+ test_info: {
261
+ type: "jsonb",
262
+ nullable: true
263
+ },
264
+ global_run_id: {
265
+ type: "text"
266
+ },
267
+ run_id: {
268
+ type: "text"
269
+ },
270
+ created_at: {
271
+ type: "timestamp"
272
+ }
273
+ }
274
+ }),
275
+ this.createTable({
276
+ tableName: TABLE_THREADS,
277
+ schema: {
278
+ id: { type: "text", nullable: false, primaryKey: true },
279
+ resourceId: { type: "text", nullable: false },
280
+ title: { type: "text", nullable: false },
281
+ metadata: { type: "text", nullable: true },
282
+ createdAt: { type: "timestamp", nullable: false },
283
+ updatedAt: { type: "timestamp", nullable: false }
284
+ }
285
+ }),
286
+ this.createTable({
287
+ tableName: TABLE_MESSAGES,
288
+ schema: {
289
+ id: { type: "text", nullable: false, primaryKey: true },
290
+ thread_id: { type: "text", nullable: false },
291
+ content: { type: "text", nullable: false },
292
+ role: { type: "text", nullable: false },
293
+ type: { type: "text", nullable: false },
294
+ createdAt: { type: "timestamp", nullable: false }
295
+ }
296
+ }),
297
+ this.createTable({
298
+ tableName: TABLE_TRACES,
299
+ schema: {
300
+ id: { type: "text", nullable: false, primaryKey: true },
301
+ parentSpanId: { type: "text", nullable: true },
302
+ name: { type: "text", nullable: false },
303
+ traceId: { type: "text", nullable: false },
304
+ scope: { type: "text", nullable: false },
305
+ kind: { type: "integer", nullable: false },
306
+ attributes: { type: "jsonb", nullable: true },
307
+ status: { type: "jsonb", nullable: true },
308
+ events: { type: "jsonb", nullable: true },
309
+ links: { type: "jsonb", nullable: true },
310
+ other: { type: "text", nullable: true },
311
+ startTime: { type: "bigint", nullable: false },
312
+ endTime: { type: "bigint", nullable: false },
313
+ createdAt: { type: "timestamp", nullable: false }
314
+ }
315
+ })
316
+ ]).then(() => true);
317
+ await this.hasInitialized;
318
+ }
319
+ async persistWorkflowSnapshot({
320
+ workflowName,
321
+ runId,
322
+ snapshot
323
+ }) {
324
+ await this.init();
325
+ const data = {
326
+ workflow_name: workflowName,
327
+ run_id: runId,
328
+ snapshot,
329
+ createdAt: /* @__PURE__ */ new Date(),
330
+ updatedAt: /* @__PURE__ */ new Date()
331
+ };
332
+ this.logger.debug("Persisting workflow snapshot", { workflowName, runId, data });
333
+ await this.insert({
334
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
335
+ record: data
336
+ });
337
+ }
338
+ async loadWorkflowSnapshot({
339
+ workflowName,
340
+ runId
341
+ }) {
342
+ if (!this.hasInitialized) {
343
+ await this.init();
344
+ }
345
+ this.logger.debug("Loading workflow snapshot", { workflowName, runId });
346
+ const d = await this.load({
347
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
348
+ keys: { workflow_name: workflowName, run_id: runId }
349
+ });
350
+ return d ? d.snapshot : null;
351
+ }
352
+ async __getEvalsByAgentName(agentName, type) {
353
+ await this.init();
354
+ return this.getEvalsByAgentName(agentName, type);
355
+ }
356
+ };
357
+
358
+ // src/storage/libsql/index.ts
359
+ function safelyParseJSON(jsonString) {
360
+ try {
361
+ return JSON.parse(jsonString);
362
+ } catch {
363
+ return {};
364
+ }
365
+ }
366
+ var LibSQLStore = class extends MastraStorage {
367
+ client;
368
+ constructor({ config }) {
369
+ super({ name: `LibSQLStore` });
370
+ this.client = client.createClient({
371
+ url: this.rewriteDbUrl(config.url),
372
+ authToken: config.authToken
373
+ });
374
+ }
375
+ rewriteDbUrl(url) {
376
+ if (url.startsWith("file:") && !url.startsWith("file:/")) {
377
+ const cwd = process.cwd();
378
+ const relativePath = url.slice("file:".length);
379
+ if (cwd.endsWith(".mastra") || cwd.endsWith(".mastra/")) {
380
+ const baseDir = path.join(cwd, `..`);
381
+ const fullPath = path.join(baseDir, relativePath);
382
+ this.logger.debug(
383
+ `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.`
384
+ );
385
+ return `file:${fullPath}`;
386
+ }
387
+ }
388
+ return url;
389
+ }
390
+ getCreateTableSQL(tableName, schema) {
391
+ const columns = Object.entries(schema).map(([name, col]) => {
392
+ let type = col.type.toUpperCase();
393
+ if (type === "TEXT") type = "TEXT";
394
+ if (type === "TIMESTAMP") type = "TEXT";
395
+ const nullable = col.nullable ? "" : "NOT NULL";
396
+ const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
397
+ return `${name} ${type} ${nullable} ${primaryKey}`.trim();
398
+ });
399
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
400
+ const stmnt = `CREATE TABLE IF NOT EXISTS ${tableName} (
401
+ ${columns.join(",\n")},
402
+ PRIMARY KEY (workflow_name, run_id)
403
+ )`;
404
+ return stmnt;
405
+ }
406
+ return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
407
+ }
408
+ async createTable({
409
+ tableName,
410
+ schema
411
+ }) {
412
+ try {
413
+ this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
414
+ const sql = this.getCreateTableSQL(tableName, schema);
415
+ await this.client.execute(sql);
416
+ } catch (error) {
417
+ this.logger.error(`Error creating table ${tableName}: ${error}`);
418
+ throw error;
419
+ }
420
+ }
421
+ async clearTable({ tableName }) {
422
+ try {
423
+ await this.client.execute(`DELETE FROM ${tableName}`);
424
+ } catch (e) {
425
+ if (e instanceof Error) {
426
+ this.logger.error(e.message);
427
+ }
428
+ }
429
+ }
430
+ prepareStatement({ tableName, record }) {
431
+ const columns = Object.keys(record);
432
+ const values = Object.values(record).map((v) => {
433
+ if (typeof v === `undefined`) {
434
+ return null;
435
+ }
436
+ return typeof v === "object" ? JSON.stringify(v) : v;
437
+ });
438
+ const placeholders = values.map(() => "?").join(", ");
439
+ return {
440
+ sql: `INSERT OR REPLACE INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
441
+ args: values
442
+ };
443
+ }
444
+ async insert({ tableName, record }) {
445
+ try {
446
+ await this.client.execute(this.prepareStatement({ tableName, record }));
447
+ } catch (error) {
448
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
449
+ throw error;
450
+ }
451
+ }
452
+ async batchInsert({ tableName, records }) {
453
+ if (records.length === 0) return;
454
+ try {
455
+ const batchStatements = records.map((r) => this.prepareStatement({ tableName, record: r }));
456
+ await this.client.batch(batchStatements, "write");
457
+ } catch (error) {
458
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
459
+ throw error;
460
+ }
461
+ }
462
+ async load({ tableName, keys }) {
463
+ const conditions = Object.entries(keys).map(([key]) => `${key} = ?`).join(" AND ");
464
+ const values = Object.values(keys);
465
+ const result = await this.client.execute({
466
+ sql: `SELECT * FROM ${tableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
467
+ args: values
468
+ });
469
+ if (!result.rows || result.rows.length === 0) {
470
+ return null;
471
+ }
472
+ const row = result.rows[0];
473
+ const parsed = Object.fromEntries(
474
+ Object.entries(row || {}).map(([k, v]) => {
475
+ try {
476
+ return [k, typeof v === "string" ? JSON.parse(v) : v];
477
+ } catch {
478
+ return [k, v];
479
+ }
480
+ })
481
+ );
482
+ return parsed;
483
+ }
484
+ async getThreadById({ threadId }) {
485
+ const result = await this.load({
486
+ tableName: TABLE_THREADS,
487
+ keys: { id: threadId }
488
+ });
489
+ if (!result) {
490
+ return null;
491
+ }
492
+ return {
493
+ ...result,
494
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
495
+ };
496
+ }
497
+ async getThreadsByResourceId({ resourceId }) {
498
+ const result = await this.client.execute({
499
+ sql: `SELECT * FROM ${TABLE_THREADS} WHERE resourceId = ?`,
500
+ args: [resourceId]
501
+ });
502
+ if (!result.rows) {
503
+ return [];
504
+ }
505
+ return result.rows.map((thread) => ({
506
+ id: thread.id,
507
+ resourceId: thread.resourceId,
508
+ title: thread.title,
509
+ createdAt: thread.createdAt,
510
+ updatedAt: thread.updatedAt,
511
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
512
+ }));
513
+ }
514
+ async saveThread({ thread }) {
515
+ await this.insert({
516
+ tableName: TABLE_THREADS,
517
+ record: {
518
+ ...thread,
519
+ metadata: JSON.stringify(thread.metadata)
520
+ }
521
+ });
522
+ return thread;
523
+ }
524
+ async updateThread({
525
+ id,
526
+ title,
527
+ metadata
528
+ }) {
529
+ const thread = await this.getThreadById({ threadId: id });
530
+ if (!thread) {
531
+ throw new Error(`Thread ${id} not found`);
532
+ }
533
+ const updatedThread = {
534
+ ...thread,
535
+ title,
536
+ metadata: {
537
+ ...thread.metadata,
538
+ ...metadata
539
+ }
540
+ };
541
+ await this.client.execute({
542
+ sql: `UPDATE ${TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
543
+ args: [title, JSON.stringify(updatedThread.metadata), id]
544
+ });
545
+ return updatedThread;
546
+ }
547
+ async deleteThread({ threadId }) {
548
+ await this.client.execute({
549
+ sql: `DELETE FROM ${TABLE_THREADS} WHERE id = ?`,
550
+ args: [threadId]
551
+ });
552
+ }
553
+ parseRow(row) {
554
+ let content = row.content;
555
+ try {
556
+ content = JSON.parse(row.content);
557
+ } catch {
558
+ }
559
+ return {
560
+ id: row.id,
561
+ content,
562
+ role: row.role,
563
+ type: row.type,
564
+ createdAt: new Date(row.createdAt),
565
+ threadId: row.thread_id
566
+ };
567
+ }
568
+ async getMessages({ threadId, selectBy }) {
569
+ try {
570
+ const messages = [];
571
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
572
+ if (selectBy?.include?.length) {
573
+ const includeIds = selectBy.include.map((i) => i.id);
574
+ const maxPrev = Math.max(...selectBy.include.map((i) => i.withPreviousMessages || 0));
575
+ const maxNext = Math.max(...selectBy.include.map((i) => i.withNextMessages || 0));
576
+ const includeResult = await this.client.execute({
577
+ sql: `
578
+ WITH numbered_messages AS (
579
+ SELECT
580
+ id,
581
+ content,
582
+ role,
583
+ type,
584
+ "createdAt",
585
+ thread_id,
586
+ ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
587
+ FROM "${TABLE_MESSAGES}"
588
+ WHERE thread_id = ?
589
+ ),
590
+ target_positions AS (
591
+ SELECT row_num as target_pos
592
+ FROM numbered_messages
593
+ WHERE id IN (${includeIds.map(() => "?").join(", ")})
594
+ )
595
+ SELECT DISTINCT m.*
596
+ FROM numbered_messages m
597
+ CROSS JOIN target_positions t
598
+ WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
599
+ ORDER BY m."createdAt" ASC
600
+ `,
601
+ args: [threadId, ...includeIds, maxPrev, maxNext]
602
+ });
603
+ if (includeResult.rows) {
604
+ messages.push(...includeResult.rows.map((row) => this.parseRow(row)));
605
+ }
606
+ }
607
+ const excludeIds = messages.map((m) => m.id);
608
+ const remainingSql = `
609
+ SELECT
610
+ id,
611
+ content,
612
+ role,
613
+ type,
614
+ "createdAt",
615
+ thread_id
616
+ FROM "${TABLE_MESSAGES}"
617
+ WHERE thread_id = ?
618
+ ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
619
+ ORDER BY "createdAt" DESC
620
+ LIMIT ?
621
+ `;
622
+ const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
623
+ const remainingResult = await this.client.execute({
624
+ sql: remainingSql,
625
+ args: remainingArgs
626
+ });
627
+ if (remainingResult.rows) {
628
+ messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
629
+ }
630
+ messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
631
+ return messages;
632
+ } catch (error) {
633
+ this.logger.error("Error getting messages:", error);
634
+ throw error;
635
+ }
636
+ }
637
+ async saveMessages({ messages }) {
638
+ if (messages.length === 0) return messages;
639
+ const tx = await this.client.transaction("write");
640
+ try {
641
+ const threadId = messages[0]?.threadId;
642
+ if (!threadId) {
643
+ throw new Error("Thread ID is required");
644
+ }
645
+ for (const message of messages) {
646
+ const time = message.createdAt || /* @__PURE__ */ new Date();
647
+ await tx.execute({
648
+ sql: `INSERT INTO ${TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
649
+ VALUES (?, ?, ?, ?, ?, ?)`,
650
+ args: [
651
+ message.id,
652
+ threadId,
653
+ typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
654
+ message.role,
655
+ message.type,
656
+ time instanceof Date ? time.toISOString() : time
657
+ ]
658
+ });
659
+ }
660
+ await tx.commit();
661
+ return messages;
662
+ } catch (error) {
663
+ this.logger.error("Failed to save messages in database: " + error?.message);
664
+ await tx.rollback();
665
+ throw error;
666
+ }
667
+ }
668
+ transformEvalRow(row) {
669
+ const resultValue = JSON.parse(row.result);
670
+ const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
671
+ if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
672
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
673
+ }
674
+ return {
675
+ input: row.input,
676
+ output: row.output,
677
+ result: resultValue,
678
+ agentName: row.agent_name,
679
+ metricName: row.metric_name,
680
+ instructions: row.instructions,
681
+ testInfo: testInfoValue,
682
+ globalRunId: row.global_run_id,
683
+ runId: row.run_id,
684
+ createdAt: row.created_at
685
+ };
686
+ }
687
+ async getEvalsByAgentName(agentName, type) {
688
+ try {
689
+ const baseQuery = `SELECT * FROM ${TABLE_EVALS} WHERE agent_name = ?`;
690
+ 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)" : "";
691
+ const result = await this.client.execute({
692
+ sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
693
+ args: [agentName]
694
+ });
695
+ return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
696
+ } catch (error) {
697
+ if (error instanceof Error && error.message.includes("no such table")) {
698
+ return [];
699
+ }
700
+ this.logger.error("Failed to get evals for the specified agent: " + error?.message);
701
+ throw error;
702
+ }
703
+ }
704
+ // TODO: add types
705
+ async getTraces({
706
+ name,
707
+ scope,
708
+ page,
709
+ perPage,
710
+ attributes
711
+ } = {
712
+ page: 0,
713
+ perPage: 100
714
+ }) {
715
+ const limit = perPage;
716
+ const offset = page * perPage;
717
+ const args = [];
718
+ const conditions = [];
719
+ if (name) {
720
+ conditions.push("name LIKE CONCAT(?, '%')");
721
+ }
722
+ if (scope) {
723
+ conditions.push("scope = ?");
724
+ }
725
+ if (attributes) {
726
+ Object.keys(attributes).forEach((key) => {
727
+ conditions.push(`attributes->>'$.${key}' = ?`);
728
+ });
729
+ }
730
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
731
+ if (name) {
732
+ args.push(name);
733
+ }
734
+ if (scope) {
735
+ args.push(scope);
736
+ }
737
+ if (attributes) {
738
+ for (const [_key, value] of Object.entries(attributes)) {
739
+ args.push(value);
740
+ }
741
+ }
742
+ args.push(limit, offset);
743
+ const result = await this.client.execute({
744
+ sql: `SELECT * FROM ${TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
745
+ args
746
+ });
747
+ if (!result.rows) {
748
+ return [];
749
+ }
750
+ return result.rows.map((row) => ({
751
+ id: row.id,
752
+ parentSpanId: row.parentSpanId,
753
+ traceId: row.traceId,
754
+ name: row.name,
755
+ scope: row.scope,
756
+ kind: row.kind,
757
+ status: safelyParseJSON(row.status),
758
+ events: safelyParseJSON(row.events),
759
+ links: safelyParseJSON(row.links),
760
+ attributes: safelyParseJSON(row.attributes),
761
+ startTime: row.startTime,
762
+ endTime: row.endTime,
763
+ other: safelyParseJSON(row.other),
764
+ createdAt: row.createdAt
765
+ }));
766
+ }
767
+ };
768
+
769
+ exports.DefaultStorage = LibSQLStore;
770
+ exports.LibSQLStore = LibSQLStore;