@mastra/libsql 0.0.0-add-runtime-context-to-openai-realtime-20250516201052

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1448 @@
1
+ 'use strict';
2
+
3
+ var client = require('@libsql/client');
4
+ var utils = require('@mastra/core/utils');
5
+ var vector = require('@mastra/core/vector');
6
+ var filter = require('@mastra/core/vector/filter');
7
+ var storage = require('@mastra/core/storage');
8
+
9
+ // src/vector/index.ts
10
+ var LibSQLFilterTranslator = class extends filter.BaseFilterTranslator {
11
+ getSupportedOperators() {
12
+ return {
13
+ ...filter.BaseFilterTranslator.DEFAULT_OPERATORS,
14
+ regex: [],
15
+ custom: ["$contains", "$size"]
16
+ };
17
+ }
18
+ translate(filter) {
19
+ if (this.isEmpty(filter)) {
20
+ return filter;
21
+ }
22
+ this.validateFilter(filter);
23
+ return this.translateNode(filter);
24
+ }
25
+ translateNode(node, currentPath = "") {
26
+ if (this.isRegex(node)) {
27
+ throw new Error("Direct regex pattern format is not supported in LibSQL");
28
+ }
29
+ const withPath = (result2) => currentPath ? { [currentPath]: result2 } : result2;
30
+ if (this.isPrimitive(node)) {
31
+ return withPath({ $eq: this.normalizeComparisonValue(node) });
32
+ }
33
+ if (Array.isArray(node)) {
34
+ return withPath({ $in: this.normalizeArrayValues(node) });
35
+ }
36
+ const entries = Object.entries(node);
37
+ const result = {};
38
+ for (const [key, value] of entries) {
39
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
40
+ if (this.isLogicalOperator(key)) {
41
+ result[key] = Array.isArray(value) ? value.map((filter) => this.translateNode(filter)) : this.translateNode(value);
42
+ } else if (this.isOperator(key)) {
43
+ if (this.isArrayOperator(key) && !Array.isArray(value) && key !== "$elemMatch") {
44
+ result[key] = [value];
45
+ } else if (this.isBasicOperator(key) && Array.isArray(value)) {
46
+ result[key] = JSON.stringify(value);
47
+ } else {
48
+ result[key] = value;
49
+ }
50
+ } else if (typeof value === "object" && value !== null) {
51
+ const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
52
+ if (hasOperators) {
53
+ result[newPath] = this.translateNode(value);
54
+ } else {
55
+ Object.assign(result, this.translateNode(value, newPath));
56
+ }
57
+ } else {
58
+ result[newPath] = this.translateNode(value);
59
+ }
60
+ }
61
+ return result;
62
+ }
63
+ // TODO: Look more into regex support for LibSQL
64
+ // private translateRegexPattern(pattern: string, options: string = ''): any {
65
+ // if (!options) return { $regex: pattern };
66
+ // const flags = options
67
+ // .split('')
68
+ // .filter(f => 'imsux'.includes(f))
69
+ // .join('');
70
+ // return {
71
+ // $regex: pattern,
72
+ // $options: flags,
73
+ // };
74
+ // }
75
+ };
76
+ var createBasicOperator = (symbol) => {
77
+ return (key, value) => {
78
+ const jsonPathKey = parseJsonPathKey(key);
79
+ return {
80
+ sql: `CASE
81
+ WHEN ? IS NULL THEN json_extract(metadata, '$."${jsonPathKey}"') IS ${symbol === "=" ? "" : "NOT"} NULL
82
+ ELSE json_extract(metadata, '$."${jsonPathKey}"') ${symbol} ?
83
+ END`,
84
+ needsValue: true,
85
+ transformValue: () => {
86
+ return [value, value];
87
+ }
88
+ };
89
+ };
90
+ };
91
+ var createNumericOperator = (symbol) => {
92
+ return (key) => {
93
+ const jsonPathKey = parseJsonPathKey(key);
94
+ return {
95
+ sql: `CAST(json_extract(metadata, '$."${jsonPathKey}"') AS NUMERIC) ${symbol} ?`,
96
+ needsValue: true
97
+ };
98
+ };
99
+ };
100
+ var validateJsonArray = (key) => `json_valid(json_extract(metadata, '$."${key}"'))
101
+ AND json_type(json_extract(metadata, '$."${key}"')) = 'array'`;
102
+ var pattern = /json_extract\(metadata, '\$\."[^"]*"(\."[^"]*")*'\)/g;
103
+ function buildElemMatchConditions(value) {
104
+ const conditions = Object.entries(value).map(([field, fieldValue]) => {
105
+ if (field.startsWith("$")) {
106
+ const { sql, values } = buildCondition("elem.value", { [field]: fieldValue });
107
+ const elemSql = sql.replace(pattern, "elem.value");
108
+ return { sql: elemSql, values };
109
+ } else if (typeof fieldValue === "object" && !Array.isArray(fieldValue)) {
110
+ const { sql, values } = buildCondition(field, fieldValue);
111
+ const elemSql = sql.replace(pattern, `json_extract(elem.value, '$."${field}"')`);
112
+ return { sql: elemSql, values };
113
+ } else {
114
+ const parsedFieldKey = utils.parseFieldKey(field);
115
+ return {
116
+ sql: `json_extract(elem.value, '$."${parsedFieldKey}"') = ?`,
117
+ values: [fieldValue]
118
+ };
119
+ }
120
+ });
121
+ return conditions;
122
+ }
123
+ var FILTER_OPERATORS = {
124
+ $eq: createBasicOperator("="),
125
+ $ne: createBasicOperator("!="),
126
+ $gt: createNumericOperator(">"),
127
+ $gte: createNumericOperator(">="),
128
+ $lt: createNumericOperator("<"),
129
+ $lte: createNumericOperator("<="),
130
+ // Array Operators
131
+ $in: (key, value) => {
132
+ const jsonPathKey = parseJsonPathKey(key);
133
+ const arr = Array.isArray(value) ? value : [value];
134
+ if (arr.length === 0) {
135
+ return { sql: "1 = 0", needsValue: true, transformValue: () => [] };
136
+ }
137
+ const paramPlaceholders = arr.map(() => "?").join(",");
138
+ return {
139
+ sql: `(
140
+ CASE
141
+ WHEN ${validateJsonArray(jsonPathKey)} THEN
142
+ EXISTS (
143
+ SELECT 1 FROM json_each(json_extract(metadata, '$."${jsonPathKey}"')) as elem
144
+ WHERE elem.value IN (SELECT value FROM json_each(?))
145
+ )
146
+ ELSE json_extract(metadata, '$."${jsonPathKey}"') IN (${paramPlaceholders})
147
+ END
148
+ )`,
149
+ needsValue: true,
150
+ transformValue: () => [JSON.stringify(arr), ...arr]
151
+ };
152
+ },
153
+ $nin: (key, value) => {
154
+ const jsonPathKey = parseJsonPathKey(key);
155
+ const arr = Array.isArray(value) ? value : [value];
156
+ if (arr.length === 0) {
157
+ return { sql: "1 = 1", needsValue: true, transformValue: () => [] };
158
+ }
159
+ const paramPlaceholders = arr.map(() => "?").join(",");
160
+ return {
161
+ sql: `(
162
+ CASE
163
+ WHEN ${validateJsonArray(jsonPathKey)} THEN
164
+ NOT EXISTS (
165
+ SELECT 1 FROM json_each(json_extract(metadata, '$."${jsonPathKey}"')) as elem
166
+ WHERE elem.value IN (SELECT value FROM json_each(?))
167
+ )
168
+ ELSE json_extract(metadata, '$."${jsonPathKey}"') NOT IN (${paramPlaceholders})
169
+ END
170
+ )`,
171
+ needsValue: true,
172
+ transformValue: () => [JSON.stringify(arr), ...arr]
173
+ };
174
+ },
175
+ $all: (key, value) => {
176
+ const jsonPathKey = parseJsonPathKey(key);
177
+ let sql;
178
+ const arrayValue = Array.isArray(value) ? value : [value];
179
+ if (arrayValue.length === 0) {
180
+ sql = "1 = 0";
181
+ } else {
182
+ sql = `(
183
+ CASE
184
+ WHEN ${validateJsonArray(jsonPathKey)} THEN
185
+ NOT EXISTS (
186
+ SELECT value
187
+ FROM json_each(?)
188
+ WHERE value NOT IN (
189
+ SELECT value
190
+ FROM json_each(json_extract(metadata, '$."${jsonPathKey}"'))
191
+ )
192
+ )
193
+ ELSE FALSE
194
+ END
195
+ )`;
196
+ }
197
+ return {
198
+ sql,
199
+ needsValue: true,
200
+ transformValue: () => {
201
+ if (arrayValue.length === 0) {
202
+ return [];
203
+ }
204
+ return [JSON.stringify(arrayValue)];
205
+ }
206
+ };
207
+ },
208
+ $elemMatch: (key, value) => {
209
+ const jsonPathKey = parseJsonPathKey(key);
210
+ if (typeof value !== "object" || Array.isArray(value)) {
211
+ throw new Error("$elemMatch requires an object with conditions");
212
+ }
213
+ const conditions = buildElemMatchConditions(value);
214
+ return {
215
+ sql: `(
216
+ CASE
217
+ WHEN ${validateJsonArray(jsonPathKey)} THEN
218
+ EXISTS (
219
+ SELECT 1
220
+ FROM json_each(json_extract(metadata, '$."${jsonPathKey}"')) as elem
221
+ WHERE ${conditions.map((c) => c.sql).join(" AND ")}
222
+ )
223
+ ELSE FALSE
224
+ END
225
+ )`,
226
+ needsValue: true,
227
+ transformValue: () => conditions.flatMap((c) => c.values)
228
+ };
229
+ },
230
+ // Element Operators
231
+ $exists: (key) => {
232
+ const jsonPathKey = parseJsonPathKey(key);
233
+ return {
234
+ sql: `json_extract(metadata, '$."${jsonPathKey}"') IS NOT NULL`,
235
+ needsValue: false
236
+ };
237
+ },
238
+ // Logical Operators
239
+ $and: (key) => ({
240
+ sql: `(${key})`,
241
+ needsValue: false
242
+ }),
243
+ $or: (key) => ({
244
+ sql: `(${key})`,
245
+ needsValue: false
246
+ }),
247
+ $not: (key) => ({ sql: `NOT (${key})`, needsValue: false }),
248
+ $nor: (key) => ({
249
+ sql: `NOT (${key})`,
250
+ needsValue: false
251
+ }),
252
+ $size: (key, paramIndex) => {
253
+ const jsonPathKey = parseJsonPathKey(key);
254
+ return {
255
+ sql: `(
256
+ CASE
257
+ WHEN json_type(json_extract(metadata, '$."${jsonPathKey}"')) = 'array' THEN
258
+ json_array_length(json_extract(metadata, '$."${jsonPathKey}"')) = $${paramIndex}
259
+ ELSE FALSE
260
+ END
261
+ )`,
262
+ needsValue: true
263
+ };
264
+ },
265
+ // /**
266
+ // * Regex Operators
267
+ // * Supports case insensitive and multiline
268
+ // */
269
+ // $regex: (key: string): FilterOperator => ({
270
+ // sql: `json_extract(metadata, '$."${toJsonPathKey(key)}"') = ?`,
271
+ // needsValue: true,
272
+ // transformValue: (value: any) => {
273
+ // const pattern = typeof value === 'object' ? value.$regex : value;
274
+ // const options = typeof value === 'object' ? value.$options || '' : '';
275
+ // let sql = `json_extract(metadata, '$."${toJsonPathKey(key)}"')`;
276
+ // // Handle multiline
277
+ // // if (options.includes('m')) {
278
+ // // sql = `REPLACE(${sql}, CHAR(10), '\n')`;
279
+ // // }
280
+ // // let finalPattern = pattern;
281
+ // // if (options) {
282
+ // // finalPattern = `(\\?${options})${pattern}`;
283
+ // // }
284
+ // // // Handle case insensitivity
285
+ // // if (options.includes('i')) {
286
+ // // sql = `LOWER(${sql}) REGEXP LOWER(?)`;
287
+ // // } else {
288
+ // // sql = `${sql} REGEXP ?`;
289
+ // // }
290
+ // if (options.includes('m')) {
291
+ // sql = `EXISTS (
292
+ // SELECT 1
293
+ // FROM json_each(
294
+ // json_array(
295
+ // ${sql},
296
+ // REPLACE(${sql}, CHAR(10), CHAR(13))
297
+ // )
298
+ // ) as lines
299
+ // WHERE lines.value REGEXP ?
300
+ // )`;
301
+ // } else {
302
+ // sql = `${sql} REGEXP ?`;
303
+ // }
304
+ // // Handle case insensitivity
305
+ // if (options.includes('i')) {
306
+ // sql = sql.replace('REGEXP ?', 'REGEXP LOWER(?)');
307
+ // sql = sql.replace('value REGEXP', 'LOWER(value) REGEXP');
308
+ // }
309
+ // // Handle extended - allows whitespace and comments in pattern
310
+ // if (options.includes('x')) {
311
+ // // Remove whitespace and comments from pattern
312
+ // const cleanPattern = pattern.replace(/\s+|#.*$/gm, '');
313
+ // return {
314
+ // sql,
315
+ // values: [cleanPattern],
316
+ // };
317
+ // }
318
+ // return {
319
+ // sql,
320
+ // values: [pattern],
321
+ // };
322
+ // },
323
+ // }),
324
+ $contains: (key, value) => {
325
+ const jsonPathKey = parseJsonPathKey(key);
326
+ let sql;
327
+ if (Array.isArray(value)) {
328
+ sql = `(
329
+ SELECT ${validateJsonArray(jsonPathKey)}
330
+ AND EXISTS (
331
+ SELECT 1
332
+ FROM json_each(json_extract(metadata, '$."${jsonPathKey}"')) as m
333
+ WHERE m.value IN (SELECT value FROM json_each(?))
334
+ )
335
+ )`;
336
+ } else if (typeof value === "string") {
337
+ sql = `lower(json_extract(metadata, '$."${jsonPathKey}"')) LIKE '%' || lower(?) || '%' ESCAPE '\\'`;
338
+ } else {
339
+ sql = `json_extract(metadata, '$."${jsonPathKey}"') = ?`;
340
+ }
341
+ return {
342
+ sql,
343
+ needsValue: true,
344
+ transformValue: () => {
345
+ if (Array.isArray(value)) {
346
+ return [JSON.stringify(value)];
347
+ }
348
+ if (typeof value === "object" && value !== null) {
349
+ return [JSON.stringify(value)];
350
+ }
351
+ if (typeof value === "string") {
352
+ return [escapeLikePattern(value)];
353
+ }
354
+ return [value];
355
+ }
356
+ };
357
+ }
358
+ /**
359
+ * $objectContains: True JSON containment for advanced use (deep sub-object match).
360
+ * Usage: { field: { $objectContains: { ...subobject } } }
361
+ */
362
+ // $objectContains: (key: string) => ({
363
+ // sql: '', // Will be overridden by transformValue
364
+ // needsValue: true,
365
+ // transformValue: (value: any) => ({
366
+ // sql: `json_type(json_extract(metadata, '$."${toJsonPathKey(key)}"')) = 'object'
367
+ // AND json_patch(json_extract(metadata, '$."${toJsonPathKey(key)}"'), ?) = json_extract(metadata, '$."${toJsonPathKey(key)}"')`,
368
+ // values: [JSON.stringify(value)],
369
+ // }),
370
+ // }),
371
+ };
372
+ function isFilterResult(obj) {
373
+ return obj && typeof obj === "object" && typeof obj.sql === "string" && Array.isArray(obj.values);
374
+ }
375
+ var parseJsonPathKey = (key) => {
376
+ const parsedKey = utils.parseFieldKey(key);
377
+ return parsedKey.replace(/\./g, '"."');
378
+ };
379
+ function escapeLikePattern(str) {
380
+ return str.replace(/([%_\\])/g, "\\$1");
381
+ }
382
+ function buildFilterQuery(filter) {
383
+ if (!filter) {
384
+ return { sql: "", values: [] };
385
+ }
386
+ const values = [];
387
+ const conditions = Object.entries(filter).map(([key, value]) => {
388
+ const condition = buildCondition(key, value);
389
+ values.push(...condition.values);
390
+ return condition.sql;
391
+ }).join(" AND ");
392
+ return {
393
+ sql: conditions ? `WHERE ${conditions}` : "",
394
+ values
395
+ };
396
+ }
397
+ function buildCondition(key, value, parentPath) {
398
+ if (["$and", "$or", "$not", "$nor"].includes(key)) {
399
+ return handleLogicalOperator(key, value);
400
+ }
401
+ if (!value || typeof value !== "object") {
402
+ return {
403
+ sql: `json_extract(metadata, '$."${key.replace(/\./g, '"."')}"') = ?`,
404
+ values: [value]
405
+ };
406
+ }
407
+ return handleOperator(key, value);
408
+ }
409
+ function handleLogicalOperator(key, value, parentPath) {
410
+ if (!value || value.length === 0) {
411
+ switch (key) {
412
+ case "$and":
413
+ case "$nor":
414
+ return { sql: "true", values: [] };
415
+ case "$or":
416
+ return { sql: "false", values: [] };
417
+ case "$not":
418
+ throw new Error("$not operator cannot be empty");
419
+ default:
420
+ return { sql: "true", values: [] };
421
+ }
422
+ }
423
+ if (key === "$not") {
424
+ const entries = Object.entries(value);
425
+ const conditions2 = entries.map(([fieldKey, fieldValue]) => buildCondition(fieldKey, fieldValue));
426
+ return {
427
+ sql: `NOT (${conditions2.map((c) => c.sql).join(" AND ")})`,
428
+ values: conditions2.flatMap((c) => c.values)
429
+ };
430
+ }
431
+ const values = [];
432
+ const joinOperator = key === "$or" || key === "$nor" ? "OR" : "AND";
433
+ const conditions = Array.isArray(value) ? value.map((f) => {
434
+ const entries = Object.entries(f);
435
+ return entries.map(([k, v]) => buildCondition(k, v));
436
+ }) : [buildCondition(key, value)];
437
+ const joined = conditions.flat().map((c) => {
438
+ values.push(...c.values);
439
+ return c.sql;
440
+ }).join(` ${joinOperator} `);
441
+ return {
442
+ sql: key === "$nor" ? `NOT (${joined})` : `(${joined})`,
443
+ values
444
+ };
445
+ }
446
+ function handleOperator(key, value) {
447
+ if (typeof value === "object" && !Array.isArray(value)) {
448
+ const entries = Object.entries(value);
449
+ const results = entries.map(
450
+ ([operator2, operatorValue2]) => operator2 === "$not" ? {
451
+ sql: `NOT (${Object.entries(operatorValue2).map(([op, val]) => processOperator(key, op, val).sql).join(" AND ")})`,
452
+ values: Object.entries(operatorValue2).flatMap(
453
+ ([op, val]) => processOperator(key, op, val).values
454
+ )
455
+ } : processOperator(key, operator2, operatorValue2)
456
+ );
457
+ return {
458
+ sql: `(${results.map((r) => r.sql).join(" AND ")})`,
459
+ values: results.flatMap((r) => r.values)
460
+ };
461
+ }
462
+ const [[operator, operatorValue] = []] = Object.entries(value);
463
+ return processOperator(key, operator, operatorValue);
464
+ }
465
+ var processOperator = (key, operator, operatorValue) => {
466
+ if (!operator.startsWith("$") || !FILTER_OPERATORS[operator]) {
467
+ throw new Error(`Invalid operator: ${operator}`);
468
+ }
469
+ const operatorFn = FILTER_OPERATORS[operator];
470
+ const operatorResult = operatorFn(key, operatorValue);
471
+ if (!operatorResult.needsValue) {
472
+ return { sql: operatorResult.sql, values: [] };
473
+ }
474
+ const transformed = operatorResult.transformValue ? operatorResult.transformValue() : operatorValue;
475
+ if (isFilterResult(transformed)) {
476
+ return transformed;
477
+ }
478
+ return {
479
+ sql: operatorResult.sql,
480
+ values: Array.isArray(transformed) ? transformed : [transformed]
481
+ };
482
+ };
483
+
484
+ // src/vector/index.ts
485
+ var LibSQLVector = class extends vector.MastraVector {
486
+ turso;
487
+ constructor({
488
+ connectionUrl,
489
+ authToken,
490
+ syncUrl,
491
+ syncInterval
492
+ }) {
493
+ super();
494
+ this.turso = client.createClient({
495
+ url: connectionUrl,
496
+ syncUrl,
497
+ authToken,
498
+ syncInterval
499
+ });
500
+ if (connectionUrl.includes(`file:`) || connectionUrl.includes(`:memory:`)) {
501
+ void this.turso.execute({
502
+ sql: "PRAGMA journal_mode=WAL;",
503
+ args: {}
504
+ });
505
+ }
506
+ }
507
+ transformFilter(filter) {
508
+ const translator = new LibSQLFilterTranslator();
509
+ return translator.translate(filter);
510
+ }
511
+ async query(...args) {
512
+ const params = this.normalizeArgs("query", args, ["minScore"]);
513
+ try {
514
+ const { indexName, queryVector, topK = 10, filter, includeVector = false, minScore = 0 } = params;
515
+ if (!Number.isInteger(topK) || topK <= 0) {
516
+ throw new Error("topK must be a positive integer");
517
+ }
518
+ if (!Array.isArray(queryVector) || !queryVector.every((x) => typeof x === "number" && Number.isFinite(x))) {
519
+ throw new Error("queryVector must be an array of finite numbers");
520
+ }
521
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
522
+ const vectorStr = `[${queryVector.join(",")}]`;
523
+ const translatedFilter = this.transformFilter(filter);
524
+ const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
525
+ filterValues.push(minScore);
526
+ filterValues.push(topK);
527
+ const query = `
528
+ WITH vector_scores AS (
529
+ SELECT
530
+ vector_id as id,
531
+ (1-vector_distance_cos(embedding, '${vectorStr}')) as score,
532
+ metadata
533
+ ${includeVector ? ", vector_extract(embedding) as embedding" : ""}
534
+ FROM ${parsedIndexName}
535
+ ${filterQuery}
536
+ )
537
+ SELECT *
538
+ FROM vector_scores
539
+ WHERE score > ?
540
+ ORDER BY score DESC
541
+ LIMIT ?`;
542
+ const result = await this.turso.execute({
543
+ sql: query,
544
+ args: filterValues
545
+ });
546
+ return result.rows.map(({ id, score, metadata, embedding }) => ({
547
+ id,
548
+ score,
549
+ metadata: JSON.parse(metadata ?? "{}"),
550
+ ...includeVector && embedding && { vector: JSON.parse(embedding) }
551
+ }));
552
+ } finally {
553
+ }
554
+ }
555
+ async upsert(...args) {
556
+ const params = this.normalizeArgs("upsert", args);
557
+ const { indexName, vectors, metadata, ids } = params;
558
+ const tx = await this.turso.transaction("write");
559
+ try {
560
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
561
+ const vectorIds = ids || vectors.map(() => crypto.randomUUID());
562
+ for (let i = 0; i < vectors.length; i++) {
563
+ const query = `
564
+ INSERT INTO ${parsedIndexName} (vector_id, embedding, metadata)
565
+ VALUES (?, vector32(?), ?)
566
+ ON CONFLICT(vector_id) DO UPDATE SET
567
+ embedding = vector32(?),
568
+ metadata = ?
569
+ `;
570
+ await tx.execute({
571
+ sql: query,
572
+ // @ts-ignore
573
+ args: [
574
+ vectorIds[i],
575
+ JSON.stringify(vectors[i]),
576
+ JSON.stringify(metadata?.[i] || {}),
577
+ JSON.stringify(vectors[i]),
578
+ JSON.stringify(metadata?.[i] || {})
579
+ ]
580
+ });
581
+ }
582
+ await tx.commit();
583
+ return vectorIds;
584
+ } catch (error) {
585
+ await tx.rollback();
586
+ if (error instanceof Error && error.message?.includes("dimensions are different")) {
587
+ const match = error.message.match(/dimensions are different: (\d+) != (\d+)/);
588
+ if (match) {
589
+ const [, actual, expected] = match;
590
+ throw new Error(
591
+ `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.`
592
+ );
593
+ }
594
+ }
595
+ throw error;
596
+ }
597
+ }
598
+ async createIndex(...args) {
599
+ const params = this.normalizeArgs("createIndex", args);
600
+ const { indexName, dimension } = params;
601
+ try {
602
+ if (!Number.isInteger(dimension) || dimension <= 0) {
603
+ throw new Error("Dimension must be a positive integer");
604
+ }
605
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
606
+ await this.turso.execute({
607
+ sql: `
608
+ CREATE TABLE IF NOT EXISTS ${parsedIndexName} (
609
+ id SERIAL PRIMARY KEY,
610
+ vector_id TEXT UNIQUE NOT NULL,
611
+ embedding F32_BLOB(${dimension}),
612
+ metadata TEXT DEFAULT '{}'
613
+ );
614
+ `,
615
+ args: []
616
+ });
617
+ await this.turso.execute({
618
+ sql: `
619
+ CREATE INDEX IF NOT EXISTS ${parsedIndexName}_vector_idx
620
+ ON ${parsedIndexName} (libsql_vector_idx(embedding))
621
+ `,
622
+ args: []
623
+ });
624
+ } catch (error) {
625
+ console.error("Failed to create vector table:", error);
626
+ throw error;
627
+ } finally {
628
+ }
629
+ }
630
+ async deleteIndex(...args) {
631
+ const params = this.normalizeArgs("deleteIndex", args);
632
+ const { indexName } = params;
633
+ try {
634
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
635
+ await this.turso.execute({
636
+ sql: `DROP TABLE IF EXISTS ${parsedIndexName}`,
637
+ args: []
638
+ });
639
+ } catch (error) {
640
+ console.error("Failed to delete vector table:", error);
641
+ throw new Error(`Failed to delete vector table: ${error.message}`);
642
+ } finally {
643
+ }
644
+ }
645
+ async listIndexes() {
646
+ try {
647
+ const vectorTablesQuery = `
648
+ SELECT name FROM sqlite_master
649
+ WHERE type='table'
650
+ AND sql LIKE '%F32_BLOB%';
651
+ `;
652
+ const result = await this.turso.execute({
653
+ sql: vectorTablesQuery,
654
+ args: []
655
+ });
656
+ return result.rows.map((row) => row.name);
657
+ } catch (error) {
658
+ throw new Error(`Failed to list vector tables: ${error.message}`);
659
+ }
660
+ }
661
+ /**
662
+ * Retrieves statistics about a vector index.
663
+ *
664
+ * @param params - The parameters for describing an index
665
+ * @param params.indexName - The name of the index to describe
666
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
667
+ */
668
+ async describeIndex(...args) {
669
+ const params = this.normalizeArgs("describeIndex", args);
670
+ const { indexName } = params;
671
+ try {
672
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
673
+ const tableInfoQuery = `
674
+ SELECT sql
675
+ FROM sqlite_master
676
+ WHERE type='table'
677
+ AND name = ?;
678
+ `;
679
+ const tableInfo = await this.turso.execute({
680
+ sql: tableInfoQuery,
681
+ args: [parsedIndexName]
682
+ });
683
+ if (!tableInfo.rows[0]?.sql) {
684
+ throw new Error(`Table ${parsedIndexName} not found`);
685
+ }
686
+ const dimension = parseInt(tableInfo.rows[0].sql.match(/F32_BLOB\((\d+)\)/)?.[1] || "0");
687
+ const countQuery = `
688
+ SELECT COUNT(*) as count
689
+ FROM ${parsedIndexName};
690
+ `;
691
+ const countResult = await this.turso.execute({
692
+ sql: countQuery,
693
+ args: []
694
+ });
695
+ const metric = "cosine";
696
+ return {
697
+ dimension,
698
+ count: countResult?.rows?.[0]?.count ?? 0,
699
+ metric
700
+ };
701
+ } catch (e) {
702
+ throw new Error(`Failed to describe vector table: ${e.message}`);
703
+ }
704
+ }
705
+ /**
706
+ * @deprecated Use {@link updateVector} instead. This method will be removed on May 20th, 2025.
707
+ *
708
+ * Updates a vector by its ID with the provided vector and/or metadata.
709
+ * @param indexName - The name of the index containing the vector.
710
+ * @param id - The ID of the vector to update.
711
+ * @param update - An object containing the vector and/or metadata to update.
712
+ * @param update.vector - An optional array of numbers representing the new vector.
713
+ * @param update.metadata - An optional record containing the new metadata.
714
+ * @returns A promise that resolves when the update is complete.
715
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
716
+ */
717
+ async updateIndexById(indexName, id, update) {
718
+ this.logger.warn(
719
+ `Deprecation Warning: updateIndexById() is deprecated.
720
+ Please use updateVector() instead.
721
+ updateIndexById() will be removed on May 20th, 2025.`
722
+ );
723
+ await this.updateVector({ indexName, id, update });
724
+ }
725
+ /**
726
+ * Updates a vector by its ID with the provided vector and/or metadata.
727
+ *
728
+ * @param indexName - The name of the index containing the vector.
729
+ * @param id - The ID of the vector to update.
730
+ * @param update - An object containing the vector and/or metadata to update.
731
+ * @param update.vector - An optional array of numbers representing the new vector.
732
+ * @param update.metadata - An optional record containing the new metadata.
733
+ * @returns A promise that resolves when the update is complete.
734
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
735
+ */
736
+ async updateVector(...args) {
737
+ const params = this.normalizeArgs("updateVector", args);
738
+ const { indexName, id, update } = params;
739
+ try {
740
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
741
+ const updates = [];
742
+ const args2 = [];
743
+ if (update.vector) {
744
+ updates.push("embedding = vector32(?)");
745
+ args2.push(JSON.stringify(update.vector));
746
+ }
747
+ if (update.metadata) {
748
+ updates.push("metadata = ?");
749
+ args2.push(JSON.stringify(update.metadata));
750
+ }
751
+ if (updates.length === 0) {
752
+ throw new Error("No updates provided");
753
+ }
754
+ args2.push(id);
755
+ const query = `
756
+ UPDATE ${parsedIndexName}
757
+ SET ${updates.join(", ")}
758
+ WHERE vector_id = ?;
759
+ `;
760
+ await this.turso.execute({
761
+ sql: query,
762
+ args: args2
763
+ });
764
+ } catch (error) {
765
+ throw new Error(`Failed to update vector by id: ${id} for index: ${indexName}: ${error.message}`);
766
+ }
767
+ }
768
+ /**
769
+ * @deprecated Use {@link deleteVector} instead. This method will be removed on May 20th, 2025.
770
+ *
771
+ * Deletes a vector by its ID.
772
+ * @param indexName - The name of the index containing the vector.
773
+ * @param id - The ID of the vector to delete.
774
+ * @returns A promise that resolves when the deletion is complete.
775
+ * @throws Will throw an error if the deletion operation fails.
776
+ */
777
+ async deleteIndexById(indexName, id) {
778
+ this.logger.warn(
779
+ `Deprecation Warning: deleteIndexById() is deprecated.
780
+ Please use deleteVector() instead.
781
+ deleteIndexById() will be removed on May 20th, 2025.`
782
+ );
783
+ await this.deleteVector({ indexName, id });
784
+ }
785
+ /**
786
+ * Deletes a vector by its ID.
787
+ * @param indexName - The name of the index containing the vector.
788
+ * @param id - The ID of the vector to delete.
789
+ * @returns A promise that resolves when the deletion is complete.
790
+ * @throws Will throw an error if the deletion operation fails.
791
+ */
792
+ async deleteVector(...args) {
793
+ const params = this.normalizeArgs("deleteVector", args);
794
+ const { indexName, id } = params;
795
+ try {
796
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
797
+ await this.turso.execute({
798
+ sql: `DELETE FROM ${parsedIndexName} WHERE vector_id = ?`,
799
+ args: [id]
800
+ });
801
+ } catch (error) {
802
+ throw new Error(`Failed to delete vector by id: ${id} for index: ${indexName}: ${error.message}`);
803
+ }
804
+ }
805
+ async truncateIndex(...args) {
806
+ const params = this.normalizeArgs("truncateIndex", args);
807
+ const { indexName } = params;
808
+ await this.turso.execute({
809
+ sql: `DELETE FROM ${utils.parseSqlIdentifier(indexName, "index name")}`,
810
+ args: []
811
+ });
812
+ }
813
+ };
814
+ function safelyParseJSON(jsonString) {
815
+ try {
816
+ return JSON.parse(jsonString);
817
+ } catch {
818
+ return {};
819
+ }
820
+ }
821
+ var LibSQLStore = class extends storage.MastraStorage {
822
+ client;
823
+ constructor(config) {
824
+ super({ name: `LibSQLStore` });
825
+ if (config.url.endsWith(":memory:")) {
826
+ this.shouldCacheInit = false;
827
+ }
828
+ this.client = client.createClient(config);
829
+ }
830
+ getCreateTableSQL(tableName, schema) {
831
+ const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
832
+ const columns = Object.entries(schema).map(([name, col]) => {
833
+ const parsedColumnName = utils.parseSqlIdentifier(name, "column name");
834
+ let type = col.type.toUpperCase();
835
+ if (type === "TEXT") type = "TEXT";
836
+ if (type === "TIMESTAMP") type = "TEXT";
837
+ const nullable = col.nullable ? "" : "NOT NULL";
838
+ const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
839
+ return `${parsedColumnName} ${type} ${nullable} ${primaryKey}`.trim();
840
+ });
841
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
842
+ const stmnt = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (
843
+ ${columns.join(",\n")},
844
+ PRIMARY KEY (workflow_name, run_id)
845
+ )`;
846
+ return stmnt;
847
+ }
848
+ return `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns.join(", ")})`;
849
+ }
850
+ async createTable({
851
+ tableName,
852
+ schema
853
+ }) {
854
+ try {
855
+ this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
856
+ const sql = this.getCreateTableSQL(tableName, schema);
857
+ await this.client.execute(sql);
858
+ } catch (error) {
859
+ this.logger.error(`Error creating table ${tableName}: ${error}`);
860
+ throw error;
861
+ }
862
+ }
863
+ async clearTable({ tableName }) {
864
+ const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
865
+ try {
866
+ await this.client.execute(`DELETE FROM ${parsedTableName}`);
867
+ } catch (e) {
868
+ if (e instanceof Error) {
869
+ this.logger.error(e.message);
870
+ }
871
+ }
872
+ }
873
+ prepareStatement({ tableName, record }) {
874
+ const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
875
+ const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
876
+ const values = Object.values(record).map((v) => {
877
+ if (typeof v === `undefined`) {
878
+ return null;
879
+ }
880
+ if (v instanceof Date) {
881
+ return v.toISOString();
882
+ }
883
+ return typeof v === "object" ? JSON.stringify(v) : v;
884
+ });
885
+ const placeholders = values.map(() => "?").join(", ");
886
+ return {
887
+ sql: `INSERT OR REPLACE INTO ${parsedTableName} (${columns.join(", ")}) VALUES (${placeholders})`,
888
+ args: values
889
+ };
890
+ }
891
+ async insert({ tableName, record }) {
892
+ try {
893
+ await this.client.execute(
894
+ this.prepareStatement({
895
+ tableName,
896
+ record
897
+ })
898
+ );
899
+ } catch (error) {
900
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
901
+ throw error;
902
+ }
903
+ }
904
+ async batchInsert({ tableName, records }) {
905
+ if (records.length === 0) return;
906
+ try {
907
+ const batchStatements = records.map((r) => this.prepareStatement({ tableName, record: r }));
908
+ await this.client.batch(batchStatements, "write");
909
+ } catch (error) {
910
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
911
+ throw error;
912
+ }
913
+ }
914
+ async load({ tableName, keys }) {
915
+ const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
916
+ const parsedKeys = Object.keys(keys).map((key) => utils.parseSqlIdentifier(key, "column name"));
917
+ const conditions = parsedKeys.map((key) => `${key} = ?`).join(" AND ");
918
+ const values = Object.values(keys);
919
+ const result = await this.client.execute({
920
+ sql: `SELECT * FROM ${parsedTableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
921
+ args: values
922
+ });
923
+ if (!result.rows || result.rows.length === 0) {
924
+ return null;
925
+ }
926
+ const row = result.rows[0];
927
+ const parsed = Object.fromEntries(
928
+ Object.entries(row || {}).map(([k, v]) => {
929
+ try {
930
+ return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
931
+ } catch {
932
+ return [k, v];
933
+ }
934
+ })
935
+ );
936
+ return parsed;
937
+ }
938
+ async getThreadById({ threadId }) {
939
+ const result = await this.load({
940
+ tableName: storage.TABLE_THREADS,
941
+ keys: { id: threadId }
942
+ });
943
+ if (!result) {
944
+ return null;
945
+ }
946
+ return {
947
+ ...result,
948
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
949
+ };
950
+ }
951
+ async getThreadsByResourceId({ resourceId }) {
952
+ const result = await this.client.execute({
953
+ sql: `SELECT * FROM ${storage.TABLE_THREADS} WHERE resourceId = ?`,
954
+ args: [resourceId]
955
+ });
956
+ if (!result.rows) {
957
+ return [];
958
+ }
959
+ return result.rows.map((thread) => ({
960
+ id: thread.id,
961
+ resourceId: thread.resourceId,
962
+ title: thread.title,
963
+ createdAt: thread.createdAt,
964
+ updatedAt: thread.updatedAt,
965
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
966
+ }));
967
+ }
968
+ async saveThread({ thread }) {
969
+ await this.insert({
970
+ tableName: storage.TABLE_THREADS,
971
+ record: {
972
+ ...thread,
973
+ metadata: JSON.stringify(thread.metadata)
974
+ }
975
+ });
976
+ return thread;
977
+ }
978
+ async updateThread({
979
+ id,
980
+ title,
981
+ metadata
982
+ }) {
983
+ const thread = await this.getThreadById({ threadId: id });
984
+ if (!thread) {
985
+ throw new Error(`Thread ${id} not found`);
986
+ }
987
+ const updatedThread = {
988
+ ...thread,
989
+ title,
990
+ metadata: {
991
+ ...thread.metadata,
992
+ ...metadata
993
+ }
994
+ };
995
+ await this.client.execute({
996
+ sql: `UPDATE ${storage.TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
997
+ args: [title, JSON.stringify(updatedThread.metadata), id]
998
+ });
999
+ return updatedThread;
1000
+ }
1001
+ async deleteThread({ threadId }) {
1002
+ await this.client.execute({
1003
+ sql: `DELETE FROM ${storage.TABLE_THREADS} WHERE id = ?`,
1004
+ args: [threadId]
1005
+ });
1006
+ }
1007
+ parseRow(row) {
1008
+ let content = row.content;
1009
+ try {
1010
+ content = JSON.parse(row.content);
1011
+ } catch {
1012
+ }
1013
+ return {
1014
+ id: row.id,
1015
+ content,
1016
+ role: row.role,
1017
+ type: row.type,
1018
+ createdAt: new Date(row.createdAt),
1019
+ threadId: row.thread_id
1020
+ };
1021
+ }
1022
+ async getMessages({ threadId, selectBy }) {
1023
+ try {
1024
+ const messages = [];
1025
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
1026
+ if (selectBy?.include?.length) {
1027
+ const includeIds = selectBy.include.map((i) => i.id);
1028
+ const maxPrev = Math.max(...selectBy.include.map((i) => i.withPreviousMessages || 0));
1029
+ const maxNext = Math.max(...selectBy.include.map((i) => i.withNextMessages || 0));
1030
+ const includeResult = await this.client.execute({
1031
+ sql: `
1032
+ WITH numbered_messages AS (
1033
+ SELECT
1034
+ id,
1035
+ content,
1036
+ role,
1037
+ type,
1038
+ "createdAt",
1039
+ thread_id,
1040
+ ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
1041
+ FROM "${storage.TABLE_MESSAGES}"
1042
+ WHERE thread_id = ?
1043
+ ),
1044
+ target_positions AS (
1045
+ SELECT row_num as target_pos
1046
+ FROM numbered_messages
1047
+ WHERE id IN (${includeIds.map(() => "?").join(", ")})
1048
+ )
1049
+ SELECT DISTINCT m.*
1050
+ FROM numbered_messages m
1051
+ CROSS JOIN target_positions t
1052
+ WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
1053
+ ORDER BY m."createdAt" ASC
1054
+ `,
1055
+ args: [threadId, ...includeIds, maxPrev, maxNext]
1056
+ });
1057
+ if (includeResult.rows) {
1058
+ messages.push(...includeResult.rows.map((row) => this.parseRow(row)));
1059
+ }
1060
+ }
1061
+ const excludeIds = messages.map((m) => m.id);
1062
+ const remainingSql = `
1063
+ SELECT
1064
+ id,
1065
+ content,
1066
+ role,
1067
+ type,
1068
+ "createdAt",
1069
+ thread_id
1070
+ FROM "${storage.TABLE_MESSAGES}"
1071
+ WHERE thread_id = ?
1072
+ ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
1073
+ ORDER BY "createdAt" DESC
1074
+ LIMIT ?
1075
+ `;
1076
+ const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
1077
+ const remainingResult = await this.client.execute({
1078
+ sql: remainingSql,
1079
+ args: remainingArgs
1080
+ });
1081
+ if (remainingResult.rows) {
1082
+ messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
1083
+ }
1084
+ messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
1085
+ return messages;
1086
+ } catch (error) {
1087
+ this.logger.error("Error getting messages:", error);
1088
+ throw error;
1089
+ }
1090
+ }
1091
+ async saveMessages({ messages }) {
1092
+ if (messages.length === 0) return messages;
1093
+ try {
1094
+ const threadId = messages[0]?.threadId;
1095
+ if (!threadId) {
1096
+ throw new Error("Thread ID is required");
1097
+ }
1098
+ const batchStatements = messages.map((message) => {
1099
+ const time = message.createdAt || /* @__PURE__ */ new Date();
1100
+ return {
1101
+ sql: `INSERT INTO ${storage.TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
1102
+ VALUES (?, ?, ?, ?, ?, ?)`,
1103
+ args: [
1104
+ message.id,
1105
+ threadId,
1106
+ typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
1107
+ message.role,
1108
+ message.type,
1109
+ time instanceof Date ? time.toISOString() : time
1110
+ ]
1111
+ };
1112
+ });
1113
+ await this.client.batch(batchStatements, "write");
1114
+ return messages;
1115
+ } catch (error) {
1116
+ this.logger.error("Failed to save messages in database: " + error?.message);
1117
+ throw error;
1118
+ }
1119
+ }
1120
+ transformEvalRow(row) {
1121
+ const resultValue = JSON.parse(row.result);
1122
+ const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
1123
+ if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
1124
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
1125
+ }
1126
+ return {
1127
+ input: row.input,
1128
+ output: row.output,
1129
+ result: resultValue,
1130
+ agentName: row.agent_name,
1131
+ metricName: row.metric_name,
1132
+ instructions: row.instructions,
1133
+ testInfo: testInfoValue,
1134
+ globalRunId: row.global_run_id,
1135
+ runId: row.run_id,
1136
+ createdAt: row.created_at
1137
+ };
1138
+ }
1139
+ async getEvalsByAgentName(agentName, type) {
1140
+ try {
1141
+ const baseQuery = `SELECT * FROM ${storage.TABLE_EVALS} WHERE agent_name = ?`;
1142
+ 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)" : "";
1143
+ const result = await this.client.execute({
1144
+ sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
1145
+ args: [agentName]
1146
+ });
1147
+ return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
1148
+ } catch (error) {
1149
+ if (error instanceof Error && error.message.includes("no such table")) {
1150
+ return [];
1151
+ }
1152
+ this.logger.error("Failed to get evals for the specified agent: " + error?.message);
1153
+ throw error;
1154
+ }
1155
+ }
1156
+ // TODO: add types
1157
+ async getTraces({
1158
+ name,
1159
+ scope,
1160
+ page,
1161
+ perPage,
1162
+ attributes,
1163
+ filters,
1164
+ fromDate,
1165
+ toDate
1166
+ } = {
1167
+ page: 0,
1168
+ perPage: 100
1169
+ }) {
1170
+ const limit = perPage;
1171
+ const offset = page * perPage;
1172
+ const args = [];
1173
+ const conditions = [];
1174
+ if (name) {
1175
+ conditions.push("name LIKE CONCAT(?, '%')");
1176
+ }
1177
+ if (scope) {
1178
+ conditions.push("scope = ?");
1179
+ }
1180
+ if (attributes) {
1181
+ Object.keys(attributes).forEach((key) => {
1182
+ conditions.push(`attributes->>'$.${key}' = ?`);
1183
+ });
1184
+ }
1185
+ if (filters) {
1186
+ Object.entries(filters).forEach(([key, _value]) => {
1187
+ conditions.push(`${key} = ?`);
1188
+ });
1189
+ }
1190
+ if (fromDate) {
1191
+ conditions.push("createdAt >= ?");
1192
+ }
1193
+ if (toDate) {
1194
+ conditions.push("createdAt <= ?");
1195
+ }
1196
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1197
+ if (name) {
1198
+ args.push(name);
1199
+ }
1200
+ if (scope) {
1201
+ args.push(scope);
1202
+ }
1203
+ if (attributes) {
1204
+ for (const [, value] of Object.entries(attributes)) {
1205
+ args.push(value);
1206
+ }
1207
+ }
1208
+ if (filters) {
1209
+ for (const [, value] of Object.entries(filters)) {
1210
+ args.push(value);
1211
+ }
1212
+ }
1213
+ if (fromDate) {
1214
+ args.push(fromDate.toISOString());
1215
+ }
1216
+ if (toDate) {
1217
+ args.push(toDate.toISOString());
1218
+ }
1219
+ args.push(limit, offset);
1220
+ const result = await this.client.execute({
1221
+ sql: `SELECT * FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
1222
+ args
1223
+ });
1224
+ if (!result.rows) {
1225
+ return [];
1226
+ }
1227
+ return result.rows.map((row) => ({
1228
+ id: row.id,
1229
+ parentSpanId: row.parentSpanId,
1230
+ traceId: row.traceId,
1231
+ name: row.name,
1232
+ scope: row.scope,
1233
+ kind: row.kind,
1234
+ status: safelyParseJSON(row.status),
1235
+ events: safelyParseJSON(row.events),
1236
+ links: safelyParseJSON(row.links),
1237
+ attributes: safelyParseJSON(row.attributes),
1238
+ startTime: row.startTime,
1239
+ endTime: row.endTime,
1240
+ other: safelyParseJSON(row.other),
1241
+ createdAt: row.createdAt
1242
+ }));
1243
+ }
1244
+ async getWorkflowRuns({
1245
+ workflowName,
1246
+ fromDate,
1247
+ toDate,
1248
+ limit,
1249
+ offset,
1250
+ resourceId
1251
+ } = {}) {
1252
+ try {
1253
+ const conditions = [];
1254
+ const args = [];
1255
+ if (workflowName) {
1256
+ conditions.push("workflow_name = ?");
1257
+ args.push(workflowName);
1258
+ }
1259
+ if (fromDate) {
1260
+ conditions.push("createdAt >= ?");
1261
+ args.push(fromDate.toISOString());
1262
+ }
1263
+ if (toDate) {
1264
+ conditions.push("createdAt <= ?");
1265
+ args.push(toDate.toISOString());
1266
+ }
1267
+ if (resourceId) {
1268
+ const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
1269
+ if (hasResourceId) {
1270
+ conditions.push("resourceId = ?");
1271
+ args.push(resourceId);
1272
+ } else {
1273
+ console.warn(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
1274
+ }
1275
+ }
1276
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1277
+ let total = 0;
1278
+ if (limit !== void 0 && offset !== void 0) {
1279
+ const countResult = await this.client.execute({
1280
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
1281
+ args
1282
+ });
1283
+ total = Number(countResult.rows?.[0]?.count ?? 0);
1284
+ }
1285
+ const result = await this.client.execute({
1286
+ sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${limit !== void 0 && offset !== void 0 ? ` LIMIT ? OFFSET ?` : ""}`,
1287
+ args: limit !== void 0 && offset !== void 0 ? [...args, limit, offset] : args
1288
+ });
1289
+ const runs = (result.rows || []).map((row) => this.parseWorkflowRun(row));
1290
+ return { runs, total: total || runs.length };
1291
+ } catch (error) {
1292
+ console.error("Error getting workflow runs:", error);
1293
+ throw error;
1294
+ }
1295
+ }
1296
+ async getWorkflowRunById({
1297
+ runId,
1298
+ workflowName
1299
+ }) {
1300
+ const conditions = [];
1301
+ const args = [];
1302
+ if (runId) {
1303
+ conditions.push("run_id = ?");
1304
+ args.push(runId);
1305
+ }
1306
+ if (workflowName) {
1307
+ conditions.push("workflow_name = ?");
1308
+ args.push(workflowName);
1309
+ }
1310
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1311
+ const result = await this.client.execute({
1312
+ sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
1313
+ args
1314
+ });
1315
+ if (!result.rows?.[0]) {
1316
+ return null;
1317
+ }
1318
+ return this.parseWorkflowRun(result.rows[0]);
1319
+ }
1320
+ async hasColumn(table, column) {
1321
+ const result = await this.client.execute({
1322
+ sql: `PRAGMA table_info(${table})`
1323
+ });
1324
+ return (await result.rows)?.some((row) => row.name === column);
1325
+ }
1326
+ parseWorkflowRun(row) {
1327
+ let parsedSnapshot = row.snapshot;
1328
+ if (typeof parsedSnapshot === "string") {
1329
+ try {
1330
+ parsedSnapshot = JSON.parse(row.snapshot);
1331
+ } catch (e) {
1332
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1333
+ }
1334
+ }
1335
+ return {
1336
+ workflowName: row.workflow_name,
1337
+ runId: row.run_id,
1338
+ snapshot: parsedSnapshot,
1339
+ resourceId: row.resourceId,
1340
+ createdAt: new Date(row.created_at),
1341
+ updatedAt: new Date(row.updated_at)
1342
+ };
1343
+ }
1344
+ };
1345
+
1346
+ // src/vector/prompt.ts
1347
+ var LIBSQL_PROMPT = `When querying LibSQL Vector, you can ONLY use the operators listed below. Any other operators will be rejected.
1348
+ Important: Don't explain how to construct the filter - use the specified operators and fields to search the content and return relevant results.
1349
+ If a user tries to give an explicit operator that is not supported, reject the filter entirely and let them know that the operator is not supported.
1350
+
1351
+ Basic Comparison Operators:
1352
+ - $eq: Exact match (default when using field: value)
1353
+ Example: { "category": "electronics" }
1354
+ - $ne: Not equal
1355
+ Example: { "category": { "$ne": "electronics" } }
1356
+ - $gt: Greater than
1357
+ Example: { "price": { "$gt": 100 } }
1358
+ - $gte: Greater than or equal
1359
+ Example: { "price": { "$gte": 100 } }
1360
+ - $lt: Less than
1361
+ Example: { "price": { "$lt": 100 } }
1362
+ - $lte: Less than or equal
1363
+ Example: { "price": { "$lte": 100 } }
1364
+
1365
+ Array Operators:
1366
+ - $in: Match any value in array
1367
+ Example: { "category": { "$in": ["electronics", "books"] } }
1368
+ - $nin: Does not match any value in array
1369
+ Example: { "category": { "$nin": ["electronics", "books"] } }
1370
+ - $all: Match all values in array
1371
+ Example: { "tags": { "$all": ["premium", "sale"] } }
1372
+ - $elemMatch: Match array elements that meet all specified conditions
1373
+ Example: { "items": { "$elemMatch": { "price": { "$gt": 100 } } } }
1374
+ - $contains: Check if array contains value
1375
+ Example: { "tags": { "$contains": "premium" } }
1376
+
1377
+ Logical Operators:
1378
+ - $and: Logical AND (implicit when using multiple conditions)
1379
+ Example: { "$and": [{ "price": { "$gt": 100 } }, { "category": "electronics" }] }
1380
+ - $or: Logical OR
1381
+ Example: { "$or": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
1382
+ - $not: Logical NOT
1383
+ Example: { "$not": { "category": "electronics" } }
1384
+ - $nor: Logical NOR
1385
+ Example: { "$nor": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
1386
+
1387
+ Element Operators:
1388
+ - $exists: Check if field exists
1389
+ Example: { "rating": { "$exists": true } }
1390
+
1391
+ Special Operators:
1392
+ - $size: Array length check
1393
+ Example: { "tags": { "$size": 2 } }
1394
+
1395
+ Restrictions:
1396
+ - Regex patterns are not supported
1397
+ - Direct RegExp patterns will throw an error
1398
+ - Nested fields are supported using dot notation
1399
+ - Multiple conditions on the same field are supported with both implicit and explicit $and
1400
+ - Array operations work on array fields only
1401
+ - Basic operators handle array values as JSON strings
1402
+ - Empty arrays in conditions are handled gracefully
1403
+ - Only logical operators ($and, $or, $not, $nor) can be used at the top level
1404
+ - All other operators must be used within a field condition
1405
+ Valid: { "field": { "$gt": 100 } }
1406
+ Valid: { "$and": [...] }
1407
+ Invalid: { "$gt": 100 }
1408
+ Invalid: { "$contains": "value" }
1409
+ - Logical operators must contain field conditions, not direct operators
1410
+ Valid: { "$and": [{ "field": { "$gt": 100 } }] }
1411
+ Invalid: { "$and": [{ "$gt": 100 }] }
1412
+ - $not operator:
1413
+ - Must be an object
1414
+ - Cannot be empty
1415
+ - Can be used at field level or top level
1416
+ - Valid: { "$not": { "field": "value" } }
1417
+ - Valid: { "field": { "$not": { "$eq": "value" } } }
1418
+ - Other logical operators ($and, $or, $nor):
1419
+ - Can only be used at top level or nested within other logical operators
1420
+ - Can not be used on a field level, or be nested inside a field
1421
+ - Can not be used inside an operator
1422
+ - Valid: { "$and": [{ "field": { "$gt": 100 } }] }
1423
+ - Valid: { "$or": [{ "$and": [{ "field": { "$gt": 100 } }] }] }
1424
+ - Invalid: { "field": { "$and": [{ "$gt": 100 }] } }
1425
+ - Invalid: { "field": { "$or": [{ "$gt": 100 }] } }
1426
+ - Invalid: { "field": { "$gt": { "$and": [{...}] } } }
1427
+ - $elemMatch requires an object with conditions
1428
+ Valid: { "array": { "$elemMatch": { "field": "value" } } }
1429
+ Invalid: { "array": { "$elemMatch": "value" } }
1430
+
1431
+ Example Complex Query:
1432
+ {
1433
+ "$and": [
1434
+ { "category": { "$in": ["electronics", "computers"] } },
1435
+ { "price": { "$gte": 100, "$lte": 1000 } },
1436
+ { "tags": { "$all": ["premium", "sale"] } },
1437
+ { "items": { "$elemMatch": { "price": { "$gt": 50 }, "inStock": true } } },
1438
+ { "$or": [
1439
+ { "stock": { "$gt": 0 } },
1440
+ { "preorder": true }
1441
+ ]}
1442
+ ]
1443
+ }`;
1444
+
1445
+ exports.DefaultStorage = LibSQLStore;
1446
+ exports.LIBSQL_PROMPT = LIBSQL_PROMPT;
1447
+ exports.LibSQLStore = LibSQLStore;
1448
+ exports.LibSQLVector = LibSQLVector;