@mastra/core 0.9.4 → 0.10.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 (168) hide show
  1. package/README.md +3 -2
  2. package/dist/agent/index.cjs +2 -2
  3. package/dist/agent/index.d.cts +13 -14
  4. package/dist/agent/index.d.ts +13 -14
  5. package/dist/agent/index.js +1 -1
  6. package/dist/{base-BCfssGt6.d.ts → base-DttB7sJD.d.ts} +1187 -886
  7. package/dist/{base-CAEcd6q2.d.cts → base-aJ3etsh5.d.cts} +1187 -886
  8. package/dist/{base-H7siSAfu.d.cts → base-aPYtPBT2.d.cts} +3 -3
  9. package/dist/{base-4Z34GQL8.d.ts → base-tc5kgDTD.d.ts} +3 -3
  10. package/dist/base.cjs +2 -2
  11. package/dist/base.d.cts +2 -3
  12. package/dist/base.d.ts +2 -3
  13. package/dist/base.js +1 -1
  14. package/dist/bundler/index.cjs +2 -2
  15. package/dist/bundler/index.d.cts +2 -3
  16. package/dist/bundler/index.d.ts +2 -3
  17. package/dist/bundler/index.js +1 -1
  18. package/dist/{chunk-W4BSLENO.js → chunk-2NTUAUGH.js} +1 -1
  19. package/dist/{chunk-S34QVMKE.js → chunk-2PW6UJMW.js} +77 -10
  20. package/dist/{chunk-WE36CRQV.cjs → chunk-2U7ZZUFO.cjs} +2 -2
  21. package/dist/{workflows/vNext/index.js → chunk-3SQ3G2EJ.js} +19 -16
  22. package/dist/chunk-5HULBQ2W.cjs +38 -0
  23. package/dist/{chunk-XRGDVLM4.cjs → chunk-5JRD3NDP.cjs} +15 -15
  24. package/dist/{chunk-GXKODTLA.cjs → chunk-5W2G7S44.cjs} +83 -68
  25. package/dist/chunk-75Z4BZEE.js +36 -0
  26. package/dist/{chunk-66GQROSI.cjs → chunk-AOGUTJUO.cjs} +58 -51
  27. package/dist/{chunk-WIKOYZ63.js → chunk-BPTSLJHA.js} +9 -9
  28. package/dist/{chunk-JBJ7KXN5.js → chunk-C3ICEF6E.js} +1 -1
  29. package/dist/{chunk-E4FAXBUV.cjs → chunk-CWSFP2HS.cjs} +2 -2
  30. package/dist/{chunk-FW5RS6WV.js → chunk-E7CLY6SK.js} +42 -35
  31. package/dist/{chunk-235X76GC.js → chunk-FI7R232B.js} +2 -2
  32. package/dist/chunk-GQ2XQ4UN.js +321 -0
  33. package/dist/{chunk-H4CEZSRM.js → chunk-J7GDGV6F.js} +1 -1
  34. package/dist/{chunk-NLBJOFNG.js → chunk-JW5TMK2L.js} +1 -1
  35. package/dist/{chunk-NOPY74PV.js → chunk-KJQFFEEQ.js} +1 -1
  36. package/dist/{chunk-V2Q2FEVO.cjs → chunk-KSPHQSZX.cjs} +2 -2
  37. package/dist/{chunk-NZV4OA6P.js → chunk-LHRZV5VG.js} +2 -23
  38. package/dist/chunk-NMDM4IZN.cjs +78 -0
  39. package/dist/chunk-OBEALYTK.js +74 -0
  40. package/dist/{chunk-PEK4TY3P.js → chunk-OCT2762Q.js} +1 -1
  41. package/dist/{chunk-5DUFC7TV.cjs → chunk-P7BGXOQV.cjs} +2 -2
  42. package/dist/{chunk-WQKOM7XM.cjs → chunk-PIZM25KI.cjs} +3 -24
  43. package/dist/{chunk-S7J63JOG.cjs → chunk-RVS6OUJN.cjs} +2 -2
  44. package/dist/{chunk-5JUWUTPJ.cjs → chunk-SKG2NIZW.cjs} +2 -2
  45. package/dist/chunk-SWW4EBUZ.cjs +96 -0
  46. package/dist/{chunk-RGE4UF6A.cjs → chunk-TMPFLJLG.cjs} +2 -2
  47. package/dist/{workflows/vNext/index.cjs → chunk-TTKQ37ZZ.cjs} +24 -21
  48. package/dist/{chunk-EJITEVAB.cjs → chunk-U3L3NEOM.cjs} +81 -10
  49. package/dist/chunk-VHLL4AZK.js +90 -0
  50. package/dist/{chunk-EG74VBSP.cjs → chunk-YEULQPUY.cjs} +6 -6
  51. package/dist/{chunk-SOLXHDNQ.js → chunk-ZB3LEHL2.js} +81 -66
  52. package/dist/{chunk-TAFOICHR.js → chunk-ZKN6HYYQ.js} +1 -1
  53. package/dist/chunk-ZZDAC5KD.cjs +325 -0
  54. package/dist/deployer/index.cjs +2 -2
  55. package/dist/deployer/index.d.cts +2 -3
  56. package/dist/deployer/index.d.ts +2 -3
  57. package/dist/deployer/index.js +1 -1
  58. package/dist/eval/index.d.cts +13 -14
  59. package/dist/eval/index.d.ts +13 -14
  60. package/dist/hooks/index.d.cts +1 -1
  61. package/dist/hooks/index.d.ts +1 -1
  62. package/dist/index.cjs +88 -159
  63. package/dist/index.d.cts +17 -25
  64. package/dist/index.d.ts +17 -25
  65. package/dist/index.js +18 -25
  66. package/dist/integration/index.cjs +3 -3
  67. package/dist/integration/index.d.cts +12 -13
  68. package/dist/integration/index.d.ts +12 -13
  69. package/dist/integration/index.js +1 -1
  70. package/dist/llm/index.d.cts +13 -14
  71. package/dist/llm/index.d.ts +13 -14
  72. package/dist/logger/index.cjs +18 -17
  73. package/dist/logger/index.d.cts +42 -2
  74. package/dist/logger/index.d.ts +42 -2
  75. package/dist/logger/index.js +2 -1
  76. package/dist/{index-QV27jkxQ.d.ts → logger-EhZkzZOr.d.cts} +38 -52
  77. package/dist/{index-QV27jkxQ.d.cts → logger-EhZkzZOr.d.ts} +38 -52
  78. package/dist/mastra/index.cjs +2 -2
  79. package/dist/mastra/index.d.cts +11 -12
  80. package/dist/mastra/index.d.ts +11 -12
  81. package/dist/mastra/index.js +1 -1
  82. package/dist/mcp/index.cjs +75 -17
  83. package/dist/mcp/index.d.cts +14 -15
  84. package/dist/mcp/index.d.ts +14 -15
  85. package/dist/mcp/index.js +69 -15
  86. package/dist/memory/index.cjs +4 -4
  87. package/dist/memory/index.d.cts +12 -13
  88. package/dist/memory/index.d.ts +12 -13
  89. package/dist/memory/index.js +1 -1
  90. package/dist/network/index.cjs +8 -8
  91. package/dist/network/index.d.cts +12 -13
  92. package/dist/network/index.d.ts +12 -13
  93. package/dist/network/index.js +5 -5
  94. package/dist/relevance/index.cjs +4 -4
  95. package/dist/relevance/index.d.cts +15 -16
  96. package/dist/relevance/index.d.ts +15 -16
  97. package/dist/relevance/index.js +1 -1
  98. package/dist/server/index.cjs +4 -0
  99. package/dist/server/index.d.cts +13 -12
  100. package/dist/server/index.d.ts +13 -12
  101. package/dist/server/index.js +4 -1
  102. package/dist/storage/index.cjs +184 -3
  103. package/dist/storage/index.d.cts +83 -13
  104. package/dist/storage/index.d.ts +83 -13
  105. package/dist/storage/index.js +186 -1
  106. package/dist/telemetry/index.d.cts +14 -15
  107. package/dist/telemetry/index.d.ts +14 -15
  108. package/dist/telemetry/otel-vendor.cjs +2 -2
  109. package/dist/telemetry/otel-vendor.d.cts +1 -1
  110. package/dist/telemetry/otel-vendor.d.ts +1 -1
  111. package/dist/telemetry/otel-vendor.js +1 -1
  112. package/dist/tools/index.cjs +4 -4
  113. package/dist/tools/index.d.cts +12 -13
  114. package/dist/tools/index.d.ts +12 -13
  115. package/dist/tools/index.js +1 -1
  116. package/dist/tts/index.cjs +2 -2
  117. package/dist/tts/index.d.cts +2 -3
  118. package/dist/tts/index.d.ts +2 -3
  119. package/dist/tts/index.js +1 -1
  120. package/dist/{types-BtMyV38I.d.ts → types-Bo1uigWx.d.cts} +1 -1
  121. package/dist/{types-BtMyV38I.d.cts → types-Bo1uigWx.d.ts} +1 -1
  122. package/dist/utils.cjs +28 -12
  123. package/dist/utils.d.cts +59 -16
  124. package/dist/utils.d.ts +59 -16
  125. package/dist/utils.js +1 -1
  126. package/dist/vector/filter/index.cjs +189 -7
  127. package/dist/vector/filter/index.js +190 -1
  128. package/dist/vector/index.cjs +2 -2
  129. package/dist/vector/index.d.cts +28 -20
  130. package/dist/vector/index.d.ts +28 -20
  131. package/dist/vector/index.js +1 -1
  132. package/dist/voice/index.cjs +4 -4
  133. package/dist/voice/index.d.cts +12 -13
  134. package/dist/voice/index.d.ts +12 -13
  135. package/dist/voice/index.js +1 -1
  136. package/dist/workflows/index.cjs +17 -69
  137. package/dist/workflows/index.d.cts +197 -77
  138. package/dist/workflows/index.d.ts +197 -77
  139. package/dist/workflows/index.js +1 -1
  140. package/dist/workflows/legacy/index.cjs +90 -0
  141. package/dist/workflows/legacy/index.d.cts +87 -0
  142. package/dist/workflows/legacy/index.d.ts +87 -0
  143. package/dist/workflows/legacy/index.js +1 -0
  144. package/package.json +19 -40
  145. package/workflows/legacy.d.ts +1 -0
  146. package/dist/chunk-4WABQORE.js +0 -781
  147. package/dist/chunk-CIEPFV6B.js +0 -658
  148. package/dist/chunk-CMPPXW4U.js +0 -154
  149. package/dist/chunk-CTKNWYK2.js +0 -131
  150. package/dist/chunk-LGERQTJM.js +0 -190
  151. package/dist/chunk-O44MSFMZ.cjs +0 -168
  152. package/dist/chunk-QDAMIZY3.cjs +0 -783
  153. package/dist/chunk-QHDPLMHB.cjs +0 -667
  154. package/dist/chunk-RAQBTCIR.cjs +0 -134
  155. package/dist/chunk-YK3XJ52U.cjs +0 -192
  156. package/dist/storage/libsql/index.cjs +0 -581
  157. package/dist/storage/libsql/index.d.cts +0 -104
  158. package/dist/storage/libsql/index.d.ts +0 -104
  159. package/dist/storage/libsql/index.js +0 -578
  160. package/dist/vector/libsql/index.cjs +0 -14
  161. package/dist/vector/libsql/index.d.cts +0 -82
  162. package/dist/vector/libsql/index.d.ts +0 -82
  163. package/dist/vector/libsql/index.js +0 -1
  164. package/dist/workflows/vNext/index.d.cts +0 -209
  165. package/dist/workflows/vNext/index.d.ts +0 -209
  166. package/storage/libsql.d.ts +0 -1
  167. package/vector/libsql.d.ts +0 -1
  168. package/workflows/vNext.d.ts +0 -1
