@mastra/core 0.5.0 → 0.6.0-alpha.1

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 (59) hide show
  1. package/dist/agent/index.cjs +2 -2
  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-C_Oq53qk.d.ts → base-DA1J3qra.d.ts} +18 -8
  6. package/dist/{base-CIPKleAU.d.cts → base-zjGki2_Z.d.cts} +18 -8
  7. package/dist/{chunk-YPD6BQIM.js → chunk-22HQQDJZ.js} +36 -53
  8. package/dist/chunk-3LURIF6I.cjs +90 -0
  9. package/dist/{chunk-OD7ZMKHY.js → chunk-6ZHR5KIP.js} +93 -42
  10. package/dist/{chunk-KFQ7Z3PO.cjs → chunk-B3KTSEC5.cjs} +2 -2
  11. package/dist/{chunk-XF2FMJYK.js → chunk-DGYFNGOC.js} +1 -1
  12. package/dist/chunk-GMAMAKLH.js +88 -0
  13. package/dist/{chunk-OTFLHXHZ.cjs → chunk-L5BNMAC3.cjs} +2 -2
  14. package/dist/{chunk-KP5UAFLN.js → chunk-LTLNGEL2.js} +3 -1
  15. package/dist/{chunk-MLFXOST6.js → chunk-MLKXBAQG.js} +2 -2
  16. package/dist/{chunk-UZNQG7QO.cjs → chunk-N2G5ZI42.cjs} +93 -42
  17. package/dist/{chunk-3ASEZT7U.cjs → chunk-WX2ECXAE.cjs} +3 -1
  18. package/dist/{chunk-GXQRMKSN.cjs → chunk-XLZRGA3F.cjs} +35 -52
  19. package/dist/eval/index.d.cts +1 -1
  20. package/dist/eval/index.d.ts +1 -1
  21. package/dist/index.cjs +27 -27
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +6 -6
  25. package/dist/integration/index.d.cts +1 -1
  26. package/dist/integration/index.d.ts +1 -1
  27. package/dist/llm/index.d.cts +1 -1
  28. package/dist/llm/index.d.ts +1 -1
  29. package/dist/mastra/index.cjs +2 -2
  30. package/dist/mastra/index.d.cts +1 -1
  31. package/dist/mastra/index.d.ts +1 -1
  32. package/dist/mastra/index.js +1 -1
  33. package/dist/memory/index.cjs +2 -2
  34. package/dist/memory/index.d.cts +1 -1
  35. package/dist/memory/index.d.ts +1 -1
  36. package/dist/memory/index.js +1 -1
  37. package/dist/relevance/index.cjs +4 -4
  38. package/dist/relevance/index.d.cts +1 -1
  39. package/dist/relevance/index.d.ts +1 -1
  40. package/dist/relevance/index.js +1 -1
  41. package/dist/storage/index.d.cts +1 -1
  42. package/dist/storage/index.d.ts +1 -1
  43. package/dist/storage/libsql/index.cjs +440 -10
  44. package/dist/storage/libsql/index.d.cts +1 -1
  45. package/dist/storage/libsql/index.d.ts +1 -1
  46. package/dist/storage/libsql/index.js +441 -1
  47. package/dist/telemetry/index.d.cts +1 -1
  48. package/dist/telemetry/index.d.ts +1 -1
  49. package/dist/tools/index.d.cts +2 -2
  50. package/dist/tools/index.d.ts +2 -2
  51. package/dist/utils.d.cts +1 -1
  52. package/dist/utils.d.ts +1 -1
  53. package/dist/workflows/index.cjs +17 -17
  54. package/dist/workflows/index.d.cts +2 -2
  55. package/dist/workflows/index.d.ts +2 -2
  56. package/dist/workflows/index.js +1 -1
  57. package/package.json +5 -5
  58. package/dist/chunk-QAZ2ONKM.js +0 -441
  59. package/dist/chunk-VA4P7QJT.cjs +0 -443
