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