@@ -1,581 +0,0 @@
1
- 'use strict';
2
-
3
- var chunk5DUFC7TV_cjs = require('../../chunk-5DUFC7TV.cjs');
4
- var chunk6KB5CPBV_cjs = require('../../chunk-6KB5CPBV.cjs');
5
- var path = require('path');
6
- var client = require('@libsql/client');
7
-
8
- function safelyParseJSON(jsonString) {
9
- try {
10
- return JSON.parse(jsonString);
11
- } catch {
12
- return {};
13
- }
14
- }
15
- var hasWarned = false;
16
- function warnDeprecation(logger) {
17
- if (hasWarned) return;
18
- hasWarned = true;
19
- logger?.warn(`The default storage is deprecated, please add any storage to Mastra itself.
20
-
21
- In \`src/mastra/index.ts\` add:
22
- Import { LibSQLStore } from \`@mastra/libsql\`.
23
-
24
- export const mastra = new Mastra({
25
- // other config
26
- storage: new LibSQLStore({
27
- url: 'file:../mastra.db',
28
- }),
29
- }
30
- `);
31
- }
32
- var LibSQLStore = class extends chunk5DUFC7TV_cjs.MastraStorage {
33
- client;
34
- constructor({ config }) {
35
- super({ name: `LibSQLStore` });
36
- if (config.url === ":memory:" || config.url.startsWith("file::memory:")) {
37
- this.shouldCacheInit = false;
38
- }
39
- this.client = client.createClient({
40
- url: this.rewriteDbUrl(config.url),
41
- authToken: config.authToken
42
- });
43
- }
44
- // If we're in the .mastra/output directory, use the dir outside .mastra dir
45
- // reason we need to do this is libsql relative file paths are based on cwd, not current file path
46
- // since mastra dev sets cwd to .mastra/output this means running an agent directly vs running with mastra dev
47
- // will put db files in different locations, leading to an inconsistent experience between the two.
48
- // Ex: with `file:ex.db`
49
- // 1. `mastra dev`: ${cwd}/.mastra/output/ex.db
50
- // 2. `tsx src/index.ts`: ${cwd}/ex.db
51
- // so if we're in .mastra/output we need to rewrite the file url to be relative to the project root dir
52
- // or the experience will be inconsistent
53
- // this means `file:` urls are always relative to project root
54
- // TODO: can we make this easier via bundling? https://github.com/mastra-ai/mastra/pull/2783#pullrequestreview-2662444241
55
- rewriteDbUrl(url) {
56
- if (url.startsWith("file:") && url !== "file::memory:") {
57
- const pathPart = url.slice("file:".length);
58
- if (path.isAbsolute(pathPart)) {
59
- return url;
60
- }
61
- const cwd = process.cwd();
62
- if (cwd.includes(".mastra") && (cwd.endsWith(`output`) || cwd.endsWith(`output/`) || cwd.endsWith(`output\\`))) {
63
- const baseDir = path.join(cwd, `..`, `..`);
64
- const fullPath = path.resolve(baseDir, pathPart);
65
- this.logger.debug(
66
- `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.`
67
- );
68
- return `file:${fullPath}`;
69
- }
70
- }
71
- return url;
72
- }
73
- getCreateTableSQL(tableName, schema) {
74
- const columns = Object.entries(schema).map(([name, col]) => {
75
- let type = col.type.toUpperCase();
76
- if (type === "TEXT") type = "TEXT";
77
- if (type === "TIMESTAMP") type = "TEXT";
78
- const nullable = col.nullable ? "" : "NOT NULL";
79
- const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
80
- return `${name} ${type} ${nullable} ${primaryKey}`.trim();
81
- });
82
- if (tableName === chunk6KB5CPBV_cjs.TABLE_WORKFLOW_SNAPSHOT) {
83
- const stmnt = `CREATE TABLE IF NOT EXISTS ${tableName} (
84
- ${columns.join(",\n")},
85
- PRIMARY KEY (workflow_name, run_id)
86
- )`;
87
- return stmnt;
88
- }
89
- return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
90
- }
91
- async createTable({
92
- tableName,
93
- schema
94
- }) {
95
- try {
96
- this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
97
- const sql = this.getCreateTableSQL(tableName, schema);
98
- await this.client.execute(sql);
99
- } catch (error) {
100
- this.logger.error(`Error creating table ${tableName}: ${error}`);
101
- throw error;
102
- }
103
- }
104
- async clearTable({ tableName }) {
105
- try {
106
- await this.client.execute(`DELETE FROM ${tableName}`);
107
- } catch (e) {
108
- if (e instanceof Error) {
109
- this.logger.error(e.message);
110
- }
111
- }
112
- }
113
- prepareStatement({ tableName, record }) {
114
- const columns = Object.keys(record);
115
- const values = Object.values(record).map((v) => {
116
- if (typeof v === `undefined`) {
117
- return null;
118
- }
119
- if (v instanceof Date) {
120
- return v.toISOString();
121
- }
122
- return typeof v === "object" ? JSON.stringify(v) : v;
123
- });
124
- const placeholders = values.map(() => "?").join(", ");
125
- return {
126
- sql: `INSERT OR REPLACE INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
127
- args: values
128
- };
129
- }
130
- async insert({ tableName, record }) {
131
- warnDeprecation(this.logger);
132
- try {
133
- await this.client.execute(
134
- this.prepareStatement({
135
- tableName,
136
- record
137
- })
138
- );
139
- } catch (error) {
140
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
141
- throw error;
142
- }
143
- }
144
- async batchInsert({ tableName, records }) {
145
- if (records.length === 0) return;
146
- warnDeprecation(this.logger);
147
- try {
148
- const batchStatements = records.map((r) => this.prepareStatement({ tableName, record: r }));
149
- await this.client.batch(batchStatements, "write");
150
- } catch (error) {
151
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
152
- throw error;
153
- }
154
- }
155
- async load({ tableName, keys }) {
156
- const conditions = Object.entries(keys).map(([key]) => `${key} = ?`).join(" AND ");
157
- const values = Object.values(keys);
158
- const result = await this.client.execute({
159
- sql: `SELECT * FROM ${tableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
160
- args: values
161
- });
162
- if (!result.rows || result.rows.length === 0) {
163
- return null;
164
- }
165
- const row = result.rows[0];
166
- const parsed = Object.fromEntries(
167
- Object.entries(row || {}).map(([k, v]) => {
168
- try {
169
- return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
170
- } catch {
171
- return [k, v];
172
- }
173
- })
174
- );
175
- return parsed;
176
- }
177
- async getThreadById({ threadId }) {
178
- const result = await this.load({
179
- tableName: chunk6KB5CPBV_cjs.TABLE_THREADS,
180
- keys: { id: threadId }
181
- });
182
- if (!result) {
183
- return null;
184
- }
185
- return {
186
- ...result,
187
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
188
- };
189
- }
190
- async getThreadsByResourceId({ resourceId }) {
191
- const result = await this.client.execute({
192
- sql: `SELECT * FROM ${chunk6KB5CPBV_cjs.TABLE_THREADS} WHERE resourceId = ?`,
193
- args: [resourceId]
194
- });
195
- if (!result.rows) {
196
- return [];
197
- }
198
- return result.rows.map((thread) => ({
199
- id: thread.id,
200
- resourceId: thread.resourceId,
201
- title: thread.title,
202
- createdAt: thread.createdAt,
203
- updatedAt: thread.updatedAt,
204
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
205
- }));
206
- }
207
- async saveThread({ thread }) {
208
- await this.insert({
209
- tableName: chunk6KB5CPBV_cjs.TABLE_THREADS,
210
- record: {
211
- ...thread,
212
- metadata: JSON.stringify(thread.metadata)
213
- }
214
- });
215
- return thread;
216
- }
217
- async updateThread({
218
- id,
219
- title,
220
- metadata
221
- }) {
222
- const thread = await this.getThreadById({ threadId: id });
223
- if (!thread) {
224
- throw new Error(`Thread ${id} not found`);
225
- }
226
- const updatedThread = {
227
- ...thread,
228
- title,
229
- metadata: {
230
- ...thread.metadata,
231
- ...metadata
232
- }
233
- };
234
- await this.client.execute({
235
- sql: `UPDATE ${chunk6KB5CPBV_cjs.TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
236
- args: [title, JSON.stringify(updatedThread.metadata), id]
237
- });
238
- return updatedThread;
239
- }
240
- async deleteThread({ threadId }) {
241
- await this.client.execute({
242
- sql: `DELETE FROM ${chunk6KB5CPBV_cjs.TABLE_THREADS} WHERE id = ?`,
243
- args: [threadId]
244
- });
245
- }
246
- parseRow(row) {
247
- let content = row.content;
248
- try {
249
- content = JSON.parse(row.content);
250
- } catch {
251
- }
252
- return {
253
- id: row.id,
254
- content,
255
- role: row.role,
256
- type: row.type,
257
- createdAt: new Date(row.createdAt),
258
- threadId: row.thread_id
259
- };
260
- }
261
- async getMessages({ threadId, selectBy }) {
262
- try {
263
- const messages = [];
264
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
265
- if (selectBy?.include?.length) {
266
- const includeIds = selectBy.include.map((i) => i.id);
267
- const maxPrev = Math.max(...selectBy.include.map((i) => i.withPreviousMessages || 0));
268
- const maxNext = Math.max(...selectBy.include.map((i) => i.withNextMessages || 0));
269
- const includeResult = await this.client.execute({
270
- sql: `
271
- WITH numbered_messages AS (
272
- SELECT
273
- id,
274
- content,
275
- role,
276
- type,
277
- "createdAt",
278
- thread_id,
279
- ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
280
- FROM "${chunk6KB5CPBV_cjs.TABLE_MESSAGES}"
281
- WHERE thread_id = ?
282
- ),
283
- target_positions AS (
284
- SELECT row_num as target_pos
285
- FROM numbered_messages
286
- WHERE id IN (${includeIds.map(() => "?").join(", ")})
287
- )
288
- SELECT DISTINCT m.*
289
- FROM numbered_messages m
290
- CROSS JOIN target_positions t
291
- WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
292
- ORDER BY m."createdAt" ASC
293
- `,
294
- args: [threadId, ...includeIds, maxPrev, maxNext]
295
- });
296
- if (includeResult.rows) {
297
- messages.push(...includeResult.rows.map((row) => this.parseRow(row)));
298
- }
299
- }
300
- const excludeIds = messages.map((m) => m.id);
301
- const remainingSql = `
302
- SELECT
303
- id,
304
- content,
305
- role,
306
- type,
307
- "createdAt",
308
- thread_id
309
- FROM "${chunk6KB5CPBV_cjs.TABLE_MESSAGES}"
310
- WHERE thread_id = ?
311
- ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
312
- ORDER BY "createdAt" DESC
313
- LIMIT ?
314
- `;
315
- const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
316
- const remainingResult = await this.client.execute({
317
- sql: remainingSql,
318
- args: remainingArgs
319
- });
320
- if (remainingResult.rows) {
321
- messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
322
- }
323
- messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
324
- return messages;
325
- } catch (error) {
326
- this.logger.error("Error getting messages:", error);
327
- throw error;
328
- }
329
- }
330
- async saveMessages({ messages }) {
331
- if (messages.length === 0) return messages;
332
- try {
333
- const threadId = messages[0]?.threadId;
334
- if (!threadId) {
335
- throw new Error("Thread ID is required");
336
- }
337
- const batchStatements = messages.map((message) => {
338
- const time = message.createdAt || /* @__PURE__ */ new Date();
339
- return {
340
- sql: `INSERT INTO ${chunk6KB5CPBV_cjs.TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
341
- VALUES (?, ?, ?, ?, ?, ?)`,
342
- args: [
343
- message.id,
344
- threadId,
345
- typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
346
- message.role,
347
- message.type,
348
- time instanceof Date ? time.toISOString() : time
349
- ]
350
- };
351
- });
352
- await this.client.batch(batchStatements, "write");
353
- return messages;
354
- } catch (error) {
355
- this.logger.error("Failed to save messages in database: " + error?.message);
356
- throw error;
357
- }
358
- }
359
- transformEvalRow(row) {
360
- const resultValue = JSON.parse(row.result);
361
- const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
362
- if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
363
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
364
- }
365
- return {
366
- input: row.input,
367
- output: row.output,
368
- result: resultValue,
369
- agentName: row.agent_name,
370
- metricName: row.metric_name,
371
- instructions: row.instructions,
372
- testInfo: testInfoValue,
373
- globalRunId: row.global_run_id,
374
- runId: row.run_id,
375
- createdAt: row.created_at
376
- };
377
- }
378
- async getEvalsByAgentName(agentName, type) {
379
- try {
380
- const baseQuery = `SELECT * FROM ${chunk6KB5CPBV_cjs.TABLE_EVALS} WHERE agent_name = ?`;
381
- 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)" : "";
382
- const result = await this.client.execute({
383
- sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
384
- args: [agentName]
385
- });
386
- return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
387
- } catch (error) {
388
- if (error instanceof Error && error.message.includes("no such table")) {
389
- return [];
390
- }
391
- this.logger.error("Failed to get evals for the specified agent: " + error?.message);
392
- throw error;
393
- }
394
- }
395
- // TODO: add types
396
- async getTraces({
397
- name,
398
- scope,
399
- page,
400
- perPage,
401
- attributes,
402
- filters,
403
- fromDate,
404
- toDate
405
- } = {
406
- page: 0,
407
- perPage: 100
408
- }) {
409
- const limit = perPage;
410
- const offset = page * perPage;
411
- const args = [];
412
- const conditions = [];
413
- if (name) {
414
- conditions.push("name LIKE CONCAT(?, '%')");
415
- }
416
- if (scope) {
417
- conditions.push("scope = ?");
418
- }
419
- if (attributes) {
420
- Object.keys(attributes).forEach((key) => {
421
- conditions.push(`attributes->>'$.${key}' = ?`);
422
- });
423
- }
424
- if (filters) {
425
- Object.entries(filters).forEach(([key, _value]) => {
426
- conditions.push(`${key} = ?`);
427
- });
428
- }
429
- if (fromDate) {
430
- conditions.push("createdAt >= ?");
431
- }
432
- if (toDate) {
433
- conditions.push("createdAt <= ?");
434
- }
435
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
436
- if (name) {
437
- args.push(name);
438
- }
439
- if (scope) {
440
- args.push(scope);
441
- }
442
- if (attributes) {
443
- for (const [, value] of Object.entries(attributes)) {
444
- args.push(value);
445
- }
446
- }
447
- if (filters) {
448
- for (const [, value] of Object.entries(filters)) {
449
- args.push(value);
450
- }
451
- }
452
- if (fromDate) {
453
- args.push(fromDate.toISOString());
454
- }
455
- if (toDate) {
456
- args.push(toDate.toISOString());
457
- }
458
- args.push(limit, offset);
459
- const result = await this.client.execute({
460
- sql: `SELECT * FROM ${chunk6KB5CPBV_cjs.TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
461
- args
462
- });
463
- if (!result.rows) {
464
- return [];
465
- }
466
- return result.rows.map((row) => ({
467
- id: row.id,
468
- parentSpanId: row.parentSpanId,
469
- traceId: row.traceId,
470
- name: row.name,
471
- scope: row.scope,
472
- kind: row.kind,
473
- status: safelyParseJSON(row.status),
474
- events: safelyParseJSON(row.events),
475
- links: safelyParseJSON(row.links),
476
- attributes: safelyParseJSON(row.attributes),
477
- startTime: row.startTime,
478
- endTime: row.endTime,
479
- other: safelyParseJSON(row.other),
480
- createdAt: row.createdAt
481
- }));
482
- }
483
- async getWorkflowRuns({
484
- workflowName,
485
- fromDate,
486
- toDate,
487
- limit,
488
- offset
489
- } = {}) {
490
- const conditions = [];
491
- const args = [];
492
- if (workflowName) {
493
- conditions.push("workflow_name = ?");
494
- args.push(workflowName);
495
- }
496
- if (fromDate) {
497
- conditions.push("createdAt >= ?");
498
- args.push(fromDate.toISOString());
499
- }
500
- if (toDate) {
501
- conditions.push("createdAt <= ?");
502
- args.push(toDate.toISOString());
503
- }
504
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
505
- let total = 0;
506
- if (limit !== void 0 && offset !== void 0) {
507
- const countResult = await this.client.execute({
508
- sql: `SELECT COUNT(*) as count FROM ${chunk6KB5CPBV_cjs.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
509
- args
510
- });
511
- total = Number(countResult.rows?.[0]?.count ?? 0);
512
- }
513
- const result = await this.client.execute({
514
- sql: `SELECT * FROM ${chunk6KB5CPBV_cjs.TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${limit !== void 0 && offset !== void 0 ? ` LIMIT ? OFFSET ?` : ""}`,
515
- args: limit !== void 0 && offset !== void 0 ? [...args, limit, offset] : args
516
- });
517
- const runs = (result.rows || []).map((row) => {
518
- let parsedSnapshot = row.snapshot;
519
- if (typeof parsedSnapshot === "string") {
520
- try {
521
- parsedSnapshot = JSON.parse(row.snapshot);
522
- } catch (e) {
523
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
524
- }
525
- }
526
- return {
527
- workflowName: row.workflow_name,
528
- runId: row.run_id,
529
- snapshot: parsedSnapshot,
530
- createdAt: new Date(row.createdAt),
531
- updatedAt: new Date(row.updatedAt)
532
- };
533
- });
534
- return { runs, total: total || runs.length };
535
- }
536
- async getWorkflowRunById({
537
- runId,
538
- workflowName
539
- }) {
540
- const conditions = [];
541
- const args = [];
542
- if (runId) {
543
- conditions.push("run_id = ?");
544
- args.push(runId);
545
- }
546
- if (workflowName) {
547
- conditions.push("workflow_name = ?");
548
- args.push(workflowName);
549
- }
550
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
551
- const result = await this.client.execute({
552
- sql: `SELECT * FROM ${chunk6KB5CPBV_cjs.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
553
- args
554
- });
555
- if (!result.rows?.[0]) {
556
- return null;
557
- }
558
- return this.parseWorkflowRun(result.rows[0]);
559
- }
560
- parseWorkflowRun(row) {
561
- let parsedSnapshot = row.snapshot;
562
- if (typeof parsedSnapshot === "string") {
563
- try {
564
- parsedSnapshot = JSON.parse(row.snapshot);
565
- } catch (e) {
566
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
567
- }
568
- }
569
- return {
570
- workflowName: row.workflow_name,
571
- runId: row.run_id,
572
- snapshot: parsedSnapshot,
573
- resourceId: row.resourceId,
574
- createdAt: new Date(row.created_at),
575
- updatedAt: new Date(row.updated_at)
576
- };
577
- }
578
- };
579
-
580
- exports.DefaultStorage = LibSQLStore;
581
- exports.LibSQLStore = LibSQLStore;
@@ -1,104 +0,0 @@
1
- import { Config } from '@libsql/client';
2
- import { b as MastraStorage, T as TABLE_NAMES, S as StorageColumn, c as StorageThreadType, d as MessageType, e as StorageGetMessagesArg, E as EvalRow, W as WorkflowRuns, f as WorkflowRun } from '../../base-CAEcd6q2.cjs';
3
- import 'ai';
4
- import '../../base-H7siSAfu.cjs';
5
- import '@opentelemetry/api';
6
- import '../../index-QV27jkxQ.cjs';
7
- import 'stream';
8
- import 'pino';
9
- import '@opentelemetry/sdk-trace-base';
10
- import '../../types-BtMyV38I.cjs';
11
- import 'sift';
12
- import 'zod';
13
- import 'json-schema';
14
- import '../../runtime-context/index.cjs';
15
- import 'xstate';
16
- import 'node:events';
17
- import '../../vector/index.cjs';
18
- import '../../vector/filter/index.cjs';
19
- import '../../tts/index.cjs';
20
- import 'node:http';
21
- import 'hono';
22
- import 'events';
23
- import '../../deployer/index.cjs';
24
- import '../../bundler/index.cjs';
25
- import 'hono/cors';
26
- import 'hono-openapi';
27
- import 'ai/test';
28
-
29
- declare class LibSQLStore extends MastraStorage {
30
- private client;
31
- constructor({ config }: {
32
- config: Config;
33
- });
34
- protected rewriteDbUrl(url: string): string;
35
- private getCreateTableSQL;
36
- createTable({ tableName, schema, }: {
37
- tableName: TABLE_NAMES;
38
- schema: Record<string, StorageColumn>;
39
- }): Promise<void>;
40
- clearTable({ tableName }: {
41
- tableName: TABLE_NAMES;
42
- }): Promise<void>;
43
- private prepareStatement;
44
- insert({ tableName, record }: {
45
- tableName: TABLE_NAMES;
46
- record: Record<string, any>;
47
- }): Promise<void>;
48
- batchInsert({ tableName, records }: {
49
- tableName: TABLE_NAMES;
50
- records: Record<string, any>[];
51
- }): Promise<void>;
52
- load<R>({ tableName, keys }: {
53
- tableName: TABLE_NAMES;
54
- keys: Record<string, string>;
55
- }): Promise<R | null>;
56
- getThreadById({ threadId }: {
57
- threadId: string;
58
- }): Promise<StorageThreadType | null>;
59
- getThreadsByResourceId({ resourceId }: {
60
- resourceId: string;
61
- }): Promise<StorageThreadType[]>;
62
- saveThread({ thread }: {
63
- thread: StorageThreadType;
64
- }): Promise<StorageThreadType>;
65
- updateThread({ id, title, metadata, }: {
66
- id: string;
67
- title: string;
68
- metadata: Record<string, unknown>;
69
- }): Promise<StorageThreadType>;
70
- deleteThread({ threadId }: {
71
- threadId: string;
72
- }): Promise<void>;
73
- private parseRow;
74
- getMessages<T extends MessageType[]>({ threadId, selectBy }: StorageGetMessagesArg): Promise<T>;
75
- saveMessages({ messages }: {
76
- messages: MessageType[];
77
- }): Promise<MessageType[]>;
78
- private transformEvalRow;
79
- getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
80
- getTraces({ name, scope, page, perPage, attributes, filters, fromDate, toDate, }?: {
81
- name?: string;
82
- scope?: string;
83
- page: number;
84
- perPage: number;
85
- attributes?: Record<string, string>;
86
- filters?: Record<string, any>;
87
- fromDate?: Date;
88
- toDate?: Date;
89
- }): Promise<any[]>;
90
- getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, }?: {
91
- workflowName?: string;
92
- fromDate?: Date;
93
- toDate?: Date;
94
- limit?: number;
95
- offset?: number;
96
- }): Promise<WorkflowRuns>;
97
- getWorkflowRunById({ runId, workflowName, }: {
98
- runId: string;
99
- workflowName?: string;
100
- }): Promise<WorkflowRun | null>;
101
- private parseWorkflowRun;
102
- }
103
-
104
- export { LibSQLStore as DefaultStorage, LibSQLStore };