@@ -1,441 +0,0 @@
1
- import { MastraStorage } from './chunk-7TZAPEAT.js';
2
- import { TABLE_WORKFLOW_SNAPSHOT, TABLE_THREADS, TABLE_MESSAGES, TABLE_EVALS, TABLE_TRACES } from './chunk-RG66XEJT.js';
3
- import { isAbsolute, join, resolve } from 'node:path';
4
- import { createClient } from '@libsql/client';
5
-
6
- function safelyParseJSON(jsonString) {
7
- try {
8
- return JSON.parse(jsonString);
9
- } catch {
10
- return {};
11
- }
12
- }
13
- var LibSQLStore = class extends MastraStorage {
14
- client;
15
- constructor({ config }) {
16
- super({ name: `LibSQLStore` });
17
- if (config.url === ":memory:") {
18
- this.shouldCacheInit = false;
19
- }
20
- this.client = createClient({
21
- url: this.rewriteDbUrl(config.url),
22
- authToken: config.authToken
23
- });
24
- }
25
- // If we're in the .mastra/output directory, use the dir outside .mastra dir
26
- // reason we need to do this is libsql relative file paths are based on cwd, not current file path
27
- // since mastra dev sets cwd to .mastra/output this means running an agent directly vs running with mastra dev
28
- // will put db files in different locations, leading to an inconsistent experience between the two.
29
- // Ex: with `file:ex.db`
30
- // 1. `mastra dev`: ${cwd}/.mastra/output/ex.db
31
- // 2. `tsx src/index.ts`: ${cwd}/ex.db
32
- // so if we're in .mastra/output we need to rewrite the file url to be relative to the project root dir
33
- // or the experience will be inconsistent
34
- // this means `file:` urls are always relative to project root
35
- // TODO: can we make this easier via bundling? https://github.com/mastra-ai/mastra/pull/2783#pullrequestreview-2662444241
36
- rewriteDbUrl(url) {
37
- if (url.startsWith("file:")) {
38
- const pathPart = url.slice("file:".length);
39
- if (isAbsolute(pathPart)) {
40
- return url;
41
- }
42
- const cwd = process.cwd();
43
- if (cwd.includes(".mastra") && (cwd.endsWith(`output`) || cwd.endsWith(`output/`) || cwd.endsWith(`output\\`))) {
44
- const baseDir = join(cwd, `..`, `..`);
45
- const fullPath = resolve(baseDir, pathPart);
46
- this.logger.debug(
47
- `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.`
48
- );
49
- return `file:${fullPath}`;
50
- }
51
- }
52
- return url;
53
- }
54
- getCreateTableSQL(tableName, schema) {
55
- const columns = Object.entries(schema).map(([name, col]) => {
56
- let type = col.type.toUpperCase();
57
- if (type === "TEXT") type = "TEXT";
58
- if (type === "TIMESTAMP") type = "TEXT";
59
- const nullable = col.nullable ? "" : "NOT NULL";
60
- const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
61
- return `${name} ${type} ${nullable} ${primaryKey}`.trim();
62
- });
63
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
64
- const stmnt = `CREATE TABLE IF NOT EXISTS ${tableName} (
65
- ${columns.join(",\n")},
66
- PRIMARY KEY (workflow_name, run_id)
67
- )`;
68
- return stmnt;
69
- }
70
- return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
71
- }
72
- async createTable({
73
- tableName,
74
- schema
75
- }) {
76
- try {
77
- this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
78
- const sql = this.getCreateTableSQL(tableName, schema);
79
- await this.client.execute(sql);
80
- } catch (error) {
81
- this.logger.error(`Error creating table ${tableName}: ${error}`);
82
- throw error;
83
- }
84
- }
85
- async clearTable({ tableName }) {
86
- try {
87
- await this.client.execute(`DELETE FROM ${tableName}`);
88
- } catch (e) {
89
- if (e instanceof Error) {
90
- this.logger.error(e.message);
91
- }
92
- }
93
- }
94
- prepareStatement({ tableName, record }) {
95
- const columns = Object.keys(record);
96
- const values = Object.values(record).map((v) => {
97
- if (typeof v === `undefined`) {
98
- return null;
99
- }
100
- if (v instanceof Date) {
101
- return v.toISOString();
102
- }
103
- return typeof v === "object" ? JSON.stringify(v) : v;
104
- });
105
- const placeholders = values.map(() => "?").join(", ");
106
- return {
107
- sql: `INSERT OR REPLACE INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
108
- args: values
109
- };
110
- }
111
- async insert({ tableName, record }) {
112
- try {
113
- await this.client.execute(
114
- this.prepareStatement({
115
- tableName,
116
- record
117
- })
118
- );
119
- } catch (error) {
120
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
121
- throw error;
122
- }
123
- }
124
- async batchInsert({ tableName, records }) {
125
- if (records.length === 0) return;
126
- try {
127
- const batchStatements = records.map((r) => this.prepareStatement({ tableName, record: r }));
128
- await this.client.batch(batchStatements, "write");
129
- } catch (error) {
130
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
131
- throw error;
132
- }
133
- }
134
- async load({ tableName, keys }) {
135
- const conditions = Object.entries(keys).map(([key]) => `${key} = ?`).join(" AND ");
136
- const values = Object.values(keys);
137
- const result = await this.client.execute({
138
- sql: `SELECT * FROM ${tableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
139
- args: values
140
- });
141
- if (!result.rows || result.rows.length === 0) {
142
- return null;
143
- }
144
- const row = result.rows[0];
145
- const parsed = Object.fromEntries(
146
- Object.entries(row || {}).map(([k, v]) => {
147
- try {
148
- return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
149
- } catch {
150
- return [k, v];
151
- }
152
- })
153
- );
154
- return parsed;
155
- }
156
- async getThreadById({ threadId }) {
157
- const result = await this.load({
158
- tableName: TABLE_THREADS,
159
- keys: { id: threadId }
160
- });
161
- if (!result) {
162
- return null;
163
- }
164
- return {
165
- ...result,
166
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
167
- };
168
- }
169
- async getThreadsByResourceId({ resourceId }) {
170
- const result = await this.client.execute({
171
- sql: `SELECT * FROM ${TABLE_THREADS} WHERE resourceId = ?`,
172
- args: [resourceId]
173
- });
174
- if (!result.rows) {
175
- return [];
176
- }
177
- return result.rows.map((thread) => ({
178
- id: thread.id,
179
- resourceId: thread.resourceId,
180
- title: thread.title,
181
- createdAt: thread.createdAt,
182
- updatedAt: thread.updatedAt,
183
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
184
- }));
185
- }
186
- async saveThread({ thread }) {
187
- await this.insert({
188
- tableName: TABLE_THREADS,
189
- record: {
190
- ...thread,
191
- metadata: JSON.stringify(thread.metadata)
192
- }
193
- });
194
- return thread;
195
- }
196
- async updateThread({
197
- id,
198
- title,
199
- metadata
200
- }) {
201
- const thread = await this.getThreadById({ threadId: id });
202
- if (!thread) {
203
- throw new Error(`Thread ${id} not found`);
204
- }
205
- const updatedThread = {
206
- ...thread,
207
- title,
208
- metadata: {
209
- ...thread.metadata,
210
- ...metadata
211
- }
212
- };
213
- await this.client.execute({
214
- sql: `UPDATE ${TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
215
- args: [title, JSON.stringify(updatedThread.metadata), id]
216
- });
217
- return updatedThread;
218
- }
219
- async deleteThread({ threadId }) {
220
- await this.client.execute({
221
- sql: `DELETE FROM ${TABLE_THREADS} WHERE id = ?`,
222
- args: [threadId]
223
- });
224
- }
225
- parseRow(row) {
226
- let content = row.content;
227
- try {
228
- content = JSON.parse(row.content);
229
- } catch {
230
- }
231
- return {
232
- id: row.id,
233
- content,
234
- role: row.role,
235
- type: row.type,
236
- createdAt: new Date(row.createdAt),
237
- threadId: row.thread_id
238
- };
239
- }
240
- async getMessages({ threadId, selectBy }) {
241
- try {
242
- const messages = [];
243
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
244
- if (selectBy?.include?.length) {
245
- const includeIds = selectBy.include.map((i) => i.id);
246
- const maxPrev = Math.max(...selectBy.include.map((i) => i.withPreviousMessages || 0));
247
- const maxNext = Math.max(...selectBy.include.map((i) => i.withNextMessages || 0));
248
- const includeResult = await this.client.execute({
249
- sql: `
250
- WITH numbered_messages AS (
251
- SELECT
252
- id,
253
- content,
254
- role,
255
- type,
256
- "createdAt",
257
- thread_id,
258
- ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
259
- FROM "${TABLE_MESSAGES}"
260
- WHERE thread_id = ?
261
- ),
262
- target_positions AS (
263
- SELECT row_num as target_pos
264
- FROM numbered_messages
265
- WHERE id IN (${includeIds.map(() => "?").join(", ")})
266
- )
267
- SELECT DISTINCT m.*
268
- FROM numbered_messages m
269
- CROSS JOIN target_positions t
270
- WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
271
- ORDER BY m."createdAt" ASC
272
- `,
273
- args: [threadId, ...includeIds, maxPrev, maxNext]
274
- });
275
- if (includeResult.rows) {
276
- messages.push(...includeResult.rows.map((row) => this.parseRow(row)));
277
- }
278
- }
279
- const excludeIds = messages.map((m) => m.id);
280
- const remainingSql = `
281
- SELECT
282
- id,
283
- content,
284
- role,
285
- type,
286
- "createdAt",
287
- thread_id
288
- FROM "${TABLE_MESSAGES}"
289
- WHERE thread_id = ?
290
- ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
291
- ORDER BY "createdAt" DESC
292
- LIMIT ?
293
- `;
294
- const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
295
- const remainingResult = await this.client.execute({
296
- sql: remainingSql,
297
- args: remainingArgs
298
- });
299
- if (remainingResult.rows) {
300
- messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
301
- }
302
- messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
303
- return messages;
304
- } catch (error) {
305
- this.logger.error("Error getting messages:", error);
306
- throw error;
307
- }
308
- }
309
- async saveMessages({ messages }) {
310
- if (messages.length === 0) return messages;
311
- const tx = await this.client.transaction("write");
312
- try {
313
- const threadId = messages[0]?.threadId;
314
- if (!threadId) {
315
- throw new Error("Thread ID is required");
316
- }
317
- for (const message of messages) {
318
- const time = message.createdAt || /* @__PURE__ */ new Date();
319
- await tx.execute({
320
- sql: `INSERT INTO ${TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
321
- VALUES (?, ?, ?, ?, ?, ?)`,
322
- args: [
323
- message.id,
324
- threadId,
325
- typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
326
- message.role,
327
- message.type,
328
- time instanceof Date ? time.toISOString() : time
329
- ]
330
- });
331
- }
332
- await tx.commit();
333
- return messages;
334
- } catch (error) {
335
- this.logger.error("Failed to save messages in database: " + error?.message);
336
- await tx.rollback();
337
- throw error;
338
- }
339
- }
340
- transformEvalRow(row) {
341
- const resultValue = JSON.parse(row.result);
342
- const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
343
- if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
344
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
345
- }
346
- return {
347
- input: row.input,
348
- output: row.output,
349
- result: resultValue,
350
- agentName: row.agent_name,
351
- metricName: row.metric_name,
352
- instructions: row.instructions,
353
- testInfo: testInfoValue,
354
- globalRunId: row.global_run_id,
355
- runId: row.run_id,
356
- createdAt: row.created_at
357
- };
358
- }
359
- async getEvalsByAgentName(agentName, type) {
360
- try {
361
- const baseQuery = `SELECT * FROM ${TABLE_EVALS} WHERE agent_name = ?`;
362
- 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)" : "";
363
- const result = await this.client.execute({
364
- sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
365
- args: [agentName]
366
- });
367
- return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
368
- } catch (error) {
369
- if (error instanceof Error && error.message.includes("no such table")) {
370
- return [];
371
- }
372
- this.logger.error("Failed to get evals for the specified agent: " + error?.message);
373
- throw error;
374
- }
375
- }
376
- // TODO: add types
377
- async getTraces({
378
- name,
379
- scope,
380
- page,
381
- perPage,
382
- attributes
383
- } = {
384
- page: 0,
385
- perPage: 100
386
- }) {
387
- const limit = perPage;
388
- const offset = page * perPage;
389
- const args = [];
390
- const conditions = [];
391
- if (name) {
392
- conditions.push("name LIKE CONCAT(?, '%')");
393
- }
394
- if (scope) {
395
- conditions.push("scope = ?");
396
- }
397
- if (attributes) {
398
- Object.keys(attributes).forEach((key) => {
399
- conditions.push(`attributes->>'$.${key}' = ?`);
400
- });
401
- }
402
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
403
- if (name) {
404
- args.push(name);
405
- }
406
- if (scope) {
407
- args.push(scope);
408
- }
409
- if (attributes) {
410
- for (const [_key, value] of Object.entries(attributes)) {
411
- args.push(value);
412
- }
413
- }
414
- args.push(limit, offset);
415
- const result = await this.client.execute({
416
- sql: `SELECT * FROM ${TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
417
- args
418
- });
419
- if (!result.rows) {
420
- return [];
421
- }
422
- return result.rows.map((row) => ({
423
- id: row.id,
424
- parentSpanId: row.parentSpanId,
425
- traceId: row.traceId,
426
- name: row.name,
427
- scope: row.scope,
428
- kind: row.kind,
429
- status: safelyParseJSON(row.status),
430
- events: safelyParseJSON(row.events),
431
- links: safelyParseJSON(row.links),
432
- attributes: safelyParseJSON(row.attributes),
433
- startTime: row.startTime,
434
- endTime: row.endTime,
435
- other: safelyParseJSON(row.other),
436
- createdAt: row.createdAt
437
- }));
438
- }
439
- };
440
-
441
- export { LibSQLStore };