@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,781 +0,0 @@
1
- import { MastraVector } from './chunk-NZV4OA6P.js';
2
- import { BaseFilterTranslator } from './chunk-LGERQTJM.js';
3
- import { isAbsolute, join, resolve } from 'path';
4
- import { createClient } from '@libsql/client';
5
-
6
- // src/vector/libsql/filter.ts
7
- var LibSQLFilterTranslator = class extends BaseFilterTranslator {
8
- getSupportedOperators() {
9
- return {
10
- ...BaseFilterTranslator.DEFAULT_OPERATORS,
11
- regex: [],
12
- custom: ["$contains", "$size"]
13
- };
14
- }
15
- translate(filter) {
16
- if (this.isEmpty(filter)) {
17
- return filter;
18
- }
19
- this.validateFilter(filter);
20
- return this.translateNode(filter);
21
- }
22
- translateNode(node, currentPath = "") {
23
- if (this.isRegex(node)) {
24
- throw new Error("Direct regex pattern format is not supported in LibSQL");
25
- }
26
- const withPath = (result2) => currentPath ? { [currentPath]: result2 } : result2;
27
- if (this.isPrimitive(node)) {
28
- return withPath({ $eq: this.normalizeComparisonValue(node) });
29
- }
30
- if (Array.isArray(node)) {
31
- return withPath({ $in: this.normalizeArrayValues(node) });
32
- }
33
- const entries = Object.entries(node);
34
- const result = {};
35
- for (const [key, value] of entries) {
36
- const newPath = currentPath ? `${currentPath}.${key}` : key;
37
- if (this.isLogicalOperator(key)) {
38
- result[key] = Array.isArray(value) ? value.map((filter) => this.translateNode(filter)) : this.translateNode(value);
39
- } else if (this.isOperator(key)) {
40
- if (this.isArrayOperator(key) && !Array.isArray(value) && key !== "$elemMatch") {
41
- result[key] = [value];
42
- } else if (this.isBasicOperator(key) && Array.isArray(value)) {
43
- result[key] = JSON.stringify(value);
44
- } else {
45
- result[key] = value;
46
- }
47
- } else if (typeof value === "object" && value !== null) {
48
- const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
49
- if (hasOperators) {
50
- result[newPath] = this.translateNode(value);
51
- } else {
52
- Object.assign(result, this.translateNode(value, newPath));
53
- }
54
- } else {
55
- result[newPath] = this.translateNode(value);
56
- }
57
- }
58
- return result;
59
- }
60
- // TODO: Look more into regex support for LibSQL
61
- // private translateRegexPattern(pattern: string, options: string = ''): any {
62
- // if (!options) return { $regex: pattern };
63
- // const flags = options
64
- // .split('')
65
- // .filter(f => 'imsux'.includes(f))
66
- // .join('');
67
- // return {
68
- // $regex: pattern,
69
- // $options: flags,
70
- // };
71
- // }
72
- };
73
-
74
- // src/vector/libsql/sql-builder.ts
75
- var createBasicOperator = (symbol) => {
76
- return (key, value) => ({
77
- sql: `CASE
78
- WHEN ? IS NULL THEN json_extract(metadata, '$."${handleKey(key)}"') IS ${symbol === "=" ? "" : "NOT"} NULL
79
- ELSE json_extract(metadata, '$."${handleKey(key)}"') ${symbol} ?
80
- END`,
81
- needsValue: true,
82
- transformValue: () => [value, value]
83
- });
84
- };
85
- var createNumericOperator = (symbol) => {
86
- return (key) => ({
87
- sql: `CAST(json_extract(metadata, '$."${handleKey(key)}"') AS NUMERIC) ${symbol} ?`,
88
- needsValue: true
89
- });
90
- };
91
- function buildElemMatchConditions(value) {
92
- const conditions = Object.entries(value).map(([field, fieldValue]) => {
93
- if (field.startsWith("$")) {
94
- const { sql, values } = buildCondition("elem.value", { [field]: fieldValue });
95
- const pattern = /json_extract\(metadata, '\$\."[^"]*"(\."[^"]*")*'\)/g;
96
- const elemSql = sql.replace(pattern, "elem.value");
97
- return { sql: elemSql, values };
98
- } else if (typeof fieldValue === "object" && !Array.isArray(fieldValue)) {
99
- const { sql, values } = buildCondition(field, fieldValue);
100
- const pattern = /json_extract\(metadata, '\$\."[^"]*"(\."[^"]*")*'\)/g;
101
- const elemSql = sql.replace(pattern, `json_extract(elem.value, '$."${field}"')`);
102
- return { sql: elemSql, values };
103
- } else {
104
- return {
105
- sql: `json_extract(elem.value, '$."${field}"') = ?`,
106
- values: [fieldValue]
107
- };
108
- }
109
- });
110
- return conditions;
111
- }
112
- var validateJsonArray = (key) => `json_valid(json_extract(metadata, '$."${handleKey(key)}"'))
113
- AND json_type(json_extract(metadata, '$."${handleKey(key)}"')) = 'array'`;
114
- var FILTER_OPERATORS = {
115
- $eq: createBasicOperator("="),
116
- $ne: createBasicOperator("!="),
117
- $gt: createNumericOperator(">"),
118
- $gte: createNumericOperator(">="),
119
- $lt: createNumericOperator("<"),
120
- $lte: createNumericOperator("<="),
121
- // Array Operators
122
- $in: (key, value) => {
123
- const arr = Array.isArray(value) ? value : [value];
124
- if (arr.length === 0) {
125
- return { sql: "1 = 0", needsValue: true, transformValue: () => [] };
126
- }
127
- const paramPlaceholders = arr.map(() => "?").join(",");
128
- return {
129
- sql: `(
130
- CASE
131
- WHEN ${validateJsonArray(key)} THEN
132
- EXISTS (
133
- SELECT 1 FROM json_each(json_extract(metadata, '$."${handleKey(key)}"')) as elem
134
- WHERE elem.value IN (SELECT value FROM json_each(?))
135
- )
136
- ELSE json_extract(metadata, '$."${handleKey(key)}"') IN (${paramPlaceholders})
137
- END
138
- )`,
139
- needsValue: true,
140
- transformValue: () => [JSON.stringify(arr), ...arr]
141
- };
142
- },
143
- $nin: (key, value) => {
144
- const arr = Array.isArray(value) ? value : [value];
145
- if (arr.length === 0) {
146
- return { sql: "1 = 1", needsValue: true, transformValue: () => [] };
147
- }
148
- const paramPlaceholders = arr.map(() => "?").join(",");
149
- return {
150
- sql: `(
151
- CASE
152
- WHEN ${validateJsonArray(key)} THEN
153
- NOT EXISTS (
154
- SELECT 1 FROM json_each(json_extract(metadata, '$."${handleKey(key)}"')) as elem
155
- WHERE elem.value IN (SELECT value FROM json_each(?))
156
- )
157
- ELSE json_extract(metadata, '$."${handleKey(key)}"') NOT IN (${paramPlaceholders})
158
- END
159
- )`,
160
- needsValue: true,
161
- transformValue: () => [JSON.stringify(arr), ...arr]
162
- };
163
- },
164
- $all: (key, value) => {
165
- let sql;
166
- const arrayValue = Array.isArray(value) ? value : [value];
167
- if (arrayValue.length === 0) {
168
- sql = "1 = 0";
169
- } else {
170
- sql = `(
171
- CASE
172
- WHEN ${validateJsonArray(key)} THEN
173
- NOT EXISTS (
174
- SELECT value
175
- FROM json_each(?)
176
- WHERE value NOT IN (
177
- SELECT value
178
- FROM json_each(json_extract(metadata, '$."${handleKey(key)}"'))
179
- )
180
- )
181
- ELSE FALSE
182
- END
183
- )`;
184
- }
185
- return {
186
- sql,
187
- needsValue: true,
188
- transformValue: () => {
189
- if (arrayValue.length === 0) {
190
- return [];
191
- }
192
- return [JSON.stringify(arrayValue)];
193
- }
194
- };
195
- },
196
- $elemMatch: (key, value) => {
197
- if (typeof value !== "object" || Array.isArray(value)) {
198
- throw new Error("$elemMatch requires an object with conditions");
199
- }
200
- const conditions = buildElemMatchConditions(value);
201
- return {
202
- sql: `(
203
- CASE
204
- WHEN ${validateJsonArray(key)} THEN
205
- EXISTS (
206
- SELECT 1
207
- FROM json_each(json_extract(metadata, '$."${handleKey(key)}"')) as elem
208
- WHERE ${conditions.map((c) => c.sql).join(" AND ")}
209
- )
210
- ELSE FALSE
211
- END
212
- )`,
213
- needsValue: true,
214
- transformValue: () => conditions.flatMap((c) => c.values)
215
- };
216
- },
217
- // Element Operators
218
- $exists: (key) => ({
219
- sql: `json_extract(metadata, '$."${handleKey(key)}"') IS NOT NULL`,
220
- needsValue: false
221
- }),
222
- // Logical Operators
223
- $and: (key) => ({
224
- sql: `(${key})`,
225
- needsValue: false
226
- }),
227
- $or: (key) => ({
228
- sql: `(${key})`,
229
- needsValue: false
230
- }),
231
- $not: (key) => ({ sql: `NOT (${key})`, needsValue: false }),
232
- $nor: (key) => ({
233
- sql: `NOT (${key})`,
234
- needsValue: false
235
- }),
236
- $size: (key, paramIndex) => ({
237
- sql: `(
238
- CASE
239
- WHEN json_type(json_extract(metadata, '$."${handleKey(key)}"')) = 'array' THEN
240
- json_array_length(json_extract(metadata, '$."${handleKey(key)}"')) = $${paramIndex}
241
- ELSE FALSE
242
- END
243
- )`,
244
- needsValue: true
245
- }),
246
- // /**
247
- // * Regex Operators
248
- // * Supports case insensitive and multiline
249
- // */
250
- // $regex: (key: string): FilterOperator => ({
251
- // sql: `json_extract(metadata, '$."${handleKey(key)}"') = ?`,
252
- // needsValue: true,
253
- // transformValue: (value: any) => {
254
- // const pattern = typeof value === 'object' ? value.$regex : value;
255
- // const options = typeof value === 'object' ? value.$options || '' : '';
256
- // let sql = `json_extract(metadata, '$."${handleKey(key)}"')`;
257
- // // Handle multiline
258
- // // if (options.includes('m')) {
259
- // // sql = `REPLACE(${sql}, CHAR(10), '\n')`;
260
- // // }
261
- // // let finalPattern = pattern;
262
- // // if (options) {
263
- // // finalPattern = `(\\?${options})${pattern}`;
264
- // // }
265
- // // // Handle case insensitivity
266
- // // if (options.includes('i')) {
267
- // // sql = `LOWER(${sql}) REGEXP LOWER(?)`;
268
- // // } else {
269
- // // sql = `${sql} REGEXP ?`;
270
- // // }
271
- // if (options.includes('m')) {
272
- // sql = `EXISTS (
273
- // SELECT 1
274
- // FROM json_each(
275
- // json_array(
276
- // ${sql},
277
- // REPLACE(${sql}, CHAR(10), CHAR(13))
278
- // )
279
- // ) as lines
280
- // WHERE lines.value REGEXP ?
281
- // )`;
282
- // } else {
283
- // sql = `${sql} REGEXP ?`;
284
- // }
285
- // // Handle case insensitivity
286
- // if (options.includes('i')) {
287
- // sql = sql.replace('REGEXP ?', 'REGEXP LOWER(?)');
288
- // sql = sql.replace('value REGEXP', 'LOWER(value) REGEXP');
289
- // }
290
- // // Handle extended - allows whitespace and comments in pattern
291
- // if (options.includes('x')) {
292
- // // Remove whitespace and comments from pattern
293
- // const cleanPattern = pattern.replace(/\s+|#.*$/gm, '');
294
- // return {
295
- // sql,
296
- // values: [cleanPattern],
297
- // };
298
- // }
299
- // return {
300
- // sql,
301
- // values: [pattern],
302
- // };
303
- // },
304
- // }),
305
- $contains: (key, value) => {
306
- let sql;
307
- if (Array.isArray(value)) {
308
- sql = `(
309
- SELECT ${validateJsonArray(key)}
310
- AND EXISTS (
311
- SELECT 1
312
- FROM json_each(json_extract(metadata, '$."${handleKey(key)}"')) as m
313
- WHERE m.value IN (SELECT value FROM json_each(?))
314
- )
315
- )`;
316
- } else if (typeof value === "string") {
317
- sql = `lower(json_extract(metadata, '$."${handleKey(key)}"')) LIKE '%' || lower(?) || '%'`;
318
- } else {
319
- sql = `json_extract(metadata, '$."${handleKey(key)}"') = ?`;
320
- }
321
- return {
322
- sql,
323
- needsValue: true,
324
- transformValue: () => {
325
- if (Array.isArray(value)) {
326
- return [JSON.stringify(value)];
327
- }
328
- if (typeof value === "object" && value !== null) {
329
- return [JSON.stringify(value)];
330
- }
331
- return [value];
332
- }
333
- };
334
- }
335
- /**
336
- * $objectContains: True JSON containment for advanced use (deep sub-object match).
337
- * Usage: { field: { $objectContains: { ...subobject } } }
338
- */
339
- // $objectContains: (key: string) => ({
340
- // sql: '', // Will be overridden by transformValue
341
- // needsValue: true,
342
- // transformValue: (value: any) => ({
343
- // sql: `json_type(json_extract(metadata, '$."${handleKey(key)}"')) = 'object'
344
- // AND json_patch(json_extract(metadata, '$."${handleKey(key)}"'), ?) = json_extract(metadata, '$."${handleKey(key)}"')`,
345
- // values: [JSON.stringify(value)],
346
- // }),
347
- // }),
348
- };
349
- var handleKey = (key) => {
350
- return key.replace(/\./g, '"."');
351
- };
352
- function buildFilterQuery(filter) {
353
- if (!filter) {
354
- return { sql: "", values: [] };
355
- }
356
- const values = [];
357
- const conditions = Object.entries(filter).map(([key, value]) => {
358
- const condition = buildCondition(key, value);
359
- values.push(...condition.values);
360
- return condition.sql;
361
- }).join(" AND ");
362
- return {
363
- sql: conditions ? `WHERE ${conditions}` : "",
364
- values
365
- };
366
- }
367
- function buildCondition(key, value, parentPath) {
368
- if (["$and", "$or", "$not", "$nor"].includes(key)) {
369
- return handleLogicalOperator(key, value);
370
- }
371
- if (!value || typeof value !== "object") {
372
- return {
373
- sql: `json_extract(metadata, '$."${key.replace(/\./g, '"."')}"') = ?`,
374
- values: [value]
375
- };
376
- }
377
- return handleOperator(key, value);
378
- }
379
- function handleLogicalOperator(key, value, parentPath) {
380
- if (!value || value.length === 0) {
381
- switch (key) {
382
- case "$and":
383
- case "$nor":
384
- return { sql: "true", values: [] };
385
- case "$or":
386
- return { sql: "false", values: [] };
387
- case "$not":
388
- throw new Error("$not operator cannot be empty");
389
- default:
390
- return { sql: "true", values: [] };
391
- }
392
- }
393
- if (key === "$not") {
394
- const entries = Object.entries(value);
395
- const conditions2 = entries.map(([fieldKey, fieldValue]) => buildCondition(fieldKey, fieldValue));
396
- return {
397
- sql: `NOT (${conditions2.map((c) => c.sql).join(" AND ")})`,
398
- values: conditions2.flatMap((c) => c.values)
399
- };
400
- }
401
- const values = [];
402
- const joinOperator = key === "$or" || key === "$nor" ? "OR" : "AND";
403
- const conditions = Array.isArray(value) ? value.map((f) => {
404
- const entries = Object.entries(f);
405
- return entries.map(([k, v]) => buildCondition(k, v));
406
- }) : [buildCondition(key, value)];
407
- const joined = conditions.flat().map((c) => {
408
- values.push(...c.values);
409
- return c.sql;
410
- }).join(` ${joinOperator} `);
411
- return {
412
- sql: key === "$nor" ? `NOT (${joined})` : `(${joined})`,
413
- values
414
- };
415
- }
416
- function handleOperator(key, value) {
417
- if (typeof value === "object" && !Array.isArray(value)) {
418
- const entries = Object.entries(value);
419
- const results = entries.map(
420
- ([operator2, operatorValue2]) => operator2 === "$not" ? {
421
- sql: `NOT (${Object.entries(operatorValue2).map(([op, val]) => processOperator(key, op, val).sql).join(" AND ")})`,
422
- values: Object.entries(operatorValue2).flatMap(
423
- ([op, val]) => processOperator(key, op, val).values
424
- )
425
- } : processOperator(key, operator2, operatorValue2)
426
- );
427
- return {
428
- sql: `(${results.map((r) => r.sql).join(" AND ")})`,
429
- values: results.flatMap((r) => r.values)
430
- };
431
- }
432
- const [[operator, operatorValue] = []] = Object.entries(value);
433
- return processOperator(key, operator, operatorValue);
434
- }
435
- var processOperator = (key, operator, operatorValue) => {
436
- if (!operator.startsWith("$") || !FILTER_OPERATORS[operator]) {
437
- throw new Error(`Invalid operator: ${operator}`);
438
- }
439
- const operatorFn = FILTER_OPERATORS[operator];
440
- const operatorResult = operatorFn(key, operatorValue);
441
- if (!operatorResult.needsValue) {
442
- return { sql: operatorResult.sql, values: [] };
443
- }
444
- const transformed = operatorResult.transformValue ? operatorResult.transformValue() : operatorValue;
445
- return {
446
- sql: operatorResult.sql,
447
- values: Array.isArray(transformed) ? transformed : [transformed]
448
- };
449
- };
450
-
451
- // src/vector/libsql/index.ts
452
- var LibSQLVector = class extends MastraVector {
453
- turso;
454
- constructor({
455
- connectionUrl,
456
- authToken,
457
- syncUrl,
458
- syncInterval
459
- }) {
460
- super();
461
- this.turso = createClient({
462
- url: this.rewriteDbUrl(connectionUrl),
463
- syncUrl,
464
- authToken,
465
- syncInterval
466
- });
467
- if (connectionUrl.includes(`file:`) || connectionUrl.includes(`:memory:`)) {
468
- void this.turso.execute({
469
- sql: "PRAGMA journal_mode=WAL;",
470
- args: {}
471
- });
472
- }
473
- }
474
- // If we're in the .mastra/output directory, use the dir outside .mastra dir
475
- // reason we need to do this is libsql relative file paths are based on cwd, not current file path
476
- // since mastra dev sets cwd to .mastra/output this means running an agent directly vs running with mastra dev
477
- // will put db files in different locations, leading to an inconsistent experience between the two.
478
- // Ex: with `file:ex.db`
479
- // 1. `mastra dev`: ${cwd}/.mastra/output/ex.db
480
- // 2. `tsx src/index.ts`: ${cwd}/ex.db
481
- // so if we're in .mastra/output we need to rewrite the file url to be relative to the project root dir
482
- // or the experience will be inconsistent
483
- // this means `file:` urls are always relative to project root
484
- // TODO: can we make this easier via bundling? https://github.com/mastra-ai/mastra/pull/2783#pullrequestreview-2662444241
485
- rewriteDbUrl(url) {
486
- if (url.startsWith("file:")) {
487
- const pathPart = url.slice("file:".length);
488
- if (isAbsolute(pathPart)) {
489
- return url;
490
- }
491
- const cwd = process.cwd();
492
- if (cwd.includes(".mastra") && (cwd.endsWith(`output`) || cwd.endsWith(`output/`) || cwd.endsWith(`output\\`))) {
493
- const baseDir = join(cwd, `..`, `..`);
494
- const fullPath = resolve(baseDir, pathPart);
495
- this.logger.debug(
496
- `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.`
497
- );
498
- return `file:${fullPath}`;
499
- }
500
- }
501
- return url;
502
- }
503
- transformFilter(filter) {
504
- const translator = new LibSQLFilterTranslator();
505
- return translator.translate(filter);
506
- }
507
- async query(...args) {
508
- const params = this.normalizeArgs("query", args, ["minScore"]);
509
- try {
510
- const { indexName, queryVector, topK = 10, filter, includeVector = false, minScore = 0 } = params;
511
- const vectorStr = `[${queryVector.join(",")}]`;
512
- const translatedFilter = this.transformFilter(filter);
513
- const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
514
- filterValues.push(minScore);
515
- const query = `
516
- WITH vector_scores AS (
517
- SELECT
518
- vector_id as id,
519
- (1-vector_distance_cos(embedding, '${vectorStr}')) as score,
520
- metadata
521
- ${includeVector ? ", vector_extract(embedding) as embedding" : ""}
522
- FROM ${indexName}
523
- ${filterQuery}
524
- )
525
- SELECT *
526
- FROM vector_scores
527
- WHERE score > ?
528
- ORDER BY score DESC
529
- LIMIT ${topK}`;
530
- const result = await this.turso.execute({
531
- sql: query,
532
- args: filterValues
533
- });
534
- return result.rows.map(({ id, score, metadata, embedding }) => ({
535
- id,
536
- score,
537
- metadata: JSON.parse(metadata ?? "{}"),
538
- ...includeVector && embedding && { vector: JSON.parse(embedding) }
539
- }));
540
- } finally {
541
- }
542
- }
543
- async upsert(...args) {
544
- const params = this.normalizeArgs("upsert", args);
545
- const { indexName, vectors, metadata, ids } = params;
546
- const tx = await this.turso.transaction("write");
547
- try {
548
- const vectorIds = ids || vectors.map(() => crypto.randomUUID());
549
- for (let i = 0; i < vectors.length; i++) {
550
- const query = `
551
- INSERT INTO ${indexName} (vector_id, embedding, metadata)
552
- VALUES (?, vector32(?), ?)
553
- ON CONFLICT(vector_id) DO UPDATE SET
554
- embedding = vector32(?),
555
- metadata = ?
556
- `;
557
- await tx.execute({
558
- sql: query,
559
- // @ts-ignore
560
- args: [
561
- vectorIds[i],
562
- JSON.stringify(vectors[i]),
563
- JSON.stringify(metadata?.[i] || {}),
564
- JSON.stringify(vectors[i]),
565
- JSON.stringify(metadata?.[i] || {})
566
- ]
567
- });
568
- }
569
- await tx.commit();
570
- return vectorIds;
571
- } catch (error) {
572
- await tx.rollback();
573
- if (error instanceof Error && error.message?.includes("dimensions are different")) {
574
- const match = error.message.match(/dimensions are different: (\d+) != (\d+)/);
575
- if (match) {
576
- const [, actual, expected] = match;
577
- throw new Error(
578
- `Vector dimension mismatch: Index "${indexName}" expects ${expected} dimensions but got ${actual} dimensions. Either use a matching embedding model or delete and recreate the index with the new dimension.`
579
- );
580
- }
581
- }
582
- throw error;
583
- }
584
- }
585
- async createIndex(...args) {
586
- const params = this.normalizeArgs("createIndex", args);
587
- const { indexName, dimension } = params;
588
- try {
589
- if (!indexName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
590
- throw new Error("Invalid index name format");
591
- }
592
- if (!Number.isInteger(dimension) || dimension <= 0) {
593
- throw new Error("Dimension must be a positive integer");
594
- }
595
- await this.turso.execute({
596
- sql: `
597
- CREATE TABLE IF NOT EXISTS ${indexName} (
598
- id SERIAL PRIMARY KEY,
599
- vector_id TEXT UNIQUE NOT NULL,
600
- embedding F32_BLOB(${dimension}),
601
- metadata TEXT DEFAULT '{}'
602
- );
603
- `,
604
- args: []
605
- });
606
- await this.turso.execute({
607
- sql: `
608
- CREATE INDEX IF NOT EXISTS ${indexName}_vector_idx
609
- ON ${indexName} (libsql_vector_idx(embedding))
610
- `,
611
- args: []
612
- });
613
- } catch (error) {
614
- console.error("Failed to create vector table:", error);
615
- throw error;
616
- } finally {
617
- }
618
- }
619
- async deleteIndex(indexName) {
620
- try {
621
- await this.turso.execute({
622
- sql: `DROP TABLE IF EXISTS ${indexName}`,
623
- args: []
624
- });
625
- } catch (error) {
626
- console.error("Failed to delete vector table:", error);
627
- throw new Error(`Failed to delete vector table: ${error.message}`);
628
- } finally {
629
- }
630
- }
631
- async listIndexes() {
632
- try {
633
- const vectorTablesQuery = `
634
- SELECT name FROM sqlite_master
635
- WHERE type='table'
636
- AND sql LIKE '%F32_BLOB%';
637
- `;
638
- const result = await this.turso.execute({
639
- sql: vectorTablesQuery,
640
- args: []
641
- });
642
- return result.rows.map((row) => row.name);
643
- } catch (error) {
644
- throw new Error(`Failed to list vector tables: ${error.message}`);
645
- }
646
- }
647
- async describeIndex(indexName) {
648
- try {
649
- const tableInfoQuery = `
650
- SELECT sql
651
- FROM sqlite_master
652
- WHERE type='table'
653
- AND name = ?;
654
- `;
655
- const tableInfo = await this.turso.execute({
656
- sql: tableInfoQuery,
657
- args: [indexName]
658
- });
659
- if (!tableInfo.rows[0]?.sql) {
660
- throw new Error(`Table ${indexName} not found`);
661
- }
662
- const dimension = parseInt(tableInfo.rows[0].sql.match(/F32_BLOB\((\d+)\)/)?.[1] || "0");
663
- const countQuery = `
664
- SELECT COUNT(*) as count
665
- FROM ${indexName};
666
- `;
667
- const countResult = await this.turso.execute({
668
- sql: countQuery,
669
- args: []
670
- });
671
- const metric = "cosine";
672
- return {
673
- dimension,
674
- count: countResult?.rows?.[0]?.count ?? 0,
675
- metric
676
- };
677
- } catch (e) {
678
- throw new Error(`Failed to describe vector table: ${e.message}`);
679
- }
680
- }
681
- /**
682
- * @deprecated Use {@link updateVector} instead. This method will be removed on May 20th, 2025.
683
- *
684
- * Updates a vector by its ID with the provided vector and/or metadata.
685
- * @param indexName - The name of the index containing the vector.
686
- * @param id - The ID of the vector to update.
687
- * @param update - An object containing the vector and/or metadata to update.
688
- * @param update.vector - An optional array of numbers representing the new vector.
689
- * @param update.metadata - An optional record containing the new metadata.
690
- * @returns A promise that resolves when the update is complete.
691
- * @throws Will throw an error if no updates are provided or if the update operation fails.
692
- */
693
- async updateIndexById(indexName, id, update) {
694
- this.logger.warn(
695
- `Deprecation Warning: updateIndexById() is deprecated. Please use updateVector() instead. updateIndexById() will be removed on May 20th, 2025.`
696
- );
697
- await this.updateVector(indexName, id, update);
698
- }
699
- /**
700
- * Updates a vector by its ID with the provided vector and/or metadata.
701
- *
702
- * @param indexName - The name of the index containing the vector.
703
- * @param id - The ID of the vector to update.
704
- * @param update - An object containing the vector and/or metadata to update.
705
- * @param update.vector - An optional array of numbers representing the new vector.
706
- * @param update.metadata - An optional record containing the new metadata.
707
- * @returns A promise that resolves when the update is complete.
708
- * @throws Will throw an error if no updates are provided or if the update operation fails.
709
- */
710
- async updateVector(indexName, id, update) {
711
- try {
712
- const updates = [];
713
- const args = [];
714
- if (update.vector) {
715
- updates.push("embedding = vector32(?)");
716
- args.push(JSON.stringify(update.vector));
717
- }
718
- if (update.metadata) {
719
- updates.push("metadata = ?");
720
- args.push(JSON.stringify(update.metadata));
721
- }
722
- if (updates.length === 0) {
723
- throw new Error("No updates provided");
724
- }
725
- args.push(id);
726
- const query = `
727
- UPDATE ${indexName}
728
- SET ${updates.join(", ")}
729
- WHERE vector_id = ?;
730
- `;
731
- await this.turso.execute({
732
- sql: query,
733
- args
734
- });
735
- } catch (error) {
736
- throw new Error(`Failed to update vector by id: ${id} for index: ${indexName}: ${error.message}`);
737
- }
738
- }
739
- /**
740
- * @deprecated Use {@link deleteVector} instead. This method will be removed on May 20th, 2025.
741
- *
742
- * Deletes a vector by its ID.
743
- * @param indexName - The name of the index containing the vector.
744
- * @param id - The ID of the vector to delete.
745
- * @returns A promise that resolves when the deletion is complete.
746
- * @throws Will throw an error if the deletion operation fails.
747
- */
748
- async deleteIndexById(indexName, id) {
749
- this.logger.warn(
750
- `Deprecation Warning: deleteIndexById() is deprecated.
751
- Please use deleteVector() instead.
752
- deleteIndexById() will be removed on May 20th, 2025.`
753
- );
754
- await this.deleteVector(indexName, id);
755
- }
756
- /**
757
- * Deletes a vector by its ID.
758
- * @param indexName - The name of the index containing the vector.
759
- * @param id - The ID of the vector to delete.
760
- * @returns A promise that resolves when the deletion is complete.
761
- * @throws Will throw an error if the deletion operation fails.
762
- */
763
- async deleteVector(indexName, id) {
764
- try {
765
- await this.turso.execute({
766
- sql: `DELETE FROM ${indexName} WHERE vector_id = ?`,
767
- args: [id]
768
- });
769
- } catch (error) {
770
- throw new Error(`Failed to delete vector by id: ${id} for index: ${indexName}: ${error.message}`);
771
- }
772
- }
773
- async truncateIndex(indexName) {
774
- await this.turso.execute({
775
- sql: `DELETE FROM ${indexName}`,
776
- args: []
777
- });
778
- }
779
- };
780
-
781
- export { LibSQLVector };