@mastra/libsql 0.0.0-add-runtime-context-to-openai-realtime-20250516201052 → 0.0.0-add-libsql-changeset-20250910154739
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/CHANGELOG.md +842 -2
- package/LICENSE.md +12 -4
- package/dist/index.cjs +2677 -552
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +4 -5
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2670 -545
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +18 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +95 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/observability/index.d.ts +34 -0
- package/dist/storage/domains/observability/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +110 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +46 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/traces/index.d.ts +21 -0
- package/dist/storage/domains/traces/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +60 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +59 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +270 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/vector/filter.d.ts +29 -0
- package/dist/vector/filter.d.ts.map +1 -0
- package/dist/vector/index.d.ts +72 -0
- package/dist/vector/index.d.ts.map +1 -0
- package/dist/vector/prompt.d.ts +6 -0
- package/dist/vector/prompt.d.ts.map +1 -0
- package/dist/vector/sql-builder.d.ts +9 -0
- package/dist/vector/sql-builder.d.ts.map +1 -0
- package/package.json +31 -14
- package/dist/_tsup-dts-rollup.d.cts +0 -222
- package/dist/_tsup-dts-rollup.d.ts +0 -222
- package/dist/index.d.cts +0 -5
- package/eslint.config.js +0 -6
- package/src/index.ts +0 -3
- package/src/storage/index.test.ts +0 -15
- package/src/storage/index.ts +0 -710
- package/src/vector/filter.test.ts +0 -968
- package/src/vector/filter.ts +0 -117
- package/src/vector/index.test.ts +0 -1780
- package/src/vector/index.ts +0 -429
- package/src/vector/prompt.ts +0 -101
- package/src/vector/sql-builder.ts +0 -530
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -11
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var client = require('@libsql/client');
|
|
4
|
+
var error = require('@mastra/core/error');
|
|
4
5
|
var utils = require('@mastra/core/utils');
|
|
5
6
|
var vector = require('@mastra/core/vector');
|
|
6
7
|
var filter = require('@mastra/core/vector/filter');
|
|
7
8
|
var storage = require('@mastra/core/storage');
|
|
9
|
+
var agent = require('@mastra/core/agent');
|
|
8
10
|
|
|
9
11
|
// src/vector/index.ts
|
|
10
12
|
var LibSQLFilterTranslator = class extends filter.BaseFilterTranslator {
|
|
@@ -75,11 +77,11 @@ var LibSQLFilterTranslator = class extends filter.BaseFilterTranslator {
|
|
|
75
77
|
};
|
|
76
78
|
var createBasicOperator = (symbol) => {
|
|
77
79
|
return (key, value) => {
|
|
78
|
-
const
|
|
80
|
+
const jsonPath = getJsonPath(key);
|
|
79
81
|
return {
|
|
80
82
|
sql: `CASE
|
|
81
|
-
WHEN ? IS NULL THEN json_extract(metadata,
|
|
82
|
-
ELSE json_extract(metadata,
|
|
83
|
+
WHEN ? IS NULL THEN json_extract(metadata, ${jsonPath}) IS ${symbol === "=" ? "" : "NOT"} NULL
|
|
84
|
+
ELSE json_extract(metadata, ${jsonPath}) ${symbol} ?
|
|
83
85
|
END`,
|
|
84
86
|
needsValue: true,
|
|
85
87
|
transformValue: () => {
|
|
@@ -90,16 +92,19 @@ var createBasicOperator = (symbol) => {
|
|
|
90
92
|
};
|
|
91
93
|
var createNumericOperator = (symbol) => {
|
|
92
94
|
return (key) => {
|
|
93
|
-
const
|
|
95
|
+
const jsonPath = getJsonPath(key);
|
|
94
96
|
return {
|
|
95
|
-
sql: `CAST(json_extract(metadata,
|
|
97
|
+
sql: `CAST(json_extract(metadata, ${jsonPath}) AS NUMERIC) ${symbol} ?`,
|
|
96
98
|
needsValue: true
|
|
97
99
|
};
|
|
98
100
|
};
|
|
99
101
|
};
|
|
100
|
-
var validateJsonArray = (key) =>
|
|
101
|
-
|
|
102
|
-
|
|
102
|
+
var validateJsonArray = (key) => {
|
|
103
|
+
const jsonPath = getJsonPath(key);
|
|
104
|
+
return `json_valid(json_extract(metadata, ${jsonPath}))
|
|
105
|
+
AND json_type(json_extract(metadata, ${jsonPath})) = 'array'`;
|
|
106
|
+
};
|
|
107
|
+
var pattern = /json_extract\(metadata, '\$\.(?:"[^"]*"(?:\."[^"]*")*|[^']+)'\)/g;
|
|
103
108
|
function buildElemMatchConditions(value) {
|
|
104
109
|
const conditions = Object.entries(value).map(([field, fieldValue]) => {
|
|
105
110
|
if (field.startsWith("$")) {
|
|
@@ -108,12 +113,13 @@ function buildElemMatchConditions(value) {
|
|
|
108
113
|
return { sql: elemSql, values };
|
|
109
114
|
} else if (typeof fieldValue === "object" && !Array.isArray(fieldValue)) {
|
|
110
115
|
const { sql, values } = buildCondition(field, fieldValue);
|
|
111
|
-
const
|
|
116
|
+
const jsonPath = parseJsonPathKey(field);
|
|
117
|
+
const elemSql = sql.replace(pattern, `json_extract(elem.value, '$.${jsonPath}')`);
|
|
112
118
|
return { sql: elemSql, values };
|
|
113
119
|
} else {
|
|
114
|
-
const
|
|
120
|
+
const jsonPath = parseJsonPathKey(field);
|
|
115
121
|
return {
|
|
116
|
-
sql: `json_extract(elem.value, '
|
|
122
|
+
sql: `json_extract(elem.value, '$.${jsonPath}') = ?`,
|
|
117
123
|
values: [fieldValue]
|
|
118
124
|
};
|
|
119
125
|
}
|
|
@@ -129,7 +135,7 @@ var FILTER_OPERATORS = {
|
|
|
129
135
|
$lte: createNumericOperator("<="),
|
|
130
136
|
// Array Operators
|
|
131
137
|
$in: (key, value) => {
|
|
132
|
-
const
|
|
138
|
+
const jsonPath = getJsonPath(key);
|
|
133
139
|
const arr = Array.isArray(value) ? value : [value];
|
|
134
140
|
if (arr.length === 0) {
|
|
135
141
|
return { sql: "1 = 0", needsValue: true, transformValue: () => [] };
|
|
@@ -138,12 +144,12 @@ var FILTER_OPERATORS = {
|
|
|
138
144
|
return {
|
|
139
145
|
sql: `(
|
|
140
146
|
CASE
|
|
141
|
-
WHEN ${validateJsonArray(
|
|
147
|
+
WHEN ${validateJsonArray(key)} THEN
|
|
142
148
|
EXISTS (
|
|
143
|
-
SELECT 1 FROM json_each(json_extract(metadata,
|
|
149
|
+
SELECT 1 FROM json_each(json_extract(metadata, ${jsonPath})) as elem
|
|
144
150
|
WHERE elem.value IN (SELECT value FROM json_each(?))
|
|
145
151
|
)
|
|
146
|
-
ELSE json_extract(metadata,
|
|
152
|
+
ELSE json_extract(metadata, ${jsonPath}) IN (${paramPlaceholders})
|
|
147
153
|
END
|
|
148
154
|
)`,
|
|
149
155
|
needsValue: true,
|
|
@@ -151,7 +157,7 @@ var FILTER_OPERATORS = {
|
|
|
151
157
|
};
|
|
152
158
|
},
|
|
153
159
|
$nin: (key, value) => {
|
|
154
|
-
const
|
|
160
|
+
const jsonPath = getJsonPath(key);
|
|
155
161
|
const arr = Array.isArray(value) ? value : [value];
|
|
156
162
|
if (arr.length === 0) {
|
|
157
163
|
return { sql: "1 = 1", needsValue: true, transformValue: () => [] };
|
|
@@ -160,12 +166,12 @@ var FILTER_OPERATORS = {
|
|
|
160
166
|
return {
|
|
161
167
|
sql: `(
|
|
162
168
|
CASE
|
|
163
|
-
WHEN ${validateJsonArray(
|
|
169
|
+
WHEN ${validateJsonArray(key)} THEN
|
|
164
170
|
NOT EXISTS (
|
|
165
|
-
SELECT 1 FROM json_each(json_extract(metadata,
|
|
171
|
+
SELECT 1 FROM json_each(json_extract(metadata, ${jsonPath})) as elem
|
|
166
172
|
WHERE elem.value IN (SELECT value FROM json_each(?))
|
|
167
173
|
)
|
|
168
|
-
ELSE json_extract(metadata,
|
|
174
|
+
ELSE json_extract(metadata, ${jsonPath}) NOT IN (${paramPlaceholders})
|
|
169
175
|
END
|
|
170
176
|
)`,
|
|
171
177
|
needsValue: true,
|
|
@@ -173,7 +179,7 @@ var FILTER_OPERATORS = {
|
|
|
173
179
|
};
|
|
174
180
|
},
|
|
175
181
|
$all: (key, value) => {
|
|
176
|
-
const
|
|
182
|
+
const jsonPath = getJsonPath(key);
|
|
177
183
|
let sql;
|
|
178
184
|
const arrayValue = Array.isArray(value) ? value : [value];
|
|
179
185
|
if (arrayValue.length === 0) {
|
|
@@ -181,13 +187,13 @@ var FILTER_OPERATORS = {
|
|
|
181
187
|
} else {
|
|
182
188
|
sql = `(
|
|
183
189
|
CASE
|
|
184
|
-
WHEN ${validateJsonArray(
|
|
190
|
+
WHEN ${validateJsonArray(key)} THEN
|
|
185
191
|
NOT EXISTS (
|
|
186
192
|
SELECT value
|
|
187
193
|
FROM json_each(?)
|
|
188
194
|
WHERE value NOT IN (
|
|
189
195
|
SELECT value
|
|
190
|
-
FROM json_each(json_extract(metadata,
|
|
196
|
+
FROM json_each(json_extract(metadata, ${jsonPath}))
|
|
191
197
|
)
|
|
192
198
|
)
|
|
193
199
|
ELSE FALSE
|
|
@@ -206,7 +212,7 @@ var FILTER_OPERATORS = {
|
|
|
206
212
|
};
|
|
207
213
|
},
|
|
208
214
|
$elemMatch: (key, value) => {
|
|
209
|
-
const
|
|
215
|
+
const jsonPath = getJsonPath(key);
|
|
210
216
|
if (typeof value !== "object" || Array.isArray(value)) {
|
|
211
217
|
throw new Error("$elemMatch requires an object with conditions");
|
|
212
218
|
}
|
|
@@ -214,10 +220,10 @@ var FILTER_OPERATORS = {
|
|
|
214
220
|
return {
|
|
215
221
|
sql: `(
|
|
216
222
|
CASE
|
|
217
|
-
WHEN ${validateJsonArray(
|
|
223
|
+
WHEN ${validateJsonArray(key)} THEN
|
|
218
224
|
EXISTS (
|
|
219
225
|
SELECT 1
|
|
220
|
-
FROM json_each(json_extract(metadata,
|
|
226
|
+
FROM json_each(json_extract(metadata, ${jsonPath})) as elem
|
|
221
227
|
WHERE ${conditions.map((c) => c.sql).join(" AND ")}
|
|
222
228
|
)
|
|
223
229
|
ELSE FALSE
|
|
@@ -229,9 +235,9 @@ var FILTER_OPERATORS = {
|
|
|
229
235
|
},
|
|
230
236
|
// Element Operators
|
|
231
237
|
$exists: (key) => {
|
|
232
|
-
const
|
|
238
|
+
const jsonPath = getJsonPath(key);
|
|
233
239
|
return {
|
|
234
|
-
sql: `json_extract(metadata,
|
|
240
|
+
sql: `json_extract(metadata, ${jsonPath}) IS NOT NULL`,
|
|
235
241
|
needsValue: false
|
|
236
242
|
};
|
|
237
243
|
},
|
|
@@ -250,12 +256,12 @@ var FILTER_OPERATORS = {
|
|
|
250
256
|
needsValue: false
|
|
251
257
|
}),
|
|
252
258
|
$size: (key, paramIndex) => {
|
|
253
|
-
const
|
|
259
|
+
const jsonPath = getJsonPath(key);
|
|
254
260
|
return {
|
|
255
261
|
sql: `(
|
|
256
262
|
CASE
|
|
257
|
-
WHEN json_type(json_extract(metadata,
|
|
258
|
-
json_array_length(json_extract(metadata,
|
|
263
|
+
WHEN json_type(json_extract(metadata, ${jsonPath})) = 'array' THEN
|
|
264
|
+
json_array_length(json_extract(metadata, ${jsonPath})) = $${paramIndex}
|
|
259
265
|
ELSE FALSE
|
|
260
266
|
END
|
|
261
267
|
)`,
|
|
@@ -374,7 +380,14 @@ function isFilterResult(obj) {
|
|
|
374
380
|
}
|
|
375
381
|
var parseJsonPathKey = (key) => {
|
|
376
382
|
const parsedKey = utils.parseFieldKey(key);
|
|
377
|
-
|
|
383
|
+
if (parsedKey.includes(".")) {
|
|
384
|
+
return parsedKey.split(".").map((segment) => `"${segment}"`).join(".");
|
|
385
|
+
}
|
|
386
|
+
return parsedKey;
|
|
387
|
+
};
|
|
388
|
+
var getJsonPath = (key) => {
|
|
389
|
+
const jsonPathKey = parseJsonPathKey(key);
|
|
390
|
+
return `'$.${jsonPathKey}'`;
|
|
378
391
|
};
|
|
379
392
|
function escapeLikePattern(str) {
|
|
380
393
|
return str.replace(/([%_\\])/g, "\\$1");
|
|
@@ -399,15 +412,16 @@ function buildCondition(key, value, parentPath) {
|
|
|
399
412
|
return handleLogicalOperator(key, value);
|
|
400
413
|
}
|
|
401
414
|
if (!value || typeof value !== "object") {
|
|
415
|
+
const jsonPath = getJsonPath(key);
|
|
402
416
|
return {
|
|
403
|
-
sql: `json_extract(metadata,
|
|
417
|
+
sql: `json_extract(metadata, ${jsonPath}) = ?`,
|
|
404
418
|
values: [value]
|
|
405
419
|
};
|
|
406
420
|
}
|
|
407
421
|
return handleOperator(key, value);
|
|
408
422
|
}
|
|
409
423
|
function handleLogicalOperator(key, value, parentPath) {
|
|
410
|
-
if (!value || value.length === 0) {
|
|
424
|
+
if (!value || Array.isArray(value) && value.length === 0) {
|
|
411
425
|
switch (key) {
|
|
412
426
|
case "$and":
|
|
413
427
|
case "$nor":
|
|
@@ -431,7 +445,7 @@ function handleLogicalOperator(key, value, parentPath) {
|
|
|
431
445
|
const values = [];
|
|
432
446
|
const joinOperator = key === "$or" || key === "$nor" ? "OR" : "AND";
|
|
433
447
|
const conditions = Array.isArray(value) ? value.map((f) => {
|
|
434
|
-
const entries = Object.entries(f);
|
|
448
|
+
const entries = !!f ? Object.entries(f) : [];
|
|
435
449
|
return entries.map(([k, v]) => buildCondition(k, v));
|
|
436
450
|
}) : [buildCondition(key, value)];
|
|
437
451
|
const joined = conditions.flat().map((c) => {
|
|
@@ -484,11 +498,15 @@ var processOperator = (key, operator, operatorValue) => {
|
|
|
484
498
|
// src/vector/index.ts
|
|
485
499
|
var LibSQLVector = class extends vector.MastraVector {
|
|
486
500
|
turso;
|
|
501
|
+
maxRetries;
|
|
502
|
+
initialBackoffMs;
|
|
487
503
|
constructor({
|
|
488
504
|
connectionUrl,
|
|
489
505
|
authToken,
|
|
490
506
|
syncUrl,
|
|
491
|
-
syncInterval
|
|
507
|
+
syncInterval,
|
|
508
|
+
maxRetries = 5,
|
|
509
|
+
initialBackoffMs = 100
|
|
492
510
|
}) {
|
|
493
511
|
super();
|
|
494
512
|
this.turso = client.createClient({
|
|
@@ -497,27 +515,72 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
497
515
|
authToken,
|
|
498
516
|
syncInterval
|
|
499
517
|
});
|
|
518
|
+
this.maxRetries = maxRetries;
|
|
519
|
+
this.initialBackoffMs = initialBackoffMs;
|
|
500
520
|
if (connectionUrl.includes(`file:`) || connectionUrl.includes(`:memory:`)) {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
521
|
+
this.turso.execute("PRAGMA journal_mode=WAL;").then(() => this.logger.debug("LibSQLStore: PRAGMA journal_mode=WAL set.")).catch((err) => this.logger.warn("LibSQLStore: Failed to set PRAGMA journal_mode=WAL.", err));
|
|
522
|
+
this.turso.execute("PRAGMA busy_timeout = 5000;").then(() => this.logger.debug("LibSQLStore: PRAGMA busy_timeout=5000 set.")).catch((err) => this.logger.warn("LibSQLStore: Failed to set PRAGMA busy_timeout=5000.", err));
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
async executeWriteOperationWithRetry(operation, isTransaction = false) {
|
|
526
|
+
let attempts = 0;
|
|
527
|
+
let backoff = this.initialBackoffMs;
|
|
528
|
+
while (attempts < this.maxRetries) {
|
|
529
|
+
try {
|
|
530
|
+
return await operation();
|
|
531
|
+
} catch (error) {
|
|
532
|
+
if (error.code === "SQLITE_BUSY" || error.message && error.message.toLowerCase().includes("database is locked")) {
|
|
533
|
+
attempts++;
|
|
534
|
+
if (attempts >= this.maxRetries) {
|
|
535
|
+
this.logger.error(
|
|
536
|
+
`LibSQLVector: Operation failed after ${this.maxRetries} attempts due to: ${error.message}`,
|
|
537
|
+
error
|
|
538
|
+
);
|
|
539
|
+
throw error;
|
|
540
|
+
}
|
|
541
|
+
this.logger.warn(
|
|
542
|
+
`LibSQLVector: Attempt ${attempts} failed due to ${isTransaction ? "transaction " : ""}database lock. Retrying in ${backoff}ms...`
|
|
543
|
+
);
|
|
544
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
545
|
+
backoff *= 2;
|
|
546
|
+
} else {
|
|
547
|
+
throw error;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
505
550
|
}
|
|
551
|
+
throw new Error("LibSQLVector: Max retries reached, but no error was re-thrown from the loop.");
|
|
506
552
|
}
|
|
507
553
|
transformFilter(filter) {
|
|
508
554
|
const translator = new LibSQLFilterTranslator();
|
|
509
555
|
return translator.translate(filter);
|
|
510
556
|
}
|
|
511
|
-
async query(
|
|
512
|
-
|
|
557
|
+
async query({
|
|
558
|
+
indexName,
|
|
559
|
+
queryVector,
|
|
560
|
+
topK = 10,
|
|
561
|
+
filter,
|
|
562
|
+
includeVector = false,
|
|
563
|
+
minScore = -1
|
|
564
|
+
// Default to -1 to include all results (cosine similarity ranges from -1 to 1)
|
|
565
|
+
}) {
|
|
513
566
|
try {
|
|
514
|
-
const { indexName, queryVector, topK = 10, filter, includeVector = false, minScore = 0 } = params;
|
|
515
567
|
if (!Number.isInteger(topK) || topK <= 0) {
|
|
516
568
|
throw new Error("topK must be a positive integer");
|
|
517
569
|
}
|
|
518
570
|
if (!Array.isArray(queryVector) || !queryVector.every((x) => typeof x === "number" && Number.isFinite(x))) {
|
|
519
571
|
throw new Error("queryVector must be an array of finite numbers");
|
|
520
572
|
}
|
|
573
|
+
} catch (error$1) {
|
|
574
|
+
throw new error.MastraError(
|
|
575
|
+
{
|
|
576
|
+
id: "LIBSQL_VECTOR_QUERY_INVALID_ARGS",
|
|
577
|
+
domain: error.ErrorDomain.STORAGE,
|
|
578
|
+
category: error.ErrorCategory.USER
|
|
579
|
+
},
|
|
580
|
+
error$1
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
try {
|
|
521
584
|
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
522
585
|
const vectorStr = `[${queryVector.join(",")}]`;
|
|
523
586
|
const translatedFilter = this.transformFilter(filter);
|
|
@@ -525,20 +588,20 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
525
588
|
filterValues.push(minScore);
|
|
526
589
|
filterValues.push(topK);
|
|
527
590
|
const query = `
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
591
|
+
WITH vector_scores AS (
|
|
592
|
+
SELECT
|
|
593
|
+
vector_id as id,
|
|
594
|
+
(1-vector_distance_cos(embedding, '${vectorStr}')) as score,
|
|
595
|
+
metadata
|
|
596
|
+
${includeVector ? ", vector_extract(embedding) as embedding" : ""}
|
|
597
|
+
FROM ${parsedIndexName}
|
|
598
|
+
${filterQuery}
|
|
599
|
+
)
|
|
600
|
+
SELECT *
|
|
601
|
+
FROM vector_scores
|
|
602
|
+
WHERE score > ?
|
|
603
|
+
ORDER BY score DESC
|
|
604
|
+
LIMIT ?`;
|
|
542
605
|
const result = await this.turso.execute({
|
|
543
606
|
sql: query,
|
|
544
607
|
args: filterValues
|
|
@@ -549,27 +612,46 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
549
612
|
metadata: JSON.parse(metadata ?? "{}"),
|
|
550
613
|
...includeVector && embedding && { vector: JSON.parse(embedding) }
|
|
551
614
|
}));
|
|
552
|
-
}
|
|
615
|
+
} catch (error$1) {
|
|
616
|
+
throw new error.MastraError(
|
|
617
|
+
{
|
|
618
|
+
id: "LIBSQL_VECTOR_QUERY_FAILED",
|
|
619
|
+
domain: error.ErrorDomain.STORAGE,
|
|
620
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
621
|
+
},
|
|
622
|
+
error$1
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
upsert(args) {
|
|
627
|
+
try {
|
|
628
|
+
return this.executeWriteOperationWithRetry(() => this.doUpsert(args), true);
|
|
629
|
+
} catch (error$1) {
|
|
630
|
+
throw new error.MastraError(
|
|
631
|
+
{
|
|
632
|
+
id: "LIBSQL_VECTOR_UPSERT_FAILED",
|
|
633
|
+
domain: error.ErrorDomain.STORAGE,
|
|
634
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
635
|
+
},
|
|
636
|
+
error$1
|
|
637
|
+
);
|
|
553
638
|
}
|
|
554
639
|
}
|
|
555
|
-
async
|
|
556
|
-
const params = this.normalizeArgs("upsert", args);
|
|
557
|
-
const { indexName, vectors, metadata, ids } = params;
|
|
640
|
+
async doUpsert({ indexName, vectors, metadata, ids }) {
|
|
558
641
|
const tx = await this.turso.transaction("write");
|
|
559
642
|
try {
|
|
560
643
|
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
561
644
|
const vectorIds = ids || vectors.map(() => crypto.randomUUID());
|
|
562
645
|
for (let i = 0; i < vectors.length; i++) {
|
|
563
646
|
const query = `
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
647
|
+
INSERT INTO ${parsedIndexName} (vector_id, embedding, metadata)
|
|
648
|
+
VALUES (?, vector32(?), ?)
|
|
649
|
+
ON CONFLICT(vector_id) DO UPDATE SET
|
|
650
|
+
embedding = vector32(?),
|
|
651
|
+
metadata = ?
|
|
652
|
+
`;
|
|
570
653
|
await tx.execute({
|
|
571
654
|
sql: query,
|
|
572
|
-
// @ts-ignore
|
|
573
655
|
args: [
|
|
574
656
|
vectorIds[i],
|
|
575
657
|
JSON.stringify(vectors[i]),
|
|
@@ -582,7 +664,7 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
582
664
|
await tx.commit();
|
|
583
665
|
return vectorIds;
|
|
584
666
|
} catch (error) {
|
|
585
|
-
await tx.rollback();
|
|
667
|
+
!tx.closed && await tx.rollback();
|
|
586
668
|
if (error instanceof Error && error.message?.includes("dimensions are different")) {
|
|
587
669
|
const match = error.message.match(/dimensions are different: (\d+) != (\d+)/);
|
|
588
670
|
if (match) {
|
|
@@ -595,53 +677,67 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
595
677
|
throw error;
|
|
596
678
|
}
|
|
597
679
|
}
|
|
598
|
-
|
|
599
|
-
const params = this.normalizeArgs("createIndex", args);
|
|
600
|
-
const { indexName, dimension } = params;
|
|
680
|
+
createIndex(args) {
|
|
601
681
|
try {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
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 {
|
|
682
|
+
return this.executeWriteOperationWithRetry(() => this.doCreateIndex(args));
|
|
683
|
+
} catch (error$1) {
|
|
684
|
+
throw new error.MastraError(
|
|
685
|
+
{
|
|
686
|
+
id: "LIBSQL_VECTOR_CREATE_INDEX_FAILED",
|
|
687
|
+
domain: error.ErrorDomain.STORAGE,
|
|
688
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
689
|
+
details: { indexName: args.indexName, dimension: args.dimension }
|
|
690
|
+
},
|
|
691
|
+
error$1
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
async doCreateIndex({ indexName, dimension }) {
|
|
696
|
+
if (!Number.isInteger(dimension) || dimension <= 0) {
|
|
697
|
+
throw new Error("Dimension must be a positive integer");
|
|
628
698
|
}
|
|
699
|
+
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
700
|
+
await this.turso.execute({
|
|
701
|
+
sql: `
|
|
702
|
+
CREATE TABLE IF NOT EXISTS ${parsedIndexName} (
|
|
703
|
+
id SERIAL PRIMARY KEY,
|
|
704
|
+
vector_id TEXT UNIQUE NOT NULL,
|
|
705
|
+
embedding F32_BLOB(${dimension}),
|
|
706
|
+
metadata TEXT DEFAULT '{}'
|
|
707
|
+
);
|
|
708
|
+
`,
|
|
709
|
+
args: []
|
|
710
|
+
});
|
|
711
|
+
await this.turso.execute({
|
|
712
|
+
sql: `
|
|
713
|
+
CREATE INDEX IF NOT EXISTS ${parsedIndexName}_vector_idx
|
|
714
|
+
ON ${parsedIndexName} (libsql_vector_idx(embedding))
|
|
715
|
+
`,
|
|
716
|
+
args: []
|
|
717
|
+
});
|
|
629
718
|
}
|
|
630
|
-
|
|
631
|
-
const params = this.normalizeArgs("deleteIndex", args);
|
|
632
|
-
const { indexName } = params;
|
|
719
|
+
deleteIndex(args) {
|
|
633
720
|
try {
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
721
|
+
return this.executeWriteOperationWithRetry(() => this.doDeleteIndex(args));
|
|
722
|
+
} catch (error$1) {
|
|
723
|
+
throw new error.MastraError(
|
|
724
|
+
{
|
|
725
|
+
id: "LIBSQL_VECTOR_DELETE_INDEX_FAILED",
|
|
726
|
+
domain: error.ErrorDomain.STORAGE,
|
|
727
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
728
|
+
details: { indexName: args.indexName }
|
|
729
|
+
},
|
|
730
|
+
error$1
|
|
731
|
+
);
|
|
643
732
|
}
|
|
644
733
|
}
|
|
734
|
+
async doDeleteIndex({ indexName }) {
|
|
735
|
+
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
736
|
+
await this.turso.execute({
|
|
737
|
+
sql: `DROP TABLE IF EXISTS ${parsedIndexName}`,
|
|
738
|
+
args: []
|
|
739
|
+
});
|
|
740
|
+
}
|
|
645
741
|
async listIndexes() {
|
|
646
742
|
try {
|
|
647
743
|
const vectorTablesQuery = `
|
|
@@ -654,20 +750,24 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
654
750
|
args: []
|
|
655
751
|
});
|
|
656
752
|
return result.rows.map((row) => row.name);
|
|
657
|
-
} catch (error) {
|
|
658
|
-
throw new
|
|
753
|
+
} catch (error$1) {
|
|
754
|
+
throw new error.MastraError(
|
|
755
|
+
{
|
|
756
|
+
id: "LIBSQL_VECTOR_LIST_INDEXES_FAILED",
|
|
757
|
+
domain: error.ErrorDomain.STORAGE,
|
|
758
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
759
|
+
},
|
|
760
|
+
error$1
|
|
761
|
+
);
|
|
659
762
|
}
|
|
660
763
|
}
|
|
661
764
|
/**
|
|
662
765
|
* Retrieves statistics about a vector index.
|
|
663
766
|
*
|
|
664
|
-
* @param
|
|
665
|
-
* @param params.indexName - The name of the index to describe
|
|
767
|
+
* @param {string} indexName - The name of the index to describe
|
|
666
768
|
* @returns A promise that resolves to the index statistics including dimension, count and metric
|
|
667
769
|
*/
|
|
668
|
-
async describeIndex(
|
|
669
|
-
const params = this.normalizeArgs("describeIndex", args);
|
|
670
|
-
const { indexName } = params;
|
|
770
|
+
async describeIndex({ indexName }) {
|
|
671
771
|
try {
|
|
672
772
|
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
673
773
|
const tableInfoQuery = `
|
|
@@ -699,29 +799,17 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
699
799
|
metric
|
|
700
800
|
};
|
|
701
801
|
} catch (e) {
|
|
702
|
-
throw new
|
|
802
|
+
throw new error.MastraError(
|
|
803
|
+
{
|
|
804
|
+
id: "LIBSQL_VECTOR_DESCRIBE_INDEX_FAILED",
|
|
805
|
+
domain: error.ErrorDomain.STORAGE,
|
|
806
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
807
|
+
details: { indexName }
|
|
808
|
+
},
|
|
809
|
+
e
|
|
810
|
+
);
|
|
703
811
|
}
|
|
704
812
|
}
|
|
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
813
|
/**
|
|
726
814
|
* Updates a vector by its ID with the provided vector and/or metadata.
|
|
727
815
|
*
|
|
@@ -733,276 +821,225 @@ var LibSQLVector = class extends vector.MastraVector {
|
|
|
733
821
|
* @returns A promise that resolves when the update is complete.
|
|
734
822
|
* @throws Will throw an error if no updates are provided or if the update operation fails.
|
|
735
823
|
*/
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
824
|
+
updateVector(args) {
|
|
825
|
+
return this.executeWriteOperationWithRetry(() => this.doUpdateVector(args));
|
|
826
|
+
}
|
|
827
|
+
async doUpdateVector({ indexName, id, update }) {
|
|
828
|
+
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
829
|
+
const updates = [];
|
|
830
|
+
const args = [];
|
|
831
|
+
if (update.vector) {
|
|
832
|
+
updates.push("embedding = vector32(?)");
|
|
833
|
+
args.push(JSON.stringify(update.vector));
|
|
834
|
+
}
|
|
835
|
+
if (update.metadata) {
|
|
836
|
+
updates.push("metadata = ?");
|
|
837
|
+
args.push(JSON.stringify(update.metadata));
|
|
838
|
+
}
|
|
839
|
+
if (updates.length === 0) {
|
|
840
|
+
throw new error.MastraError({
|
|
841
|
+
id: "LIBSQL_VECTOR_UPDATE_VECTOR_INVALID_ARGS",
|
|
842
|
+
domain: error.ErrorDomain.STORAGE,
|
|
843
|
+
category: error.ErrorCategory.USER,
|
|
844
|
+
details: { indexName, id },
|
|
845
|
+
text: "No updates provided"
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
args.push(id);
|
|
849
|
+
const query = `
|
|
756
850
|
UPDATE ${parsedIndexName}
|
|
757
851
|
SET ${updates.join(", ")}
|
|
758
852
|
WHERE vector_id = ?;
|
|
759
853
|
`;
|
|
854
|
+
try {
|
|
760
855
|
await this.turso.execute({
|
|
761
856
|
sql: query,
|
|
762
|
-
args
|
|
857
|
+
args
|
|
763
858
|
});
|
|
764
|
-
} catch (error) {
|
|
765
|
-
throw new
|
|
859
|
+
} catch (error$1) {
|
|
860
|
+
throw new error.MastraError(
|
|
861
|
+
{
|
|
862
|
+
id: "LIBSQL_VECTOR_UPDATE_VECTOR_FAILED",
|
|
863
|
+
domain: error.ErrorDomain.STORAGE,
|
|
864
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
865
|
+
details: { indexName, id }
|
|
866
|
+
},
|
|
867
|
+
error$1
|
|
868
|
+
);
|
|
766
869
|
}
|
|
767
870
|
}
|
|
768
871
|
/**
|
|
769
|
-
* @deprecated Use {@link deleteVector} instead. This method will be removed on May 20th, 2025.
|
|
770
|
-
*
|
|
771
872
|
* Deletes a vector by its ID.
|
|
772
873
|
* @param indexName - The name of the index containing the vector.
|
|
773
874
|
* @param id - The ID of the vector to delete.
|
|
774
875
|
* @returns A promise that resolves when the deletion is complete.
|
|
775
876
|
* @throws Will throw an error if the deletion operation fails.
|
|
776
877
|
*/
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
878
|
+
deleteVector(args) {
|
|
879
|
+
try {
|
|
880
|
+
return this.executeWriteOperationWithRetry(() => this.doDeleteVector(args));
|
|
881
|
+
} catch (error$1) {
|
|
882
|
+
throw new error.MastraError(
|
|
883
|
+
{
|
|
884
|
+
id: "LIBSQL_VECTOR_DELETE_VECTOR_FAILED",
|
|
885
|
+
domain: error.ErrorDomain.STORAGE,
|
|
886
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
887
|
+
details: { indexName: args.indexName, id: args.id }
|
|
888
|
+
},
|
|
889
|
+
error$1
|
|
890
|
+
);
|
|
891
|
+
}
|
|
784
892
|
}
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
const params = this.normalizeArgs("deleteVector", args);
|
|
794
|
-
const { indexName, id } = params;
|
|
893
|
+
async doDeleteVector({ indexName, id }) {
|
|
894
|
+
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
895
|
+
await this.turso.execute({
|
|
896
|
+
sql: `DELETE FROM ${parsedIndexName} WHERE vector_id = ?`,
|
|
897
|
+
args: [id]
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
truncateIndex(args) {
|
|
795
901
|
try {
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
902
|
+
return this.executeWriteOperationWithRetry(() => this._doTruncateIndex(args));
|
|
903
|
+
} catch (error$1) {
|
|
904
|
+
throw new error.MastraError(
|
|
905
|
+
{
|
|
906
|
+
id: "LIBSQL_VECTOR_TRUNCATE_INDEX_FAILED",
|
|
907
|
+
domain: error.ErrorDomain.STORAGE,
|
|
908
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
909
|
+
details: { indexName: args.indexName }
|
|
910
|
+
},
|
|
911
|
+
error$1
|
|
912
|
+
);
|
|
803
913
|
}
|
|
804
914
|
}
|
|
805
|
-
async
|
|
806
|
-
const params = this.normalizeArgs("truncateIndex", args);
|
|
807
|
-
const { indexName } = params;
|
|
915
|
+
async _doTruncateIndex({ indexName }) {
|
|
808
916
|
await this.turso.execute({
|
|
809
917
|
sql: `DELETE FROM ${utils.parseSqlIdentifier(indexName, "index name")}`,
|
|
810
918
|
args: []
|
|
811
919
|
});
|
|
812
920
|
}
|
|
813
921
|
};
|
|
814
|
-
function
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
922
|
+
function transformEvalRow(row) {
|
|
923
|
+
const resultValue = JSON.parse(row.result);
|
|
924
|
+
const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
|
|
925
|
+
if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
|
|
926
|
+
throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
|
|
819
927
|
}
|
|
928
|
+
return {
|
|
929
|
+
input: row.input,
|
|
930
|
+
output: row.output,
|
|
931
|
+
result: resultValue,
|
|
932
|
+
agentName: row.agent_name,
|
|
933
|
+
metricName: row.metric_name,
|
|
934
|
+
instructions: row.instructions,
|
|
935
|
+
testInfo: testInfoValue,
|
|
936
|
+
globalRunId: row.global_run_id,
|
|
937
|
+
runId: row.run_id,
|
|
938
|
+
createdAt: row.created_at
|
|
939
|
+
};
|
|
820
940
|
}
|
|
821
|
-
var
|
|
941
|
+
var LegacyEvalsLibSQL = class extends storage.LegacyEvalsStorage {
|
|
822
942
|
client;
|
|
823
|
-
constructor(
|
|
824
|
-
super(
|
|
825
|
-
|
|
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
|
-
}
|
|
943
|
+
constructor({ client }) {
|
|
944
|
+
super();
|
|
945
|
+
this.client = client;
|
|
862
946
|
}
|
|
863
|
-
|
|
864
|
-
|
|
947
|
+
/** @deprecated use getEvals instead */
|
|
948
|
+
async getEvalsByAgentName(agentName, type) {
|
|
865
949
|
try {
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
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();
|
|
950
|
+
const baseQuery = `SELECT * FROM ${storage.TABLE_EVALS} WHERE agent_name = ?`;
|
|
951
|
+
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)" : "";
|
|
952
|
+
const result = await this.client.execute({
|
|
953
|
+
sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
|
|
954
|
+
args: [agentName]
|
|
955
|
+
});
|
|
956
|
+
return result.rows?.map((row) => transformEvalRow(row)) ?? [];
|
|
957
|
+
} catch (error$1) {
|
|
958
|
+
if (error$1 instanceof Error && error$1.message.includes("no such table")) {
|
|
959
|
+
return [];
|
|
882
960
|
}
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
async insert({ tableName, record }) {
|
|
892
|
-
try {
|
|
893
|
-
await this.client.execute(
|
|
894
|
-
this.prepareStatement({
|
|
895
|
-
tableName,
|
|
896
|
-
record
|
|
897
|
-
})
|
|
961
|
+
throw new error.MastraError(
|
|
962
|
+
{
|
|
963
|
+
id: "LIBSQL_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
|
|
964
|
+
domain: error.ErrorDomain.STORAGE,
|
|
965
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
966
|
+
details: { agentName }
|
|
967
|
+
},
|
|
968
|
+
error$1
|
|
898
969
|
);
|
|
899
|
-
} catch (error) {
|
|
900
|
-
this.logger.error(`Error upserting into table ${tableName}: ${error}`);
|
|
901
|
-
throw error;
|
|
902
970
|
}
|
|
903
971
|
}
|
|
904
|
-
async
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
972
|
+
async getEvals(options = {}) {
|
|
973
|
+
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
974
|
+
const fromDate = dateRange?.start;
|
|
975
|
+
const toDate = dateRange?.end;
|
|
976
|
+
const conditions = [];
|
|
977
|
+
const queryParams = [];
|
|
978
|
+
if (agentName) {
|
|
979
|
+
conditions.push(`agent_name = ?`);
|
|
980
|
+
queryParams.push(agentName);
|
|
912
981
|
}
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
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;
|
|
982
|
+
if (type === "test") {
|
|
983
|
+
conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
|
|
984
|
+
} else if (type === "live") {
|
|
985
|
+
conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
|
|
925
986
|
}
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
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;
|
|
987
|
+
if (fromDate) {
|
|
988
|
+
conditions.push(`created_at >= ?`);
|
|
989
|
+
queryParams.push(fromDate.toISOString());
|
|
945
990
|
}
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
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 [];
|
|
991
|
+
if (toDate) {
|
|
992
|
+
conditions.push(`created_at <= ?`);
|
|
993
|
+
queryParams.push(toDate.toISOString());
|
|
958
994
|
}
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
995
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
996
|
+
try {
|
|
997
|
+
const countResult = await this.client.execute({
|
|
998
|
+
sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_EVALS} ${whereClause}`,
|
|
999
|
+
args: queryParams
|
|
1000
|
+
});
|
|
1001
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
1002
|
+
const currentOffset = page * perPage;
|
|
1003
|
+
const hasMore = currentOffset + perPage < total;
|
|
1004
|
+
if (total === 0) {
|
|
1005
|
+
return {
|
|
1006
|
+
evals: [],
|
|
1007
|
+
total: 0,
|
|
1008
|
+
page,
|
|
1009
|
+
perPage,
|
|
1010
|
+
hasMore: false
|
|
1011
|
+
};
|
|
974
1012
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
1013
|
+
const dataResult = await this.client.execute({
|
|
1014
|
+
sql: `SELECT * FROM ${storage.TABLE_EVALS} ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
|
|
1015
|
+
args: [...queryParams, perPage, currentOffset]
|
|
1016
|
+
});
|
|
1017
|
+
return {
|
|
1018
|
+
evals: dataResult.rows?.map((row) => transformEvalRow(row)) ?? [],
|
|
1019
|
+
total,
|
|
1020
|
+
page,
|
|
1021
|
+
perPage,
|
|
1022
|
+
hasMore
|
|
1023
|
+
};
|
|
1024
|
+
} catch (error$1) {
|
|
1025
|
+
throw new error.MastraError(
|
|
1026
|
+
{
|
|
1027
|
+
id: "LIBSQL_STORE_GET_EVALS_FAILED",
|
|
1028
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1029
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1030
|
+
},
|
|
1031
|
+
error$1
|
|
1032
|
+
);
|
|
986
1033
|
}
|
|
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
1034
|
}
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1035
|
+
};
|
|
1036
|
+
var MemoryLibSQL = class extends storage.MemoryStorage {
|
|
1037
|
+
client;
|
|
1038
|
+
operations;
|
|
1039
|
+
constructor({ client, operations }) {
|
|
1040
|
+
super();
|
|
1041
|
+
this.client = client;
|
|
1042
|
+
this.operations = operations;
|
|
1006
1043
|
}
|
|
1007
1044
|
parseRow(row) {
|
|
1008
1045
|
let content = row.content;
|
|
@@ -1010,52 +1047,79 @@ var LibSQLStore = class extends storage.MastraStorage {
|
|
|
1010
1047
|
content = JSON.parse(row.content);
|
|
1011
1048
|
} catch {
|
|
1012
1049
|
}
|
|
1013
|
-
|
|
1050
|
+
const result = {
|
|
1014
1051
|
id: row.id,
|
|
1015
1052
|
content,
|
|
1016
1053
|
role: row.role,
|
|
1017
|
-
type: row.type,
|
|
1018
1054
|
createdAt: new Date(row.createdAt),
|
|
1019
|
-
threadId: row.thread_id
|
|
1055
|
+
threadId: row.thread_id,
|
|
1056
|
+
resourceId: row.resourceId
|
|
1020
1057
|
};
|
|
1058
|
+
if (row.type && row.type !== `v2`) result.type = row.type;
|
|
1059
|
+
return result;
|
|
1021
1060
|
}
|
|
1022
|
-
async
|
|
1061
|
+
async _getIncludedMessages({
|
|
1062
|
+
threadId,
|
|
1063
|
+
selectBy
|
|
1064
|
+
}) {
|
|
1065
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1066
|
+
const include = selectBy?.include;
|
|
1067
|
+
if (!include) return null;
|
|
1068
|
+
const unionQueries = [];
|
|
1069
|
+
const params = [];
|
|
1070
|
+
for (const inc of include) {
|
|
1071
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
1072
|
+
const searchId = inc.threadId || threadId;
|
|
1073
|
+
unionQueries.push(
|
|
1074
|
+
`
|
|
1075
|
+
SELECT * FROM (
|
|
1076
|
+
WITH numbered_messages AS (
|
|
1077
|
+
SELECT
|
|
1078
|
+
id, content, role, type, "createdAt", thread_id, "resourceId",
|
|
1079
|
+
ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
|
|
1080
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
1081
|
+
WHERE thread_id = ?
|
|
1082
|
+
),
|
|
1083
|
+
target_positions AS (
|
|
1084
|
+
SELECT row_num as target_pos
|
|
1085
|
+
FROM numbered_messages
|
|
1086
|
+
WHERE id = ?
|
|
1087
|
+
)
|
|
1088
|
+
SELECT DISTINCT m.*
|
|
1089
|
+
FROM numbered_messages m
|
|
1090
|
+
CROSS JOIN target_positions t
|
|
1091
|
+
WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
|
|
1092
|
+
)
|
|
1093
|
+
`
|
|
1094
|
+
// Keep ASC for final sorting after fetching context
|
|
1095
|
+
);
|
|
1096
|
+
params.push(searchId, id, withPreviousMessages, withNextMessages);
|
|
1097
|
+
}
|
|
1098
|
+
const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" ASC';
|
|
1099
|
+
const includedResult = await this.client.execute({ sql: finalQuery, args: params });
|
|
1100
|
+
const includedRows = includedResult.rows?.map((row) => this.parseRow(row));
|
|
1101
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1102
|
+
const dedupedRows = includedRows.filter((row) => {
|
|
1103
|
+
if (seen.has(row.id)) return false;
|
|
1104
|
+
seen.add(row.id);
|
|
1105
|
+
return true;
|
|
1106
|
+
});
|
|
1107
|
+
return dedupedRows;
|
|
1108
|
+
}
|
|
1109
|
+
async getMessages({
|
|
1110
|
+
threadId,
|
|
1111
|
+
resourceId,
|
|
1112
|
+
selectBy,
|
|
1113
|
+
format
|
|
1114
|
+
}) {
|
|
1023
1115
|
try {
|
|
1116
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1024
1117
|
const messages = [];
|
|
1025
|
-
const limit =
|
|
1118
|
+
const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
1026
1119
|
if (selectBy?.include?.length) {
|
|
1027
|
-
const
|
|
1028
|
-
|
|
1029
|
-
|
|
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)));
|
|
1120
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
|
|
1121
|
+
if (includeMessages) {
|
|
1122
|
+
messages.push(...includeMessages);
|
|
1059
1123
|
}
|
|
1060
1124
|
}
|
|
1061
1125
|
const excludeIds = messages.map((m) => m.id);
|
|
@@ -1066,7 +1130,8 @@ var LibSQLStore = class extends storage.MastraStorage {
|
|
|
1066
1130
|
role,
|
|
1067
1131
|
type,
|
|
1068
1132
|
"createdAt",
|
|
1069
|
-
thread_id
|
|
1133
|
+
thread_id,
|
|
1134
|
+
"resourceId"
|
|
1070
1135
|
FROM "${storage.TABLE_MESSAGES}"
|
|
1071
1136
|
WHERE thread_id = ?
|
|
1072
1137
|
${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
|
|
@@ -1074,21 +1139,149 @@ var LibSQLStore = class extends storage.MastraStorage {
|
|
|
1074
1139
|
LIMIT ?
|
|
1075
1140
|
`;
|
|
1076
1141
|
const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
|
|
1077
|
-
const remainingResult = await this.client.execute({
|
|
1078
|
-
sql: remainingSql,
|
|
1079
|
-
args: remainingArgs
|
|
1080
|
-
});
|
|
1142
|
+
const remainingResult = await this.client.execute({ sql: remainingSql, args: remainingArgs });
|
|
1081
1143
|
if (remainingResult.rows) {
|
|
1082
1144
|
messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
|
|
1083
1145
|
}
|
|
1084
1146
|
messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1147
|
+
const list = new agent.MessageList().add(messages, "memory");
|
|
1148
|
+
if (format === `v2`) return list.get.all.v2();
|
|
1149
|
+
return list.get.all.v1();
|
|
1150
|
+
} catch (error$1) {
|
|
1151
|
+
throw new error.MastraError(
|
|
1152
|
+
{
|
|
1153
|
+
id: "LIBSQL_STORE_GET_MESSAGES_FAILED",
|
|
1154
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1155
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1156
|
+
details: { threadId, resourceId: resourceId ?? "" }
|
|
1157
|
+
},
|
|
1158
|
+
error$1
|
|
1159
|
+
);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
async getMessagesById({
|
|
1163
|
+
messageIds,
|
|
1164
|
+
format
|
|
1165
|
+
}) {
|
|
1166
|
+
if (messageIds.length === 0) return [];
|
|
1167
|
+
try {
|
|
1168
|
+
const sql = `
|
|
1169
|
+
SELECT
|
|
1170
|
+
id,
|
|
1171
|
+
content,
|
|
1172
|
+
role,
|
|
1173
|
+
type,
|
|
1174
|
+
"createdAt",
|
|
1175
|
+
thread_id,
|
|
1176
|
+
"resourceId"
|
|
1177
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
1178
|
+
WHERE id IN (${messageIds.map(() => "?").join(", ")})
|
|
1179
|
+
ORDER BY "createdAt" DESC
|
|
1180
|
+
`;
|
|
1181
|
+
const result = await this.client.execute({ sql, args: messageIds });
|
|
1182
|
+
if (!result.rows) return [];
|
|
1183
|
+
const list = new agent.MessageList().add(result.rows.map(this.parseRow), "memory");
|
|
1184
|
+
if (format === `v1`) return list.get.all.v1();
|
|
1185
|
+
return list.get.all.v2();
|
|
1186
|
+
} catch (error$1) {
|
|
1187
|
+
throw new error.MastraError(
|
|
1188
|
+
{
|
|
1189
|
+
id: "LIBSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
|
|
1190
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1191
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1192
|
+
details: { messageIds: JSON.stringify(messageIds) }
|
|
1193
|
+
},
|
|
1194
|
+
error$1
|
|
1195
|
+
);
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
async getMessagesPaginated(args) {
|
|
1199
|
+
const { threadId, format, selectBy } = args;
|
|
1200
|
+
const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
|
|
1201
|
+
const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
1202
|
+
const fromDate = dateRange?.start;
|
|
1203
|
+
const toDate = dateRange?.end;
|
|
1204
|
+
const messages = [];
|
|
1205
|
+
if (selectBy?.include?.length) {
|
|
1206
|
+
try {
|
|
1207
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
|
|
1208
|
+
if (includeMessages) {
|
|
1209
|
+
messages.push(...includeMessages);
|
|
1210
|
+
}
|
|
1211
|
+
} catch (error$1) {
|
|
1212
|
+
throw new error.MastraError(
|
|
1213
|
+
{
|
|
1214
|
+
id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_GET_INCLUDE_MESSAGES_FAILED",
|
|
1215
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1216
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1217
|
+
details: { threadId }
|
|
1218
|
+
},
|
|
1219
|
+
error$1
|
|
1220
|
+
);
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
try {
|
|
1224
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1225
|
+
const currentOffset = page * perPage;
|
|
1226
|
+
const conditions = [`thread_id = ?`];
|
|
1227
|
+
const queryParams = [threadId];
|
|
1228
|
+
if (fromDate) {
|
|
1229
|
+
conditions.push(`"createdAt" >= ?`);
|
|
1230
|
+
queryParams.push(fromDate.toISOString());
|
|
1231
|
+
}
|
|
1232
|
+
if (toDate) {
|
|
1233
|
+
conditions.push(`"createdAt" <= ?`);
|
|
1234
|
+
queryParams.push(toDate.toISOString());
|
|
1235
|
+
}
|
|
1236
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1237
|
+
const countResult = await this.client.execute({
|
|
1238
|
+
sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_MESSAGES} ${whereClause}`,
|
|
1239
|
+
args: queryParams
|
|
1240
|
+
});
|
|
1241
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
1242
|
+
if (total === 0 && messages.length === 0) {
|
|
1243
|
+
return {
|
|
1244
|
+
messages: [],
|
|
1245
|
+
total: 0,
|
|
1246
|
+
page,
|
|
1247
|
+
perPage,
|
|
1248
|
+
hasMore: false
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
const excludeIds = messages.map((m) => m.id);
|
|
1252
|
+
const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + queryParams.length + 1}`).join(", ");
|
|
1253
|
+
const dataResult = await this.client.execute({
|
|
1254
|
+
sql: `SELECT id, content, role, type, "createdAt", "resourceId", "thread_id" FROM ${storage.TABLE_MESSAGES} ${whereClause} ${excludeIds.length ? `AND id NOT IN (${excludeIdsParam})` : ""} ORDER BY "createdAt" DESC LIMIT ? OFFSET ?`,
|
|
1255
|
+
args: [...queryParams, ...excludeIds, perPage, currentOffset]
|
|
1256
|
+
});
|
|
1257
|
+
messages.push(...(dataResult.rows || []).map((row) => this.parseRow(row)));
|
|
1258
|
+
const messagesToReturn = format === "v1" ? new agent.MessageList().add(messages, "memory").get.all.v1() : new agent.MessageList().add(messages, "memory").get.all.v2();
|
|
1259
|
+
return {
|
|
1260
|
+
messages: messagesToReturn,
|
|
1261
|
+
total,
|
|
1262
|
+
page,
|
|
1263
|
+
perPage,
|
|
1264
|
+
hasMore: currentOffset + messages.length < total
|
|
1265
|
+
};
|
|
1266
|
+
} catch (error$1) {
|
|
1267
|
+
const mastraError = new error.MastraError(
|
|
1268
|
+
{
|
|
1269
|
+
id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
|
|
1270
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1271
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1272
|
+
details: { threadId }
|
|
1273
|
+
},
|
|
1274
|
+
error$1
|
|
1275
|
+
);
|
|
1276
|
+
this.logger?.trackException?.(mastraError);
|
|
1277
|
+
this.logger?.error?.(mastraError.toString());
|
|
1278
|
+
return { messages: [], total: 0, page, perPage, hasMore: false };
|
|
1089
1279
|
}
|
|
1090
1280
|
}
|
|
1091
|
-
async saveMessages({
|
|
1281
|
+
async saveMessages({
|
|
1282
|
+
messages,
|
|
1283
|
+
format
|
|
1284
|
+
}) {
|
|
1092
1285
|
if (messages.length === 0) return messages;
|
|
1093
1286
|
try {
|
|
1094
1287
|
const threadId = messages[0]?.threadId;
|
|
@@ -1097,149 +1290,1848 @@ var LibSQLStore = class extends storage.MastraStorage {
|
|
|
1097
1290
|
}
|
|
1098
1291
|
const batchStatements = messages.map((message) => {
|
|
1099
1292
|
const time = message.createdAt || /* @__PURE__ */ new Date();
|
|
1293
|
+
if (!message.threadId) {
|
|
1294
|
+
throw new Error(
|
|
1295
|
+
`Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`
|
|
1296
|
+
);
|
|
1297
|
+
}
|
|
1298
|
+
if (!message.resourceId) {
|
|
1299
|
+
throw new Error(
|
|
1300
|
+
`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`
|
|
1301
|
+
);
|
|
1302
|
+
}
|
|
1100
1303
|
return {
|
|
1101
|
-
sql: `INSERT INTO ${storage.TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
|
|
1102
|
-
|
|
1304
|
+
sql: `INSERT INTO "${storage.TABLE_MESSAGES}" (id, thread_id, content, role, type, "createdAt", "resourceId")
|
|
1305
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1306
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1307
|
+
thread_id=excluded.thread_id,
|
|
1308
|
+
content=excluded.content,
|
|
1309
|
+
role=excluded.role,
|
|
1310
|
+
type=excluded.type,
|
|
1311
|
+
"resourceId"=excluded."resourceId"
|
|
1312
|
+
`,
|
|
1103
1313
|
args: [
|
|
1104
1314
|
message.id,
|
|
1105
|
-
threadId,
|
|
1315
|
+
message.threadId,
|
|
1106
1316
|
typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
|
|
1107
1317
|
message.role,
|
|
1108
|
-
message.type,
|
|
1109
|
-
time instanceof Date ? time.toISOString() : time
|
|
1318
|
+
message.type || "v2",
|
|
1319
|
+
time instanceof Date ? time.toISOString() : time,
|
|
1320
|
+
message.resourceId
|
|
1110
1321
|
]
|
|
1111
1322
|
};
|
|
1112
1323
|
});
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1324
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1325
|
+
batchStatements.push({
|
|
1326
|
+
sql: `UPDATE "${storage.TABLE_THREADS}" SET "updatedAt" = ? WHERE id = ?`,
|
|
1327
|
+
args: [now, threadId]
|
|
1328
|
+
});
|
|
1329
|
+
const BATCH_SIZE = 50;
|
|
1330
|
+
const messageStatements = batchStatements.slice(0, -1);
|
|
1331
|
+
const threadUpdateStatement = batchStatements[batchStatements.length - 1];
|
|
1332
|
+
for (let i = 0; i < messageStatements.length; i += BATCH_SIZE) {
|
|
1333
|
+
const batch = messageStatements.slice(i, i + BATCH_SIZE);
|
|
1334
|
+
if (batch.length > 0) {
|
|
1335
|
+
await this.client.batch(batch, "write");
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
if (threadUpdateStatement) {
|
|
1339
|
+
await this.client.execute(threadUpdateStatement);
|
|
1340
|
+
}
|
|
1341
|
+
const list = new agent.MessageList().add(messages, "memory");
|
|
1342
|
+
if (format === `v2`) return list.get.all.v2();
|
|
1343
|
+
return list.get.all.v1();
|
|
1344
|
+
} catch (error$1) {
|
|
1345
|
+
throw new error.MastraError(
|
|
1346
|
+
{
|
|
1347
|
+
id: "LIBSQL_STORE_SAVE_MESSAGES_FAILED",
|
|
1348
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1349
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1350
|
+
},
|
|
1351
|
+
error$1
|
|
1352
|
+
);
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
async updateMessages({
|
|
1356
|
+
messages
|
|
1357
|
+
}) {
|
|
1358
|
+
if (messages.length === 0) {
|
|
1359
|
+
return [];
|
|
1360
|
+
}
|
|
1361
|
+
const messageIds = messages.map((m) => m.id);
|
|
1362
|
+
const placeholders = messageIds.map(() => "?").join(",");
|
|
1363
|
+
const selectSql = `SELECT * FROM ${storage.TABLE_MESSAGES} WHERE id IN (${placeholders})`;
|
|
1364
|
+
const existingResult = await this.client.execute({ sql: selectSql, args: messageIds });
|
|
1365
|
+
const existingMessages = existingResult.rows.map((row) => this.parseRow(row));
|
|
1366
|
+
if (existingMessages.length === 0) {
|
|
1367
|
+
return [];
|
|
1368
|
+
}
|
|
1369
|
+
const batchStatements = [];
|
|
1370
|
+
const threadIdsToUpdate = /* @__PURE__ */ new Set();
|
|
1371
|
+
const columnMapping = {
|
|
1372
|
+
threadId: "thread_id"
|
|
1373
|
+
};
|
|
1374
|
+
for (const existingMessage of existingMessages) {
|
|
1375
|
+
const updatePayload = messages.find((m) => m.id === existingMessage.id);
|
|
1376
|
+
if (!updatePayload) continue;
|
|
1377
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1378
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1379
|
+
threadIdsToUpdate.add(existingMessage.threadId);
|
|
1380
|
+
if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
1381
|
+
threadIdsToUpdate.add(updatePayload.threadId);
|
|
1382
|
+
}
|
|
1383
|
+
const setClauses = [];
|
|
1384
|
+
const args = [];
|
|
1385
|
+
const updatableFields = { ...fieldsToUpdate };
|
|
1386
|
+
if (updatableFields.content) {
|
|
1387
|
+
const newContent = {
|
|
1388
|
+
...existingMessage.content,
|
|
1389
|
+
...updatableFields.content,
|
|
1390
|
+
// Deep merge metadata if it exists on both
|
|
1391
|
+
...existingMessage.content?.metadata && updatableFields.content.metadata ? {
|
|
1392
|
+
metadata: {
|
|
1393
|
+
...existingMessage.content.metadata,
|
|
1394
|
+
...updatableFields.content.metadata
|
|
1395
|
+
}
|
|
1396
|
+
} : {}
|
|
1397
|
+
};
|
|
1398
|
+
setClauses.push(`${utils.parseSqlIdentifier("content", "column name")} = ?`);
|
|
1399
|
+
args.push(JSON.stringify(newContent));
|
|
1400
|
+
delete updatableFields.content;
|
|
1401
|
+
}
|
|
1402
|
+
for (const key in updatableFields) {
|
|
1403
|
+
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
1404
|
+
const dbKey = columnMapping[key] || key;
|
|
1405
|
+
setClauses.push(`${utils.parseSqlIdentifier(dbKey, "column name")} = ?`);
|
|
1406
|
+
let value = updatableFields[key];
|
|
1407
|
+
if (typeof value === "object" && value !== null) {
|
|
1408
|
+
value = JSON.stringify(value);
|
|
1409
|
+
}
|
|
1410
|
+
args.push(value);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
if (setClauses.length === 0) continue;
|
|
1414
|
+
args.push(id);
|
|
1415
|
+
const sql = `UPDATE ${storage.TABLE_MESSAGES} SET ${setClauses.join(", ")} WHERE id = ?`;
|
|
1416
|
+
batchStatements.push({ sql, args });
|
|
1417
|
+
}
|
|
1418
|
+
if (batchStatements.length === 0) {
|
|
1419
|
+
return existingMessages;
|
|
1420
|
+
}
|
|
1421
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1422
|
+
for (const threadId of threadIdsToUpdate) {
|
|
1423
|
+
if (threadId) {
|
|
1424
|
+
batchStatements.push({
|
|
1425
|
+
sql: `UPDATE ${storage.TABLE_THREADS} SET updatedAt = ? WHERE id = ?`,
|
|
1426
|
+
args: [now, threadId]
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1118
1429
|
}
|
|
1430
|
+
await this.client.batch(batchStatements, "write");
|
|
1431
|
+
const updatedResult = await this.client.execute({ sql: selectSql, args: messageIds });
|
|
1432
|
+
return updatedResult.rows.map((row) => this.parseRow(row));
|
|
1119
1433
|
}
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1434
|
+
async deleteMessages(messageIds) {
|
|
1435
|
+
if (!messageIds || messageIds.length === 0) {
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
try {
|
|
1439
|
+
const BATCH_SIZE = 100;
|
|
1440
|
+
const threadIds = /* @__PURE__ */ new Set();
|
|
1441
|
+
const tx = await this.client.transaction("write");
|
|
1442
|
+
try {
|
|
1443
|
+
for (let i = 0; i < messageIds.length; i += BATCH_SIZE) {
|
|
1444
|
+
const batch = messageIds.slice(i, i + BATCH_SIZE);
|
|
1445
|
+
const placeholders = batch.map(() => "?").join(",");
|
|
1446
|
+
const result = await tx.execute({
|
|
1447
|
+
sql: `SELECT DISTINCT thread_id FROM "${storage.TABLE_MESSAGES}" WHERE id IN (${placeholders})`,
|
|
1448
|
+
args: batch
|
|
1449
|
+
});
|
|
1450
|
+
result.rows?.forEach((row) => {
|
|
1451
|
+
if (row.thread_id) threadIds.add(row.thread_id);
|
|
1452
|
+
});
|
|
1453
|
+
await tx.execute({
|
|
1454
|
+
sql: `DELETE FROM "${storage.TABLE_MESSAGES}" WHERE id IN (${placeholders})`,
|
|
1455
|
+
args: batch
|
|
1456
|
+
});
|
|
1457
|
+
}
|
|
1458
|
+
if (threadIds.size > 0) {
|
|
1459
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1460
|
+
for (const threadId of threadIds) {
|
|
1461
|
+
await tx.execute({
|
|
1462
|
+
sql: `UPDATE "${storage.TABLE_THREADS}" SET "updatedAt" = ? WHERE id = ?`,
|
|
1463
|
+
args: [now, threadId]
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
await tx.commit();
|
|
1468
|
+
} catch (error) {
|
|
1469
|
+
await tx.rollback();
|
|
1470
|
+
throw error;
|
|
1471
|
+
}
|
|
1472
|
+
} catch (error$1) {
|
|
1473
|
+
throw new error.MastraError(
|
|
1474
|
+
{
|
|
1475
|
+
id: "LIBSQL_STORE_DELETE_MESSAGES_FAILED",
|
|
1476
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1477
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1478
|
+
details: { messageIds: messageIds.join(", ") }
|
|
1479
|
+
},
|
|
1480
|
+
error$1
|
|
1481
|
+
);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
async getResourceById({ resourceId }) {
|
|
1485
|
+
const result = await this.operations.load({
|
|
1486
|
+
tableName: storage.TABLE_RESOURCES,
|
|
1487
|
+
keys: { id: resourceId }
|
|
1488
|
+
});
|
|
1489
|
+
if (!result) {
|
|
1490
|
+
return null;
|
|
1125
1491
|
}
|
|
1126
1492
|
return {
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
result:
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
testInfo: testInfoValue,
|
|
1134
|
-
globalRunId: row.global_run_id,
|
|
1135
|
-
runId: row.run_id,
|
|
1136
|
-
createdAt: row.created_at
|
|
1493
|
+
...result,
|
|
1494
|
+
// Ensure workingMemory is always returned as a string, even if auto-parsed as JSON
|
|
1495
|
+
workingMemory: result.workingMemory && typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
|
|
1496
|
+
metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata,
|
|
1497
|
+
createdAt: new Date(result.createdAt),
|
|
1498
|
+
updatedAt: new Date(result.updatedAt)
|
|
1137
1499
|
};
|
|
1138
1500
|
}
|
|
1139
|
-
async
|
|
1501
|
+
async saveResource({ resource }) {
|
|
1502
|
+
await this.operations.insert({
|
|
1503
|
+
tableName: storage.TABLE_RESOURCES,
|
|
1504
|
+
record: {
|
|
1505
|
+
...resource,
|
|
1506
|
+
metadata: JSON.stringify(resource.metadata)
|
|
1507
|
+
}
|
|
1508
|
+
});
|
|
1509
|
+
return resource;
|
|
1510
|
+
}
|
|
1511
|
+
async updateResource({
|
|
1512
|
+
resourceId,
|
|
1513
|
+
workingMemory,
|
|
1514
|
+
metadata
|
|
1515
|
+
}) {
|
|
1516
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
1517
|
+
if (!existingResource) {
|
|
1518
|
+
const newResource = {
|
|
1519
|
+
id: resourceId,
|
|
1520
|
+
workingMemory,
|
|
1521
|
+
metadata: metadata || {},
|
|
1522
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1523
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1524
|
+
};
|
|
1525
|
+
return this.saveResource({ resource: newResource });
|
|
1526
|
+
}
|
|
1527
|
+
const updatedResource = {
|
|
1528
|
+
...existingResource,
|
|
1529
|
+
workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
|
|
1530
|
+
metadata: {
|
|
1531
|
+
...existingResource.metadata,
|
|
1532
|
+
...metadata
|
|
1533
|
+
},
|
|
1534
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1535
|
+
};
|
|
1536
|
+
const updates = [];
|
|
1537
|
+
const values = [];
|
|
1538
|
+
if (workingMemory !== void 0) {
|
|
1539
|
+
updates.push("workingMemory = ?");
|
|
1540
|
+
values.push(workingMemory);
|
|
1541
|
+
}
|
|
1542
|
+
if (metadata) {
|
|
1543
|
+
updates.push("metadata = ?");
|
|
1544
|
+
values.push(JSON.stringify(updatedResource.metadata));
|
|
1545
|
+
}
|
|
1546
|
+
updates.push("updatedAt = ?");
|
|
1547
|
+
values.push(updatedResource.updatedAt.toISOString());
|
|
1548
|
+
values.push(resourceId);
|
|
1549
|
+
await this.client.execute({
|
|
1550
|
+
sql: `UPDATE ${storage.TABLE_RESOURCES} SET ${updates.join(", ")} WHERE id = ?`,
|
|
1551
|
+
args: values
|
|
1552
|
+
});
|
|
1553
|
+
return updatedResource;
|
|
1554
|
+
}
|
|
1555
|
+
async getThreadById({ threadId }) {
|
|
1140
1556
|
try {
|
|
1141
|
-
const
|
|
1142
|
-
|
|
1557
|
+
const result = await this.operations.load({
|
|
1558
|
+
tableName: storage.TABLE_THREADS,
|
|
1559
|
+
keys: { id: threadId }
|
|
1560
|
+
});
|
|
1561
|
+
if (!result) {
|
|
1562
|
+
return null;
|
|
1563
|
+
}
|
|
1564
|
+
return {
|
|
1565
|
+
...result,
|
|
1566
|
+
metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata,
|
|
1567
|
+
createdAt: new Date(result.createdAt),
|
|
1568
|
+
updatedAt: new Date(result.updatedAt)
|
|
1569
|
+
};
|
|
1570
|
+
} catch (error$1) {
|
|
1571
|
+
throw new error.MastraError(
|
|
1572
|
+
{
|
|
1573
|
+
id: "LIBSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
1574
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1575
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1576
|
+
details: { threadId }
|
|
1577
|
+
},
|
|
1578
|
+
error$1
|
|
1579
|
+
);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
|
|
1584
|
+
*/
|
|
1585
|
+
async getThreadsByResourceId(args) {
|
|
1586
|
+
const resourceId = args.resourceId;
|
|
1587
|
+
const orderBy = this.castThreadOrderBy(args.orderBy);
|
|
1588
|
+
const sortDirection = this.castThreadSortDirection(args.sortDirection);
|
|
1589
|
+
try {
|
|
1590
|
+
const baseQuery = `FROM ${storage.TABLE_THREADS} WHERE resourceId = ?`;
|
|
1591
|
+
const queryParams = [resourceId];
|
|
1592
|
+
const mapRowToStorageThreadType = (row) => ({
|
|
1593
|
+
id: row.id,
|
|
1594
|
+
resourceId: row.resourceId,
|
|
1595
|
+
title: row.title,
|
|
1596
|
+
createdAt: new Date(row.createdAt),
|
|
1597
|
+
// Convert string to Date
|
|
1598
|
+
updatedAt: new Date(row.updatedAt),
|
|
1599
|
+
// Convert string to Date
|
|
1600
|
+
metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
|
|
1601
|
+
});
|
|
1143
1602
|
const result = await this.client.execute({
|
|
1144
|
-
sql:
|
|
1145
|
-
args:
|
|
1603
|
+
sql: `SELECT * ${baseQuery} ORDER BY ${orderBy} ${sortDirection}`,
|
|
1604
|
+
args: queryParams
|
|
1146
1605
|
});
|
|
1147
|
-
|
|
1148
|
-
} catch (error) {
|
|
1149
|
-
if (error instanceof Error && error.message.includes("no such table")) {
|
|
1606
|
+
if (!result.rows) {
|
|
1150
1607
|
return [];
|
|
1151
1608
|
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1609
|
+
return result.rows.map(mapRowToStorageThreadType);
|
|
1610
|
+
} catch (error$1) {
|
|
1611
|
+
const mastraError = new error.MastraError(
|
|
1612
|
+
{
|
|
1613
|
+
id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
|
|
1614
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1615
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1616
|
+
details: { resourceId }
|
|
1617
|
+
},
|
|
1618
|
+
error$1
|
|
1619
|
+
);
|
|
1620
|
+
this.logger?.trackException?.(mastraError);
|
|
1621
|
+
this.logger?.error?.(mastraError.toString());
|
|
1622
|
+
return [];
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
1626
|
+
const { resourceId, page = 0, perPage = 100 } = args;
|
|
1627
|
+
const orderBy = this.castThreadOrderBy(args.orderBy);
|
|
1628
|
+
const sortDirection = this.castThreadSortDirection(args.sortDirection);
|
|
1629
|
+
try {
|
|
1630
|
+
const baseQuery = `FROM ${storage.TABLE_THREADS} WHERE resourceId = ?`;
|
|
1631
|
+
const queryParams = [resourceId];
|
|
1632
|
+
const mapRowToStorageThreadType = (row) => ({
|
|
1633
|
+
id: row.id,
|
|
1634
|
+
resourceId: row.resourceId,
|
|
1635
|
+
title: row.title,
|
|
1636
|
+
createdAt: new Date(row.createdAt),
|
|
1637
|
+
// Convert string to Date
|
|
1638
|
+
updatedAt: new Date(row.updatedAt),
|
|
1639
|
+
// Convert string to Date
|
|
1640
|
+
metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
|
|
1641
|
+
});
|
|
1642
|
+
const currentOffset = page * perPage;
|
|
1643
|
+
const countResult = await this.client.execute({
|
|
1644
|
+
sql: `SELECT COUNT(*) as count ${baseQuery}`,
|
|
1645
|
+
args: queryParams
|
|
1646
|
+
});
|
|
1647
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
1648
|
+
if (total === 0) {
|
|
1649
|
+
return {
|
|
1650
|
+
threads: [],
|
|
1651
|
+
total: 0,
|
|
1652
|
+
page,
|
|
1653
|
+
perPage,
|
|
1654
|
+
hasMore: false
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
const dataResult = await this.client.execute({
|
|
1658
|
+
sql: `SELECT * ${baseQuery} ORDER BY ${orderBy} ${sortDirection} LIMIT ? OFFSET ?`,
|
|
1659
|
+
args: [...queryParams, perPage, currentOffset]
|
|
1660
|
+
});
|
|
1661
|
+
const threads = (dataResult.rows || []).map(mapRowToStorageThreadType);
|
|
1662
|
+
return {
|
|
1663
|
+
threads,
|
|
1664
|
+
total,
|
|
1665
|
+
page,
|
|
1666
|
+
perPage,
|
|
1667
|
+
hasMore: currentOffset + threads.length < total
|
|
1668
|
+
};
|
|
1669
|
+
} catch (error$1) {
|
|
1670
|
+
const mastraError = new error.MastraError(
|
|
1671
|
+
{
|
|
1672
|
+
id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
|
|
1673
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1674
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1675
|
+
details: { resourceId }
|
|
1676
|
+
},
|
|
1677
|
+
error$1
|
|
1678
|
+
);
|
|
1679
|
+
this.logger?.trackException?.(mastraError);
|
|
1680
|
+
this.logger?.error?.(mastraError.toString());
|
|
1681
|
+
return { threads: [], total: 0, page, perPage, hasMore: false };
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
async saveThread({ thread }) {
|
|
1685
|
+
try {
|
|
1686
|
+
await this.operations.insert({
|
|
1687
|
+
tableName: storage.TABLE_THREADS,
|
|
1688
|
+
record: {
|
|
1689
|
+
...thread,
|
|
1690
|
+
metadata: JSON.stringify(thread.metadata)
|
|
1691
|
+
}
|
|
1692
|
+
});
|
|
1693
|
+
return thread;
|
|
1694
|
+
} catch (error$1) {
|
|
1695
|
+
const mastraError = new error.MastraError(
|
|
1696
|
+
{
|
|
1697
|
+
id: "LIBSQL_STORE_SAVE_THREAD_FAILED",
|
|
1698
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1699
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1700
|
+
details: { threadId: thread.id }
|
|
1701
|
+
},
|
|
1702
|
+
error$1
|
|
1703
|
+
);
|
|
1704
|
+
this.logger?.trackException?.(mastraError);
|
|
1705
|
+
this.logger?.error?.(mastraError.toString());
|
|
1706
|
+
throw mastraError;
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
async updateThread({
|
|
1710
|
+
id,
|
|
1711
|
+
title,
|
|
1712
|
+
metadata
|
|
1713
|
+
}) {
|
|
1714
|
+
const thread = await this.getThreadById({ threadId: id });
|
|
1715
|
+
if (!thread) {
|
|
1716
|
+
throw new error.MastraError({
|
|
1717
|
+
id: "LIBSQL_STORE_UPDATE_THREAD_FAILED_THREAD_NOT_FOUND",
|
|
1718
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1719
|
+
category: error.ErrorCategory.USER,
|
|
1720
|
+
text: `Thread ${id} not found`,
|
|
1721
|
+
details: {
|
|
1722
|
+
status: 404,
|
|
1723
|
+
threadId: id
|
|
1724
|
+
}
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
const updatedThread = {
|
|
1728
|
+
...thread,
|
|
1729
|
+
title,
|
|
1730
|
+
metadata: {
|
|
1731
|
+
...thread.metadata,
|
|
1732
|
+
...metadata
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
try {
|
|
1736
|
+
await this.client.execute({
|
|
1737
|
+
sql: `UPDATE ${storage.TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
|
|
1738
|
+
args: [title, JSON.stringify(updatedThread.metadata), id]
|
|
1739
|
+
});
|
|
1740
|
+
return updatedThread;
|
|
1741
|
+
} catch (error$1) {
|
|
1742
|
+
throw new error.MastraError(
|
|
1743
|
+
{
|
|
1744
|
+
id: "LIBSQL_STORE_UPDATE_THREAD_FAILED",
|
|
1745
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1746
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1747
|
+
text: `Failed to update thread ${id}`,
|
|
1748
|
+
details: { threadId: id }
|
|
1749
|
+
},
|
|
1750
|
+
error$1
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
async deleteThread({ threadId }) {
|
|
1755
|
+
try {
|
|
1756
|
+
await this.client.execute({
|
|
1757
|
+
sql: `DELETE FROM ${storage.TABLE_MESSAGES} WHERE thread_id = ?`,
|
|
1758
|
+
args: [threadId]
|
|
1759
|
+
});
|
|
1760
|
+
await this.client.execute({
|
|
1761
|
+
sql: `DELETE FROM ${storage.TABLE_THREADS} WHERE id = ?`,
|
|
1762
|
+
args: [threadId]
|
|
1763
|
+
});
|
|
1764
|
+
} catch (error$1) {
|
|
1765
|
+
throw new error.MastraError(
|
|
1766
|
+
{
|
|
1767
|
+
id: "LIBSQL_STORE_DELETE_THREAD_FAILED",
|
|
1768
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1769
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1770
|
+
details: { threadId }
|
|
1771
|
+
},
|
|
1772
|
+
error$1
|
|
1773
|
+
);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
};
|
|
1777
|
+
function createExecuteWriteOperationWithRetry({
|
|
1778
|
+
logger,
|
|
1779
|
+
maxRetries,
|
|
1780
|
+
initialBackoffMs
|
|
1781
|
+
}) {
|
|
1782
|
+
return async function executeWriteOperationWithRetry(operationFn, operationDescription) {
|
|
1783
|
+
let retries = 0;
|
|
1784
|
+
while (true) {
|
|
1785
|
+
try {
|
|
1786
|
+
return await operationFn();
|
|
1787
|
+
} catch (error) {
|
|
1788
|
+
if (error.message && (error.message.includes("SQLITE_BUSY") || error.message.includes("database is locked")) && retries < maxRetries) {
|
|
1789
|
+
retries++;
|
|
1790
|
+
const backoffTime = initialBackoffMs * Math.pow(2, retries - 1);
|
|
1791
|
+
logger.warn(
|
|
1792
|
+
`LibSQLStore: Encountered SQLITE_BUSY during ${operationDescription}. Retrying (${retries}/${maxRetries}) in ${backoffTime}ms...`
|
|
1793
|
+
);
|
|
1794
|
+
await new Promise((resolve) => setTimeout(resolve, backoffTime));
|
|
1795
|
+
} else {
|
|
1796
|
+
logger.error(`LibSQLStore: Error during ${operationDescription} after ${retries} retries: ${error}`);
|
|
1797
|
+
throw error;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
function prepareStatement({ tableName, record }) {
|
|
1804
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
1805
|
+
const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
1806
|
+
const values = Object.values(record).map((v) => {
|
|
1807
|
+
if (typeof v === `undefined` || v === null) {
|
|
1808
|
+
return null;
|
|
1809
|
+
}
|
|
1810
|
+
if (v instanceof Date) {
|
|
1811
|
+
return v.toISOString();
|
|
1812
|
+
}
|
|
1813
|
+
return typeof v === "object" ? JSON.stringify(v) : v;
|
|
1814
|
+
});
|
|
1815
|
+
const placeholders = values.map(() => "?").join(", ");
|
|
1816
|
+
return {
|
|
1817
|
+
sql: `INSERT OR REPLACE INTO ${parsedTableName} (${columns.join(", ")}) VALUES (${placeholders})`,
|
|
1818
|
+
args: values
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
function prepareUpdateStatement({
|
|
1822
|
+
tableName,
|
|
1823
|
+
updates,
|
|
1824
|
+
keys
|
|
1825
|
+
}) {
|
|
1826
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
1827
|
+
const schema = storage.TABLE_SCHEMAS[tableName];
|
|
1828
|
+
const updateColumns = Object.keys(updates).map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
1829
|
+
const updateValues = Object.values(updates).map(transformToSqlValue);
|
|
1830
|
+
const setClause = updateColumns.map((col) => `${col} = ?`).join(", ");
|
|
1831
|
+
const whereClause = prepareWhereClause(keys, schema);
|
|
1832
|
+
return {
|
|
1833
|
+
sql: `UPDATE ${parsedTableName} SET ${setClause}${whereClause.sql}`,
|
|
1834
|
+
args: [...updateValues, ...whereClause.args]
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
function transformToSqlValue(value) {
|
|
1838
|
+
if (typeof value === "undefined" || value === null) {
|
|
1839
|
+
return null;
|
|
1840
|
+
}
|
|
1841
|
+
if (value instanceof Date) {
|
|
1842
|
+
return value.toISOString();
|
|
1843
|
+
}
|
|
1844
|
+
return typeof value === "object" ? JSON.stringify(value) : value;
|
|
1845
|
+
}
|
|
1846
|
+
function prepareDeleteStatement({ tableName, keys }) {
|
|
1847
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
1848
|
+
const whereClause = prepareWhereClause(keys, storage.TABLE_SCHEMAS[tableName]);
|
|
1849
|
+
return {
|
|
1850
|
+
sql: `DELETE FROM ${parsedTableName}${whereClause.sql}`,
|
|
1851
|
+
args: whereClause.args
|
|
1852
|
+
};
|
|
1853
|
+
}
|
|
1854
|
+
function prepareWhereClause(filters, schema) {
|
|
1855
|
+
const conditions = [];
|
|
1856
|
+
const args = [];
|
|
1857
|
+
for (const [columnName, filterValue] of Object.entries(filters)) {
|
|
1858
|
+
const column = schema[columnName];
|
|
1859
|
+
if (!column) {
|
|
1860
|
+
throw new Error(`Unknown column: ${columnName}`);
|
|
1861
|
+
}
|
|
1862
|
+
const parsedColumn = utils.parseSqlIdentifier(columnName, "column name");
|
|
1863
|
+
const result = buildCondition2(parsedColumn, filterValue);
|
|
1864
|
+
conditions.push(result.condition);
|
|
1865
|
+
args.push(...result.args);
|
|
1866
|
+
}
|
|
1867
|
+
return {
|
|
1868
|
+
sql: conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "",
|
|
1869
|
+
args
|
|
1870
|
+
};
|
|
1871
|
+
}
|
|
1872
|
+
function buildCondition2(columnName, filterValue) {
|
|
1873
|
+
if (filterValue === null) {
|
|
1874
|
+
return { condition: `${columnName} IS NULL`, args: [] };
|
|
1875
|
+
}
|
|
1876
|
+
if (typeof filterValue === "object" && filterValue !== null && ("startAt" in filterValue || "endAt" in filterValue)) {
|
|
1877
|
+
return buildDateRangeCondition(columnName, filterValue);
|
|
1878
|
+
}
|
|
1879
|
+
return {
|
|
1880
|
+
condition: `${columnName} = ?`,
|
|
1881
|
+
args: [transformToSqlValue(filterValue)]
|
|
1882
|
+
};
|
|
1883
|
+
}
|
|
1884
|
+
function buildDateRangeCondition(columnName, range) {
|
|
1885
|
+
const conditions = [];
|
|
1886
|
+
const args = [];
|
|
1887
|
+
if (range.startAt !== void 0) {
|
|
1888
|
+
conditions.push(`${columnName} >= ?`);
|
|
1889
|
+
args.push(transformToSqlValue(range.startAt));
|
|
1890
|
+
}
|
|
1891
|
+
if (range.endAt !== void 0) {
|
|
1892
|
+
conditions.push(`${columnName} <= ?`);
|
|
1893
|
+
args.push(transformToSqlValue(range.endAt));
|
|
1894
|
+
}
|
|
1895
|
+
if (conditions.length === 0) {
|
|
1896
|
+
throw new Error("Date range must specify at least startAt or endAt");
|
|
1897
|
+
}
|
|
1898
|
+
return {
|
|
1899
|
+
condition: conditions.join(" AND "),
|
|
1900
|
+
args
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
1903
|
+
function buildDateRangeFilter(dateRange, columnName = "createdAt") {
|
|
1904
|
+
if (!dateRange?.start && !dateRange?.end) {
|
|
1905
|
+
return {};
|
|
1906
|
+
}
|
|
1907
|
+
const filter = {};
|
|
1908
|
+
if (dateRange.start) {
|
|
1909
|
+
filter.startAt = new Date(dateRange.start).toISOString();
|
|
1910
|
+
}
|
|
1911
|
+
if (dateRange.end) {
|
|
1912
|
+
filter.endAt = new Date(dateRange.end).toISOString();
|
|
1913
|
+
}
|
|
1914
|
+
return { [columnName]: filter };
|
|
1915
|
+
}
|
|
1916
|
+
function transformFromSqlRow({
|
|
1917
|
+
tableName,
|
|
1918
|
+
sqlRow
|
|
1919
|
+
}) {
|
|
1920
|
+
const result = {};
|
|
1921
|
+
const jsonColumns = new Set(
|
|
1922
|
+
Object.keys(storage.TABLE_SCHEMAS[tableName]).filter((key) => storage.TABLE_SCHEMAS[tableName][key].type === "jsonb").map((key) => key)
|
|
1923
|
+
);
|
|
1924
|
+
const dateColumns = new Set(
|
|
1925
|
+
Object.keys(storage.TABLE_SCHEMAS[tableName]).filter((key) => storage.TABLE_SCHEMAS[tableName][key].type === "timestamp").map((key) => key)
|
|
1926
|
+
);
|
|
1927
|
+
for (const [key, value] of Object.entries(sqlRow)) {
|
|
1928
|
+
if (value === null || value === void 0) {
|
|
1929
|
+
result[key] = value;
|
|
1930
|
+
continue;
|
|
1931
|
+
}
|
|
1932
|
+
if (dateColumns.has(key) && typeof value === "string") {
|
|
1933
|
+
result[key] = new Date(value);
|
|
1934
|
+
continue;
|
|
1935
|
+
}
|
|
1936
|
+
if (jsonColumns.has(key) && typeof value === "string") {
|
|
1937
|
+
result[key] = storage.safelyParseJSON(value);
|
|
1938
|
+
continue;
|
|
1939
|
+
}
|
|
1940
|
+
result[key] = value;
|
|
1941
|
+
}
|
|
1942
|
+
return result;
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
// src/storage/domains/observability/index.ts
|
|
1946
|
+
var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
|
|
1947
|
+
operations;
|
|
1948
|
+
constructor({ operations }) {
|
|
1949
|
+
super();
|
|
1950
|
+
this.operations = operations;
|
|
1951
|
+
}
|
|
1952
|
+
async createAISpan(span) {
|
|
1953
|
+
try {
|
|
1954
|
+
return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record: span });
|
|
1955
|
+
} catch (error$1) {
|
|
1956
|
+
throw new error.MastraError(
|
|
1957
|
+
{
|
|
1958
|
+
id: "LIBSQL_STORE_CREATE_AI_SPAN_FAILED",
|
|
1959
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1960
|
+
category: error.ErrorCategory.USER,
|
|
1961
|
+
details: {
|
|
1962
|
+
spanId: span.spanId,
|
|
1963
|
+
traceId: span.traceId,
|
|
1964
|
+
spanType: span.spanType,
|
|
1965
|
+
spanName: span.name
|
|
1966
|
+
}
|
|
1967
|
+
},
|
|
1968
|
+
error$1
|
|
1969
|
+
);
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
async getAITrace(traceId) {
|
|
1973
|
+
try {
|
|
1974
|
+
const spans = await this.operations.loadMany({
|
|
1975
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
1976
|
+
whereClause: { sql: " WHERE traceId = ?", args: [traceId] },
|
|
1977
|
+
orderBy: "startedAt DESC"
|
|
1978
|
+
});
|
|
1979
|
+
if (!spans || spans.length === 0) {
|
|
1980
|
+
return null;
|
|
1981
|
+
}
|
|
1982
|
+
return {
|
|
1983
|
+
traceId,
|
|
1984
|
+
spans: spans.map((span) => transformFromSqlRow({ tableName: storage.TABLE_AI_SPANS, sqlRow: span }))
|
|
1985
|
+
};
|
|
1986
|
+
} catch (error$1) {
|
|
1987
|
+
throw new error.MastraError(
|
|
1988
|
+
{
|
|
1989
|
+
id: "LIBSQL_STORE_GET_AI_TRACE_FAILED",
|
|
1990
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1991
|
+
category: error.ErrorCategory.USER,
|
|
1992
|
+
details: {
|
|
1993
|
+
traceId
|
|
1994
|
+
}
|
|
1995
|
+
},
|
|
1996
|
+
error$1
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
async updateAISpan({
|
|
2001
|
+
spanId,
|
|
2002
|
+
traceId,
|
|
2003
|
+
updates
|
|
2004
|
+
}) {
|
|
2005
|
+
try {
|
|
2006
|
+
await this.operations.update({
|
|
2007
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
2008
|
+
keys: { spanId, traceId },
|
|
2009
|
+
data: { ...updates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
2010
|
+
});
|
|
2011
|
+
} catch (error$1) {
|
|
2012
|
+
throw new error.MastraError(
|
|
2013
|
+
{
|
|
2014
|
+
id: "LIBSQL_STORE_UPDATE_AI_SPAN_FAILED",
|
|
2015
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2016
|
+
category: error.ErrorCategory.USER,
|
|
2017
|
+
details: {
|
|
2018
|
+
spanId,
|
|
2019
|
+
traceId
|
|
2020
|
+
}
|
|
2021
|
+
},
|
|
2022
|
+
error$1
|
|
2023
|
+
);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
async getAITracesPaginated({
|
|
2027
|
+
filters,
|
|
2028
|
+
pagination
|
|
2029
|
+
}) {
|
|
2030
|
+
const page = pagination?.page ?? 0;
|
|
2031
|
+
const perPage = pagination?.perPage ?? 10;
|
|
2032
|
+
const { entityId, entityType, ...actualFilters } = filters || {};
|
|
2033
|
+
const filtersWithDateRange = {
|
|
2034
|
+
...actualFilters,
|
|
2035
|
+
...buildDateRangeFilter(pagination?.dateRange, "startedAt"),
|
|
2036
|
+
parentSpanId: null
|
|
2037
|
+
};
|
|
2038
|
+
const whereClause = prepareWhereClause(filtersWithDateRange, storage.AI_SPAN_SCHEMA);
|
|
2039
|
+
let actualWhereClause = whereClause.sql || "";
|
|
2040
|
+
if (entityId && entityType) {
|
|
2041
|
+
const statement = `name = ?`;
|
|
2042
|
+
let name = "";
|
|
2043
|
+
if (entityType === "workflow") {
|
|
2044
|
+
name = `workflow run: '${entityId}'`;
|
|
2045
|
+
} else if (entityType === "agent") {
|
|
2046
|
+
name = `agent run: '${entityId}'`;
|
|
2047
|
+
} else {
|
|
2048
|
+
const error$1 = new error.MastraError({
|
|
2049
|
+
id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
|
|
2050
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2051
|
+
category: error.ErrorCategory.USER,
|
|
2052
|
+
details: {
|
|
2053
|
+
entityType
|
|
2054
|
+
},
|
|
2055
|
+
text: `Cannot filter by entity type: ${entityType}`
|
|
2056
|
+
});
|
|
2057
|
+
this.logger?.trackException(error$1);
|
|
2058
|
+
throw error$1;
|
|
2059
|
+
}
|
|
2060
|
+
whereClause.args.push(name);
|
|
2061
|
+
if (actualWhereClause) {
|
|
2062
|
+
actualWhereClause += ` AND ${statement}`;
|
|
2063
|
+
} else {
|
|
2064
|
+
actualWhereClause += `WHERE ${statement}`;
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
const orderBy = "startedAt DESC";
|
|
2068
|
+
let count = 0;
|
|
2069
|
+
try {
|
|
2070
|
+
count = await this.operations.loadTotalCount({
|
|
2071
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
2072
|
+
whereClause: { sql: actualWhereClause, args: whereClause.args }
|
|
2073
|
+
});
|
|
2074
|
+
} catch (error$1) {
|
|
2075
|
+
throw new error.MastraError(
|
|
2076
|
+
{
|
|
2077
|
+
id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_COUNT_FAILED",
|
|
2078
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2079
|
+
category: error.ErrorCategory.USER
|
|
2080
|
+
},
|
|
2081
|
+
error$1
|
|
2082
|
+
);
|
|
2083
|
+
}
|
|
2084
|
+
if (count === 0) {
|
|
2085
|
+
return {
|
|
2086
|
+
pagination: {
|
|
2087
|
+
total: 0,
|
|
2088
|
+
page,
|
|
2089
|
+
perPage,
|
|
2090
|
+
hasMore: false
|
|
2091
|
+
},
|
|
2092
|
+
spans: []
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
try {
|
|
2096
|
+
const spans = await this.operations.loadMany({
|
|
2097
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
2098
|
+
whereClause: {
|
|
2099
|
+
sql: actualWhereClause,
|
|
2100
|
+
args: whereClause.args
|
|
2101
|
+
},
|
|
2102
|
+
orderBy,
|
|
2103
|
+
offset: page * perPage,
|
|
2104
|
+
limit: perPage
|
|
2105
|
+
});
|
|
2106
|
+
return {
|
|
2107
|
+
pagination: {
|
|
2108
|
+
total: count,
|
|
2109
|
+
page,
|
|
2110
|
+
perPage,
|
|
2111
|
+
hasMore: spans.length === perPage
|
|
2112
|
+
},
|
|
2113
|
+
spans: spans.map((span) => transformFromSqlRow({ tableName: storage.TABLE_AI_SPANS, sqlRow: span }))
|
|
2114
|
+
};
|
|
2115
|
+
} catch (error$1) {
|
|
2116
|
+
throw new error.MastraError(
|
|
2117
|
+
{
|
|
2118
|
+
id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
|
|
2119
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2120
|
+
category: error.ErrorCategory.USER
|
|
2121
|
+
},
|
|
2122
|
+
error$1
|
|
2123
|
+
);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
async batchCreateAISpans(args) {
|
|
2127
|
+
try {
|
|
2128
|
+
return this.operations.batchInsert({
|
|
2129
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
2130
|
+
records: args.records.map((record) => ({
|
|
2131
|
+
...record,
|
|
2132
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2133
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2134
|
+
}))
|
|
2135
|
+
});
|
|
2136
|
+
} catch (error$1) {
|
|
2137
|
+
throw new error.MastraError(
|
|
2138
|
+
{
|
|
2139
|
+
id: "LIBSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
|
|
2140
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2141
|
+
category: error.ErrorCategory.USER
|
|
2142
|
+
},
|
|
2143
|
+
error$1
|
|
2144
|
+
);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
async batchUpdateAISpans(args) {
|
|
2148
|
+
try {
|
|
2149
|
+
return this.operations.batchUpdate({
|
|
2150
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
2151
|
+
updates: args.records.map((record) => ({
|
|
2152
|
+
keys: { spanId: record.spanId, traceId: record.traceId },
|
|
2153
|
+
data: { ...record.updates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
2154
|
+
}))
|
|
2155
|
+
});
|
|
2156
|
+
} catch (error$1) {
|
|
2157
|
+
throw new error.MastraError(
|
|
2158
|
+
{
|
|
2159
|
+
id: "LIBSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
|
|
2160
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2161
|
+
category: error.ErrorCategory.USER
|
|
2162
|
+
},
|
|
2163
|
+
error$1
|
|
2164
|
+
);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
async batchDeleteAITraces(args) {
|
|
2168
|
+
try {
|
|
2169
|
+
const keys = args.traceIds.map((traceId) => ({ traceId }));
|
|
2170
|
+
return this.operations.batchDelete({
|
|
2171
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
2172
|
+
keys
|
|
2173
|
+
});
|
|
2174
|
+
} catch (error$1) {
|
|
2175
|
+
throw new error.MastraError(
|
|
2176
|
+
{
|
|
2177
|
+
id: "LIBSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
|
|
2178
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2179
|
+
category: error.ErrorCategory.USER
|
|
2180
|
+
},
|
|
2181
|
+
error$1
|
|
2182
|
+
);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
};
|
|
2186
|
+
var StoreOperationsLibSQL = class extends storage.StoreOperations {
|
|
2187
|
+
client;
|
|
2188
|
+
/**
|
|
2189
|
+
* Maximum number of retries for write operations if an SQLITE_BUSY error occurs.
|
|
2190
|
+
* @default 5
|
|
2191
|
+
*/
|
|
2192
|
+
maxRetries;
|
|
2193
|
+
/**
|
|
2194
|
+
* Initial backoff time in milliseconds for retrying write operations on SQLITE_BUSY.
|
|
2195
|
+
* The backoff time will double with each retry (exponential backoff).
|
|
2196
|
+
* @default 100
|
|
2197
|
+
*/
|
|
2198
|
+
initialBackoffMs;
|
|
2199
|
+
constructor({
|
|
2200
|
+
client,
|
|
2201
|
+
maxRetries,
|
|
2202
|
+
initialBackoffMs
|
|
2203
|
+
}) {
|
|
2204
|
+
super();
|
|
2205
|
+
this.client = client;
|
|
2206
|
+
this.maxRetries = maxRetries ?? 5;
|
|
2207
|
+
this.initialBackoffMs = initialBackoffMs ?? 100;
|
|
2208
|
+
}
|
|
2209
|
+
async hasColumn(table, column) {
|
|
2210
|
+
const result = await this.client.execute({
|
|
2211
|
+
sql: `PRAGMA table_info(${table})`
|
|
2212
|
+
});
|
|
2213
|
+
return (await result.rows)?.some((row) => row.name === column);
|
|
2214
|
+
}
|
|
2215
|
+
getCreateTableSQL(tableName, schema) {
|
|
2216
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2217
|
+
const columns = Object.entries(schema).map(([name, col]) => {
|
|
2218
|
+
const parsedColumnName = utils.parseSqlIdentifier(name, "column name");
|
|
2219
|
+
let type = col.type.toUpperCase();
|
|
2220
|
+
if (type === "TEXT") type = "TEXT";
|
|
2221
|
+
if (type === "TIMESTAMP") type = "TEXT";
|
|
2222
|
+
const nullable = col.nullable ? "" : "NOT NULL";
|
|
2223
|
+
const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
|
|
2224
|
+
return `${parsedColumnName} ${type} ${nullable} ${primaryKey}`.trim();
|
|
2225
|
+
});
|
|
2226
|
+
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
2227
|
+
const stmnt = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (
|
|
2228
|
+
${columns.join(",\n")},
|
|
2229
|
+
PRIMARY KEY (workflow_name, run_id)
|
|
2230
|
+
)`;
|
|
2231
|
+
return stmnt;
|
|
2232
|
+
}
|
|
2233
|
+
if (tableName === storage.TABLE_AI_SPANS) {
|
|
2234
|
+
const stmnt = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (
|
|
2235
|
+
${columns.join(",\n")},
|
|
2236
|
+
PRIMARY KEY (traceId, spanId)
|
|
2237
|
+
)`;
|
|
2238
|
+
return stmnt;
|
|
2239
|
+
}
|
|
2240
|
+
return `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns.join(", ")})`;
|
|
2241
|
+
}
|
|
2242
|
+
async createTable({
|
|
2243
|
+
tableName,
|
|
2244
|
+
schema
|
|
2245
|
+
}) {
|
|
2246
|
+
try {
|
|
2247
|
+
this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
|
|
2248
|
+
const sql = this.getCreateTableSQL(tableName, schema);
|
|
2249
|
+
await this.client.execute(sql);
|
|
2250
|
+
} catch (error$1) {
|
|
2251
|
+
throw new error.MastraError(
|
|
2252
|
+
{
|
|
2253
|
+
id: "LIBSQL_STORE_CREATE_TABLE_FAILED",
|
|
2254
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2255
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2256
|
+
details: {
|
|
2257
|
+
tableName
|
|
2258
|
+
}
|
|
2259
|
+
},
|
|
2260
|
+
error$1
|
|
2261
|
+
);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
getSqlType(type) {
|
|
2265
|
+
switch (type) {
|
|
2266
|
+
case "bigint":
|
|
2267
|
+
return "INTEGER";
|
|
2268
|
+
// SQLite uses INTEGER for all integer sizes
|
|
2269
|
+
case "jsonb":
|
|
2270
|
+
return "TEXT";
|
|
2271
|
+
// Store JSON as TEXT in SQLite
|
|
2272
|
+
default:
|
|
2273
|
+
return super.getSqlType(type);
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
async doInsert({
|
|
2277
|
+
tableName,
|
|
2278
|
+
record
|
|
2279
|
+
}) {
|
|
2280
|
+
await this.client.execute(
|
|
2281
|
+
prepareStatement({
|
|
2282
|
+
tableName,
|
|
2283
|
+
record
|
|
2284
|
+
})
|
|
2285
|
+
);
|
|
2286
|
+
}
|
|
2287
|
+
insert(args) {
|
|
2288
|
+
const executeWriteOperationWithRetry = createExecuteWriteOperationWithRetry({
|
|
2289
|
+
logger: this.logger,
|
|
2290
|
+
maxRetries: this.maxRetries,
|
|
2291
|
+
initialBackoffMs: this.initialBackoffMs
|
|
2292
|
+
});
|
|
2293
|
+
return executeWriteOperationWithRetry(() => this.doInsert(args), `insert into table ${args.tableName}`);
|
|
2294
|
+
}
|
|
2295
|
+
async load({ tableName, keys }) {
|
|
2296
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2297
|
+
const parsedKeys = Object.keys(keys).map((key) => utils.parseSqlIdentifier(key, "column name"));
|
|
2298
|
+
const conditions = parsedKeys.map((key) => `${key} = ?`).join(" AND ");
|
|
2299
|
+
const values = Object.values(keys);
|
|
2300
|
+
const result = await this.client.execute({
|
|
2301
|
+
sql: `SELECT * FROM ${parsedTableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
|
|
2302
|
+
args: values
|
|
2303
|
+
});
|
|
2304
|
+
if (!result.rows || result.rows.length === 0) {
|
|
2305
|
+
return null;
|
|
2306
|
+
}
|
|
2307
|
+
const row = result.rows[0];
|
|
2308
|
+
const parsed = Object.fromEntries(
|
|
2309
|
+
Object.entries(row || {}).map(([k, v]) => {
|
|
2310
|
+
try {
|
|
2311
|
+
return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
|
|
2312
|
+
} catch {
|
|
2313
|
+
return [k, v];
|
|
2314
|
+
}
|
|
2315
|
+
})
|
|
2316
|
+
);
|
|
2317
|
+
return parsed;
|
|
2318
|
+
}
|
|
2319
|
+
async loadMany({
|
|
2320
|
+
tableName,
|
|
2321
|
+
whereClause,
|
|
2322
|
+
orderBy,
|
|
2323
|
+
offset,
|
|
2324
|
+
limit,
|
|
2325
|
+
args
|
|
2326
|
+
}) {
|
|
2327
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2328
|
+
let statement = `SELECT * FROM ${parsedTableName}`;
|
|
2329
|
+
if (whereClause?.sql) {
|
|
2330
|
+
statement += `${whereClause.sql}`;
|
|
2331
|
+
}
|
|
2332
|
+
if (orderBy) {
|
|
2333
|
+
statement += ` ORDER BY ${orderBy}`;
|
|
2334
|
+
}
|
|
2335
|
+
if (limit) {
|
|
2336
|
+
statement += ` LIMIT ${limit}`;
|
|
2337
|
+
}
|
|
2338
|
+
if (offset) {
|
|
2339
|
+
statement += ` OFFSET ${offset}`;
|
|
2340
|
+
}
|
|
2341
|
+
const result = await this.client.execute({
|
|
2342
|
+
sql: statement,
|
|
2343
|
+
args: [...whereClause?.args ?? [], ...args ?? []]
|
|
2344
|
+
});
|
|
2345
|
+
return result.rows;
|
|
2346
|
+
}
|
|
2347
|
+
async loadTotalCount({
|
|
2348
|
+
tableName,
|
|
2349
|
+
whereClause
|
|
2350
|
+
}) {
|
|
2351
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2352
|
+
const statement = `SELECT COUNT(*) as count FROM ${parsedTableName} ${whereClause ? `${whereClause.sql}` : ""}`;
|
|
2353
|
+
const result = await this.client.execute({
|
|
2354
|
+
sql: statement,
|
|
2355
|
+
args: whereClause?.args ?? []
|
|
2356
|
+
});
|
|
2357
|
+
if (!result.rows || result.rows.length === 0) {
|
|
2358
|
+
return 0;
|
|
2359
|
+
}
|
|
2360
|
+
return result.rows[0]?.count ?? 0;
|
|
2361
|
+
}
|
|
2362
|
+
update(args) {
|
|
2363
|
+
const executeWriteOperationWithRetry = createExecuteWriteOperationWithRetry({
|
|
2364
|
+
logger: this.logger,
|
|
2365
|
+
maxRetries: this.maxRetries,
|
|
2366
|
+
initialBackoffMs: this.initialBackoffMs
|
|
2367
|
+
});
|
|
2368
|
+
return executeWriteOperationWithRetry(() => this.executeUpdate(args), `update table ${args.tableName}`);
|
|
2369
|
+
}
|
|
2370
|
+
async executeUpdate({
|
|
2371
|
+
tableName,
|
|
2372
|
+
keys,
|
|
2373
|
+
data
|
|
2374
|
+
}) {
|
|
2375
|
+
await this.client.execute(prepareUpdateStatement({ tableName, updates: data, keys }));
|
|
2376
|
+
}
|
|
2377
|
+
async doBatchInsert({
|
|
2378
|
+
tableName,
|
|
2379
|
+
records
|
|
2380
|
+
}) {
|
|
2381
|
+
if (records.length === 0) return;
|
|
2382
|
+
const batchStatements = records.map((r) => prepareStatement({ tableName, record: r }));
|
|
2383
|
+
await this.client.batch(batchStatements, "write");
|
|
2384
|
+
}
|
|
2385
|
+
batchInsert(args) {
|
|
2386
|
+
const executeWriteOperationWithRetry = createExecuteWriteOperationWithRetry({
|
|
2387
|
+
logger: this.logger,
|
|
2388
|
+
maxRetries: this.maxRetries,
|
|
2389
|
+
initialBackoffMs: this.initialBackoffMs
|
|
2390
|
+
});
|
|
2391
|
+
return executeWriteOperationWithRetry(
|
|
2392
|
+
() => this.doBatchInsert(args),
|
|
2393
|
+
`batch insert into table ${args.tableName}`
|
|
2394
|
+
).catch((error$1) => {
|
|
2395
|
+
throw new error.MastraError(
|
|
2396
|
+
{
|
|
2397
|
+
id: "LIBSQL_STORE_BATCH_INSERT_FAILED",
|
|
2398
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2399
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2400
|
+
details: {
|
|
2401
|
+
tableName: args.tableName
|
|
2402
|
+
}
|
|
2403
|
+
},
|
|
2404
|
+
error$1
|
|
2405
|
+
);
|
|
2406
|
+
});
|
|
2407
|
+
}
|
|
2408
|
+
/**
|
|
2409
|
+
* Public batch update method with retry logic
|
|
2410
|
+
*/
|
|
2411
|
+
batchUpdate(args) {
|
|
2412
|
+
const executeWriteOperationWithRetry = createExecuteWriteOperationWithRetry({
|
|
2413
|
+
logger: this.logger,
|
|
2414
|
+
maxRetries: this.maxRetries,
|
|
2415
|
+
initialBackoffMs: this.initialBackoffMs
|
|
2416
|
+
});
|
|
2417
|
+
return executeWriteOperationWithRetry(
|
|
2418
|
+
() => this.executeBatchUpdate(args),
|
|
2419
|
+
`batch update in table ${args.tableName}`
|
|
2420
|
+
).catch((error$1) => {
|
|
2421
|
+
throw new error.MastraError(
|
|
2422
|
+
{
|
|
2423
|
+
id: "LIBSQL_STORE_BATCH_UPDATE_FAILED",
|
|
2424
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2425
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2426
|
+
details: {
|
|
2427
|
+
tableName: args.tableName
|
|
2428
|
+
}
|
|
2429
|
+
},
|
|
2430
|
+
error$1
|
|
2431
|
+
);
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* Updates multiple records in batch. Each record can be updated based on single or composite keys.
|
|
2436
|
+
*/
|
|
2437
|
+
async executeBatchUpdate({
|
|
2438
|
+
tableName,
|
|
2439
|
+
updates
|
|
2440
|
+
}) {
|
|
2441
|
+
if (updates.length === 0) return;
|
|
2442
|
+
const batchStatements = updates.map(
|
|
2443
|
+
({ keys, data }) => prepareUpdateStatement({
|
|
2444
|
+
tableName,
|
|
2445
|
+
updates: data,
|
|
2446
|
+
keys
|
|
2447
|
+
})
|
|
2448
|
+
);
|
|
2449
|
+
await this.client.batch(batchStatements, "write");
|
|
2450
|
+
}
|
|
2451
|
+
/**
|
|
2452
|
+
* Public batch delete method with retry logic
|
|
2453
|
+
*/
|
|
2454
|
+
batchDelete({ tableName, keys }) {
|
|
2455
|
+
const executeWriteOperationWithRetry = createExecuteWriteOperationWithRetry({
|
|
2456
|
+
logger: this.logger,
|
|
2457
|
+
maxRetries: this.maxRetries,
|
|
2458
|
+
initialBackoffMs: this.initialBackoffMs
|
|
2459
|
+
});
|
|
2460
|
+
return executeWriteOperationWithRetry(
|
|
2461
|
+
() => this.executeBatchDelete({ tableName, keys }),
|
|
2462
|
+
`batch delete from table ${tableName}`
|
|
2463
|
+
).catch((error$1) => {
|
|
2464
|
+
throw new error.MastraError(
|
|
2465
|
+
{
|
|
2466
|
+
id: "LIBSQL_STORE_BATCH_DELETE_FAILED",
|
|
2467
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2468
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2469
|
+
details: {
|
|
2470
|
+
tableName
|
|
2471
|
+
}
|
|
2472
|
+
},
|
|
2473
|
+
error$1
|
|
2474
|
+
);
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* Deletes multiple records in batch. Each record can be deleted based on single or composite keys.
|
|
2479
|
+
*/
|
|
2480
|
+
async executeBatchDelete({
|
|
2481
|
+
tableName,
|
|
2482
|
+
keys
|
|
2483
|
+
}) {
|
|
2484
|
+
if (keys.length === 0) return;
|
|
2485
|
+
const batchStatements = keys.map(
|
|
2486
|
+
(keyObj) => prepareDeleteStatement({
|
|
2487
|
+
tableName,
|
|
2488
|
+
keys: keyObj
|
|
2489
|
+
})
|
|
2490
|
+
);
|
|
2491
|
+
await this.client.batch(batchStatements, "write");
|
|
2492
|
+
}
|
|
2493
|
+
/**
|
|
2494
|
+
* Alters table schema to add columns if they don't exist
|
|
2495
|
+
* @param tableName Name of the table
|
|
2496
|
+
* @param schema Schema of the table
|
|
2497
|
+
* @param ifNotExists Array of column names to add if they don't exist
|
|
2498
|
+
*/
|
|
2499
|
+
async alterTable({
|
|
2500
|
+
tableName,
|
|
2501
|
+
schema,
|
|
2502
|
+
ifNotExists
|
|
2503
|
+
}) {
|
|
2504
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2505
|
+
try {
|
|
2506
|
+
const pragmaQuery = `PRAGMA table_info(${parsedTableName})`;
|
|
2507
|
+
const result = await this.client.execute(pragmaQuery);
|
|
2508
|
+
const existingColumnNames = new Set(result.rows.map((row) => row.name.toLowerCase()));
|
|
2509
|
+
for (const columnName of ifNotExists) {
|
|
2510
|
+
if (!existingColumnNames.has(columnName.toLowerCase()) && schema[columnName]) {
|
|
2511
|
+
const columnDef = schema[columnName];
|
|
2512
|
+
const sqlType = this.getSqlType(columnDef.type);
|
|
2513
|
+
const nullable = columnDef.nullable === false ? "NOT NULL" : "";
|
|
2514
|
+
const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
|
|
2515
|
+
const alterSql = `ALTER TABLE ${parsedTableName} ADD COLUMN "${columnName}" ${sqlType} ${nullable} ${defaultValue}`.trim();
|
|
2516
|
+
await this.client.execute(alterSql);
|
|
2517
|
+
this.logger?.debug?.(`Added column ${columnName} to table ${parsedTableName}`);
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
} catch (error$1) {
|
|
2521
|
+
throw new error.MastraError(
|
|
2522
|
+
{
|
|
2523
|
+
id: "LIBSQL_STORE_ALTER_TABLE_FAILED",
|
|
2524
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2525
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2526
|
+
details: {
|
|
2527
|
+
tableName
|
|
2528
|
+
}
|
|
2529
|
+
},
|
|
2530
|
+
error$1
|
|
2531
|
+
);
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
async clearTable({ tableName }) {
|
|
2535
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2536
|
+
try {
|
|
2537
|
+
await this.client.execute(`DELETE FROM ${parsedTableName}`);
|
|
2538
|
+
} catch (e) {
|
|
2539
|
+
const mastraError = new error.MastraError(
|
|
2540
|
+
{
|
|
2541
|
+
id: "LIBSQL_STORE_CLEAR_TABLE_FAILED",
|
|
2542
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2543
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2544
|
+
details: {
|
|
2545
|
+
tableName
|
|
2546
|
+
}
|
|
2547
|
+
},
|
|
2548
|
+
e
|
|
2549
|
+
);
|
|
2550
|
+
this.logger?.trackException?.(mastraError);
|
|
2551
|
+
this.logger?.error?.(mastraError.toString());
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
async dropTable({ tableName }) {
|
|
2555
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
2556
|
+
try {
|
|
2557
|
+
await this.client.execute(`DROP TABLE IF EXISTS ${parsedTableName}`);
|
|
2558
|
+
} catch (e) {
|
|
2559
|
+
throw new error.MastraError(
|
|
2560
|
+
{
|
|
2561
|
+
id: "LIBSQL_STORE_DROP_TABLE_FAILED",
|
|
2562
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2563
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2564
|
+
details: {
|
|
2565
|
+
tableName
|
|
2566
|
+
}
|
|
2567
|
+
},
|
|
2568
|
+
e
|
|
2569
|
+
);
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
};
|
|
2573
|
+
var ScoresLibSQL = class extends storage.ScoresStorage {
|
|
2574
|
+
operations;
|
|
2575
|
+
client;
|
|
2576
|
+
constructor({ client, operations }) {
|
|
2577
|
+
super();
|
|
2578
|
+
this.operations = operations;
|
|
2579
|
+
this.client = client;
|
|
2580
|
+
}
|
|
2581
|
+
async getScoresByRunId({
|
|
2582
|
+
runId,
|
|
2583
|
+
pagination
|
|
2584
|
+
}) {
|
|
2585
|
+
try {
|
|
2586
|
+
const result = await this.client.execute({
|
|
2587
|
+
sql: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE runId = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
|
|
2588
|
+
args: [runId, pagination.perPage + 1, pagination.page * pagination.perPage]
|
|
2589
|
+
});
|
|
2590
|
+
return {
|
|
2591
|
+
scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
|
|
2592
|
+
pagination: {
|
|
2593
|
+
total: result.rows?.length ?? 0,
|
|
2594
|
+
page: pagination.page,
|
|
2595
|
+
perPage: pagination.perPage,
|
|
2596
|
+
hasMore: result.rows?.length > pagination.perPage
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
} catch (error$1) {
|
|
2600
|
+
throw new error.MastraError(
|
|
2601
|
+
{
|
|
2602
|
+
id: "LIBSQL_STORE_GET_SCORES_BY_RUN_ID_FAILED",
|
|
2603
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2604
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
2605
|
+
},
|
|
2606
|
+
error$1
|
|
2607
|
+
);
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
async getScoresByScorerId({
|
|
2611
|
+
scorerId,
|
|
2612
|
+
entityId,
|
|
2613
|
+
entityType,
|
|
2614
|
+
source,
|
|
2615
|
+
pagination
|
|
2616
|
+
}) {
|
|
2617
|
+
try {
|
|
2618
|
+
const conditions = [];
|
|
2619
|
+
const queryParams = [];
|
|
2620
|
+
if (scorerId) {
|
|
2621
|
+
conditions.push(`scorerId = ?`);
|
|
2622
|
+
queryParams.push(scorerId);
|
|
2623
|
+
}
|
|
2624
|
+
if (entityId) {
|
|
2625
|
+
conditions.push(`entityId = ?`);
|
|
2626
|
+
queryParams.push(entityId);
|
|
2627
|
+
}
|
|
2628
|
+
if (entityType) {
|
|
2629
|
+
conditions.push(`entityType = ?`);
|
|
2630
|
+
queryParams.push(entityType);
|
|
2631
|
+
}
|
|
2632
|
+
if (source) {
|
|
2633
|
+
conditions.push(`source = ?`);
|
|
2634
|
+
queryParams.push(source);
|
|
2635
|
+
}
|
|
2636
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
2637
|
+
const result = await this.client.execute({
|
|
2638
|
+
sql: `SELECT * FROM ${storage.TABLE_SCORERS} ${whereClause} ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
|
|
2639
|
+
args: [...queryParams, pagination.perPage + 1, pagination.page * pagination.perPage]
|
|
2640
|
+
});
|
|
2641
|
+
return {
|
|
2642
|
+
scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
|
|
2643
|
+
pagination: {
|
|
2644
|
+
total: result.rows?.length ?? 0,
|
|
2645
|
+
page: pagination.page,
|
|
2646
|
+
perPage: pagination.perPage,
|
|
2647
|
+
hasMore: result.rows?.length > pagination.perPage
|
|
2648
|
+
}
|
|
2649
|
+
};
|
|
2650
|
+
} catch (error$1) {
|
|
2651
|
+
throw new error.MastraError(
|
|
2652
|
+
{
|
|
2653
|
+
id: "LIBSQL_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
2654
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2655
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
2656
|
+
},
|
|
2657
|
+
error$1
|
|
2658
|
+
);
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
transformScoreRow(row) {
|
|
2662
|
+
const scorerValue = storage.safelyParseJSON(row.scorer);
|
|
2663
|
+
const inputValue = storage.safelyParseJSON(row.input ?? "{}");
|
|
2664
|
+
const outputValue = storage.safelyParseJSON(row.output ?? "{}");
|
|
2665
|
+
const additionalLLMContextValue = row.additionalLLMContext ? storage.safelyParseJSON(row.additionalLLMContext) : null;
|
|
2666
|
+
const runtimeContextValue = row.runtimeContext ? storage.safelyParseJSON(row.runtimeContext) : null;
|
|
2667
|
+
const metadataValue = row.metadata ? storage.safelyParseJSON(row.metadata) : null;
|
|
2668
|
+
const entityValue = row.entity ? storage.safelyParseJSON(row.entity) : null;
|
|
2669
|
+
const preprocessStepResultValue = row.preprocessStepResult ? storage.safelyParseJSON(row.preprocessStepResult) : null;
|
|
2670
|
+
const analyzeStepResultValue = row.analyzeStepResult ? storage.safelyParseJSON(row.analyzeStepResult) : null;
|
|
2671
|
+
return {
|
|
2672
|
+
id: row.id,
|
|
2673
|
+
traceId: row.traceId,
|
|
2674
|
+
runId: row.runId,
|
|
2675
|
+
scorer: scorerValue,
|
|
2676
|
+
score: row.score,
|
|
2677
|
+
reason: row.reason,
|
|
2678
|
+
preprocessStepResult: preprocessStepResultValue,
|
|
2679
|
+
analyzeStepResult: analyzeStepResultValue,
|
|
2680
|
+
analyzePrompt: row.analyzePrompt,
|
|
2681
|
+
preprocessPrompt: row.preprocessPrompt,
|
|
2682
|
+
generateScorePrompt: row.generateScorePrompt,
|
|
2683
|
+
generateReasonPrompt: row.generateReasonPrompt,
|
|
2684
|
+
metadata: metadataValue,
|
|
2685
|
+
input: inputValue,
|
|
2686
|
+
output: outputValue,
|
|
2687
|
+
additionalContext: additionalLLMContextValue,
|
|
2688
|
+
runtimeContext: runtimeContextValue,
|
|
2689
|
+
entityType: row.entityType,
|
|
2690
|
+
entity: entityValue,
|
|
2691
|
+
entityId: row.entityId,
|
|
2692
|
+
scorerId: row.scorerId,
|
|
2693
|
+
source: row.source,
|
|
2694
|
+
resourceId: row.resourceId,
|
|
2695
|
+
threadId: row.threadId,
|
|
2696
|
+
createdAt: row.createdAt,
|
|
2697
|
+
updatedAt: row.updatedAt
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
2700
|
+
async getScoreById({ id }) {
|
|
2701
|
+
const result = await this.client.execute({
|
|
2702
|
+
sql: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE id = ?`,
|
|
2703
|
+
args: [id]
|
|
2704
|
+
});
|
|
2705
|
+
return result.rows?.[0] ? this.transformScoreRow(result.rows[0]) : null;
|
|
2706
|
+
}
|
|
2707
|
+
async saveScore(score) {
|
|
2708
|
+
try {
|
|
2709
|
+
const id = crypto.randomUUID();
|
|
2710
|
+
await this.operations.insert({
|
|
2711
|
+
tableName: storage.TABLE_SCORERS,
|
|
2712
|
+
record: {
|
|
2713
|
+
id,
|
|
2714
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2715
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2716
|
+
...score
|
|
2717
|
+
}
|
|
2718
|
+
});
|
|
2719
|
+
const scoreFromDb = await this.getScoreById({ id });
|
|
2720
|
+
return { score: scoreFromDb };
|
|
2721
|
+
} catch (error$1) {
|
|
2722
|
+
throw new error.MastraError(
|
|
2723
|
+
{
|
|
2724
|
+
id: "LIBSQL_STORE_SAVE_SCORE_FAILED",
|
|
2725
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2726
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
2727
|
+
},
|
|
2728
|
+
error$1
|
|
2729
|
+
);
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
async getScoresByEntityId({
|
|
2733
|
+
entityId,
|
|
2734
|
+
entityType,
|
|
2735
|
+
pagination
|
|
2736
|
+
}) {
|
|
2737
|
+
try {
|
|
2738
|
+
const result = await this.client.execute({
|
|
2739
|
+
sql: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE entityId = ? AND entityType = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
|
|
2740
|
+
args: [entityId, entityType, pagination.perPage + 1, pagination.page * pagination.perPage]
|
|
2741
|
+
});
|
|
2742
|
+
return {
|
|
2743
|
+
scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
|
|
2744
|
+
pagination: {
|
|
2745
|
+
total: result.rows?.length ?? 0,
|
|
2746
|
+
page: pagination.page,
|
|
2747
|
+
perPage: pagination.perPage,
|
|
2748
|
+
hasMore: result.rows?.length > pagination.perPage
|
|
2749
|
+
}
|
|
2750
|
+
};
|
|
2751
|
+
} catch (error$1) {
|
|
2752
|
+
throw new error.MastraError(
|
|
2753
|
+
{
|
|
2754
|
+
id: "LIBSQL_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
|
|
2755
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2756
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
2757
|
+
},
|
|
2758
|
+
error$1
|
|
2759
|
+
);
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
};
|
|
2763
|
+
var TracesLibSQL = class extends storage.TracesStorage {
|
|
2764
|
+
client;
|
|
2765
|
+
operations;
|
|
2766
|
+
constructor({ client, operations }) {
|
|
2767
|
+
super();
|
|
2768
|
+
this.client = client;
|
|
2769
|
+
this.operations = operations;
|
|
2770
|
+
}
|
|
2771
|
+
async getTraces(args) {
|
|
2772
|
+
if (args.fromDate || args.toDate) {
|
|
2773
|
+
args.dateRange = {
|
|
2774
|
+
start: args.fromDate,
|
|
2775
|
+
end: args.toDate
|
|
2776
|
+
};
|
|
2777
|
+
}
|
|
2778
|
+
try {
|
|
2779
|
+
const result = await this.getTracesPaginated(args);
|
|
2780
|
+
return result.traces;
|
|
2781
|
+
} catch (error$1) {
|
|
2782
|
+
throw new error.MastraError(
|
|
2783
|
+
{
|
|
2784
|
+
id: "LIBSQL_STORE_GET_TRACES_FAILED",
|
|
2785
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2786
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
2787
|
+
},
|
|
2788
|
+
error$1
|
|
2789
|
+
);
|
|
1154
2790
|
}
|
|
1155
2791
|
}
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
page
|
|
1161
|
-
|
|
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 = [];
|
|
2792
|
+
async getTracesPaginated(args) {
|
|
2793
|
+
const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
|
|
2794
|
+
const fromDate = dateRange?.start;
|
|
2795
|
+
const toDate = dateRange?.end;
|
|
2796
|
+
const currentOffset = page * perPage;
|
|
2797
|
+
const queryArgs = [];
|
|
1173
2798
|
const conditions = [];
|
|
1174
2799
|
if (name) {
|
|
1175
|
-
conditions.push("name LIKE
|
|
2800
|
+
conditions.push("name LIKE ?");
|
|
2801
|
+
queryArgs.push(`${name}%`);
|
|
1176
2802
|
}
|
|
1177
2803
|
if (scope) {
|
|
1178
2804
|
conditions.push("scope = ?");
|
|
2805
|
+
queryArgs.push(scope);
|
|
1179
2806
|
}
|
|
1180
2807
|
if (attributes) {
|
|
1181
|
-
Object.
|
|
1182
|
-
conditions.push(`attributes
|
|
2808
|
+
Object.entries(attributes).forEach(([key, value]) => {
|
|
2809
|
+
conditions.push(`json_extract(attributes, '$.${key}') = ?`);
|
|
2810
|
+
queryArgs.push(value);
|
|
1183
2811
|
});
|
|
1184
2812
|
}
|
|
1185
2813
|
if (filters) {
|
|
1186
|
-
Object.entries(filters).forEach(([key,
|
|
1187
|
-
conditions.push(`${key} = ?`);
|
|
2814
|
+
Object.entries(filters).forEach(([key, value]) => {
|
|
2815
|
+
conditions.push(`${utils.parseSqlIdentifier(key, "filter key")} = ?`);
|
|
2816
|
+
queryArgs.push(value);
|
|
1188
2817
|
});
|
|
1189
2818
|
}
|
|
1190
2819
|
if (fromDate) {
|
|
1191
2820
|
conditions.push("createdAt >= ?");
|
|
2821
|
+
queryArgs.push(fromDate.toISOString());
|
|
1192
2822
|
}
|
|
1193
2823
|
if (toDate) {
|
|
1194
2824
|
conditions.push("createdAt <= ?");
|
|
2825
|
+
queryArgs.push(toDate.toISOString());
|
|
1195
2826
|
}
|
|
1196
2827
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1197
|
-
|
|
1198
|
-
|
|
2828
|
+
try {
|
|
2829
|
+
const countResult = await this.client.execute({
|
|
2830
|
+
sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_TRACES} ${whereClause}`,
|
|
2831
|
+
args: queryArgs
|
|
2832
|
+
});
|
|
2833
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
2834
|
+
if (total === 0) {
|
|
2835
|
+
return {
|
|
2836
|
+
traces: [],
|
|
2837
|
+
total: 0,
|
|
2838
|
+
page,
|
|
2839
|
+
perPage,
|
|
2840
|
+
hasMore: false
|
|
2841
|
+
};
|
|
2842
|
+
}
|
|
2843
|
+
const dataResult = await this.client.execute({
|
|
2844
|
+
sql: `SELECT * FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
|
|
2845
|
+
args: [...queryArgs, perPage, currentOffset]
|
|
2846
|
+
});
|
|
2847
|
+
const traces = dataResult.rows?.map(
|
|
2848
|
+
(row) => ({
|
|
2849
|
+
id: row.id,
|
|
2850
|
+
parentSpanId: row.parentSpanId,
|
|
2851
|
+
traceId: row.traceId,
|
|
2852
|
+
name: row.name,
|
|
2853
|
+
scope: row.scope,
|
|
2854
|
+
kind: row.kind,
|
|
2855
|
+
status: storage.safelyParseJSON(row.status),
|
|
2856
|
+
events: storage.safelyParseJSON(row.events),
|
|
2857
|
+
links: storage.safelyParseJSON(row.links),
|
|
2858
|
+
attributes: storage.safelyParseJSON(row.attributes),
|
|
2859
|
+
startTime: row.startTime,
|
|
2860
|
+
endTime: row.endTime,
|
|
2861
|
+
other: storage.safelyParseJSON(row.other),
|
|
2862
|
+
createdAt: row.createdAt
|
|
2863
|
+
})
|
|
2864
|
+
) ?? [];
|
|
2865
|
+
return {
|
|
2866
|
+
traces,
|
|
2867
|
+
total,
|
|
2868
|
+
page,
|
|
2869
|
+
perPage,
|
|
2870
|
+
hasMore: currentOffset + traces.length < total
|
|
2871
|
+
};
|
|
2872
|
+
} catch (error$1) {
|
|
2873
|
+
throw new error.MastraError(
|
|
2874
|
+
{
|
|
2875
|
+
id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
|
|
2876
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2877
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
2878
|
+
},
|
|
2879
|
+
error$1
|
|
2880
|
+
);
|
|
1199
2881
|
}
|
|
1200
|
-
|
|
1201
|
-
|
|
2882
|
+
}
|
|
2883
|
+
async batchTraceInsert({ records }) {
|
|
2884
|
+
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
2885
|
+
await this.operations.batchInsert({
|
|
2886
|
+
tableName: storage.TABLE_TRACES,
|
|
2887
|
+
records
|
|
2888
|
+
});
|
|
2889
|
+
}
|
|
2890
|
+
};
|
|
2891
|
+
function parseWorkflowRun(row) {
|
|
2892
|
+
let parsedSnapshot = row.snapshot;
|
|
2893
|
+
if (typeof parsedSnapshot === "string") {
|
|
2894
|
+
try {
|
|
2895
|
+
parsedSnapshot = JSON.parse(row.snapshot);
|
|
2896
|
+
} catch (e) {
|
|
2897
|
+
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
1202
2898
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
2899
|
+
}
|
|
2900
|
+
return {
|
|
2901
|
+
workflowName: row.workflow_name,
|
|
2902
|
+
runId: row.run_id,
|
|
2903
|
+
snapshot: parsedSnapshot,
|
|
2904
|
+
resourceId: row.resourceId,
|
|
2905
|
+
createdAt: new Date(row.createdAt),
|
|
2906
|
+
updatedAt: new Date(row.updatedAt)
|
|
2907
|
+
};
|
|
2908
|
+
}
|
|
2909
|
+
var WorkflowsLibSQL = class extends storage.WorkflowsStorage {
|
|
2910
|
+
operations;
|
|
2911
|
+
client;
|
|
2912
|
+
maxRetries;
|
|
2913
|
+
initialBackoffMs;
|
|
2914
|
+
constructor({
|
|
2915
|
+
operations,
|
|
2916
|
+
client,
|
|
2917
|
+
maxRetries = 5,
|
|
2918
|
+
initialBackoffMs = 500
|
|
2919
|
+
}) {
|
|
2920
|
+
super();
|
|
2921
|
+
this.operations = operations;
|
|
2922
|
+
this.client = client;
|
|
2923
|
+
this.maxRetries = maxRetries;
|
|
2924
|
+
this.initialBackoffMs = initialBackoffMs;
|
|
2925
|
+
this.setupPragmaSettings().catch(
|
|
2926
|
+
(err) => this.logger.warn("LibSQL Workflows: Failed to setup PRAGMA settings.", err)
|
|
2927
|
+
);
|
|
2928
|
+
}
|
|
2929
|
+
async setupPragmaSettings() {
|
|
2930
|
+
try {
|
|
2931
|
+
await this.client.execute("PRAGMA busy_timeout = 10000;");
|
|
2932
|
+
this.logger.debug("LibSQL Workflows: PRAGMA busy_timeout=10000 set.");
|
|
2933
|
+
try {
|
|
2934
|
+
await this.client.execute("PRAGMA journal_mode = WAL;");
|
|
2935
|
+
this.logger.debug("LibSQL Workflows: PRAGMA journal_mode=WAL set.");
|
|
2936
|
+
} catch {
|
|
2937
|
+
this.logger.debug("LibSQL Workflows: WAL mode not supported, using default journal mode.");
|
|
2938
|
+
}
|
|
2939
|
+
try {
|
|
2940
|
+
await this.client.execute("PRAGMA synchronous = NORMAL;");
|
|
2941
|
+
this.logger.debug("LibSQL Workflows: PRAGMA synchronous=NORMAL set.");
|
|
2942
|
+
} catch {
|
|
2943
|
+
this.logger.debug("LibSQL Workflows: Failed to set synchronous mode.");
|
|
1206
2944
|
}
|
|
2945
|
+
} catch (err) {
|
|
2946
|
+
this.logger.warn("LibSQL Workflows: Failed to set PRAGMA settings.", err);
|
|
1207
2947
|
}
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
2948
|
+
}
|
|
2949
|
+
async executeWithRetry(operation) {
|
|
2950
|
+
let attempts = 0;
|
|
2951
|
+
let backoff = this.initialBackoffMs;
|
|
2952
|
+
while (attempts < this.maxRetries) {
|
|
2953
|
+
try {
|
|
2954
|
+
return await operation();
|
|
2955
|
+
} catch (error) {
|
|
2956
|
+
this.logger.debug("LibSQL Workflows: Error caught in retry loop", {
|
|
2957
|
+
errorType: error.constructor.name,
|
|
2958
|
+
errorCode: error.code,
|
|
2959
|
+
errorMessage: error.message,
|
|
2960
|
+
attempts,
|
|
2961
|
+
maxRetries: this.maxRetries
|
|
2962
|
+
});
|
|
2963
|
+
const isLockError = error.code === "SQLITE_BUSY" || error.code === "SQLITE_LOCKED" || error.message?.toLowerCase().includes("database is locked") || error.message?.toLowerCase().includes("database table is locked") || error.message?.toLowerCase().includes("table is locked") || error.constructor.name === "SqliteError" && error.message?.toLowerCase().includes("locked");
|
|
2964
|
+
if (isLockError) {
|
|
2965
|
+
attempts++;
|
|
2966
|
+
if (attempts >= this.maxRetries) {
|
|
2967
|
+
this.logger.error(
|
|
2968
|
+
`LibSQL Workflows: Operation failed after ${this.maxRetries} attempts due to database lock: ${error.message}`,
|
|
2969
|
+
{ error, attempts, maxRetries: this.maxRetries }
|
|
2970
|
+
);
|
|
2971
|
+
throw error;
|
|
2972
|
+
}
|
|
2973
|
+
this.logger.warn(
|
|
2974
|
+
`LibSQL Workflows: Attempt ${attempts} failed due to database lock. Retrying in ${backoff}ms...`,
|
|
2975
|
+
{ errorMessage: error.message, attempts, backoff, maxRetries: this.maxRetries }
|
|
2976
|
+
);
|
|
2977
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
2978
|
+
backoff *= 2;
|
|
2979
|
+
} else {
|
|
2980
|
+
this.logger.error("LibSQL Workflows: Non-lock error occurred, not retrying", { error });
|
|
2981
|
+
throw error;
|
|
2982
|
+
}
|
|
1211
2983
|
}
|
|
1212
2984
|
}
|
|
1213
|
-
|
|
1214
|
-
|
|
2985
|
+
throw new Error("LibSQL Workflows: Max retries reached, but no error was re-thrown from the loop.");
|
|
2986
|
+
}
|
|
2987
|
+
async updateWorkflowResults({
|
|
2988
|
+
workflowName,
|
|
2989
|
+
runId,
|
|
2990
|
+
stepId,
|
|
2991
|
+
result,
|
|
2992
|
+
runtimeContext
|
|
2993
|
+
}) {
|
|
2994
|
+
return this.executeWithRetry(async () => {
|
|
2995
|
+
const tx = await this.client.transaction("write");
|
|
2996
|
+
try {
|
|
2997
|
+
const existingSnapshotResult = await tx.execute({
|
|
2998
|
+
sql: `SELECT snapshot FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} WHERE workflow_name = ? AND run_id = ?`,
|
|
2999
|
+
args: [workflowName, runId]
|
|
3000
|
+
});
|
|
3001
|
+
let snapshot;
|
|
3002
|
+
if (!existingSnapshotResult.rows?.[0]) {
|
|
3003
|
+
snapshot = {
|
|
3004
|
+
context: {},
|
|
3005
|
+
activePaths: [],
|
|
3006
|
+
timestamp: Date.now(),
|
|
3007
|
+
suspendedPaths: {},
|
|
3008
|
+
serializedStepGraph: [],
|
|
3009
|
+
value: {},
|
|
3010
|
+
waitingPaths: {},
|
|
3011
|
+
status: "pending",
|
|
3012
|
+
runId,
|
|
3013
|
+
runtimeContext: {}
|
|
3014
|
+
};
|
|
3015
|
+
} else {
|
|
3016
|
+
const existingSnapshot = existingSnapshotResult.rows[0].snapshot;
|
|
3017
|
+
snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
|
|
3018
|
+
}
|
|
3019
|
+
snapshot.context[stepId] = result;
|
|
3020
|
+
snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
|
|
3021
|
+
await tx.execute({
|
|
3022
|
+
sql: `UPDATE ${storage.TABLE_WORKFLOW_SNAPSHOT} SET snapshot = ? WHERE workflow_name = ? AND run_id = ?`,
|
|
3023
|
+
args: [JSON.stringify(snapshot), workflowName, runId]
|
|
3024
|
+
});
|
|
3025
|
+
await tx.commit();
|
|
3026
|
+
return snapshot.context;
|
|
3027
|
+
} catch (error) {
|
|
3028
|
+
if (!tx.closed) {
|
|
3029
|
+
await tx.rollback();
|
|
3030
|
+
}
|
|
3031
|
+
throw error;
|
|
3032
|
+
}
|
|
3033
|
+
});
|
|
3034
|
+
}
|
|
3035
|
+
async updateWorkflowState({
|
|
3036
|
+
workflowName,
|
|
3037
|
+
runId,
|
|
3038
|
+
opts
|
|
3039
|
+
}) {
|
|
3040
|
+
return this.executeWithRetry(async () => {
|
|
3041
|
+
const tx = await this.client.transaction("write");
|
|
3042
|
+
try {
|
|
3043
|
+
const existingSnapshotResult = await tx.execute({
|
|
3044
|
+
sql: `SELECT snapshot FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} WHERE workflow_name = ? AND run_id = ?`,
|
|
3045
|
+
args: [workflowName, runId]
|
|
3046
|
+
});
|
|
3047
|
+
if (!existingSnapshotResult.rows?.[0]) {
|
|
3048
|
+
await tx.rollback();
|
|
3049
|
+
return void 0;
|
|
3050
|
+
}
|
|
3051
|
+
const existingSnapshot = existingSnapshotResult.rows[0].snapshot;
|
|
3052
|
+
const snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
|
|
3053
|
+
if (!snapshot || !snapshot?.context) {
|
|
3054
|
+
await tx.rollback();
|
|
3055
|
+
throw new Error(`Snapshot not found for runId ${runId}`);
|
|
3056
|
+
}
|
|
3057
|
+
const updatedSnapshot = { ...snapshot, ...opts };
|
|
3058
|
+
await tx.execute({
|
|
3059
|
+
sql: `UPDATE ${storage.TABLE_WORKFLOW_SNAPSHOT} SET snapshot = ? WHERE workflow_name = ? AND run_id = ?`,
|
|
3060
|
+
args: [JSON.stringify(updatedSnapshot), workflowName, runId]
|
|
3061
|
+
});
|
|
3062
|
+
await tx.commit();
|
|
3063
|
+
return updatedSnapshot;
|
|
3064
|
+
} catch (error) {
|
|
3065
|
+
if (!tx.closed) {
|
|
3066
|
+
await tx.rollback();
|
|
3067
|
+
}
|
|
3068
|
+
throw error;
|
|
3069
|
+
}
|
|
3070
|
+
});
|
|
3071
|
+
}
|
|
3072
|
+
async persistWorkflowSnapshot({
|
|
3073
|
+
workflowName,
|
|
3074
|
+
runId,
|
|
3075
|
+
snapshot
|
|
3076
|
+
}) {
|
|
3077
|
+
const data = {
|
|
3078
|
+
workflow_name: workflowName,
|
|
3079
|
+
run_id: runId,
|
|
3080
|
+
snapshot,
|
|
3081
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
3082
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
3083
|
+
};
|
|
3084
|
+
this.logger.debug("Persisting workflow snapshot", { workflowName, runId, data });
|
|
3085
|
+
await this.operations.insert({
|
|
3086
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
3087
|
+
record: data
|
|
3088
|
+
});
|
|
3089
|
+
}
|
|
3090
|
+
async loadWorkflowSnapshot({
|
|
3091
|
+
workflowName,
|
|
3092
|
+
runId
|
|
3093
|
+
}) {
|
|
3094
|
+
this.logger.debug("Loading workflow snapshot", { workflowName, runId });
|
|
3095
|
+
const d = await this.operations.load({
|
|
3096
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
3097
|
+
keys: { workflow_name: workflowName, run_id: runId }
|
|
3098
|
+
});
|
|
3099
|
+
return d ? d.snapshot : null;
|
|
3100
|
+
}
|
|
3101
|
+
async getWorkflowRunById({
|
|
3102
|
+
runId,
|
|
3103
|
+
workflowName
|
|
3104
|
+
}) {
|
|
3105
|
+
const conditions = [];
|
|
3106
|
+
const args = [];
|
|
3107
|
+
if (runId) {
|
|
3108
|
+
conditions.push("run_id = ?");
|
|
3109
|
+
args.push(runId);
|
|
1215
3110
|
}
|
|
1216
|
-
if (
|
|
1217
|
-
|
|
3111
|
+
if (workflowName) {
|
|
3112
|
+
conditions.push("workflow_name = ?");
|
|
3113
|
+
args.push(workflowName);
|
|
1218
3114
|
}
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
3115
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
3116
|
+
try {
|
|
3117
|
+
const result = await this.client.execute({
|
|
3118
|
+
sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC LIMIT 1`,
|
|
3119
|
+
args
|
|
3120
|
+
});
|
|
3121
|
+
if (!result.rows?.[0]) {
|
|
3122
|
+
return null;
|
|
3123
|
+
}
|
|
3124
|
+
return parseWorkflowRun(result.rows[0]);
|
|
3125
|
+
} catch (error$1) {
|
|
3126
|
+
throw new error.MastraError(
|
|
3127
|
+
{
|
|
3128
|
+
id: "LIBSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
3129
|
+
domain: error.ErrorDomain.STORAGE,
|
|
3130
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
3131
|
+
},
|
|
3132
|
+
error$1
|
|
3133
|
+
);
|
|
1226
3134
|
}
|
|
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
3135
|
}
|
|
1244
3136
|
async getWorkflowRuns({
|
|
1245
3137
|
workflowName,
|
|
@@ -1265,7 +3157,7 @@ var LibSQLStore = class extends storage.MastraStorage {
|
|
|
1265
3157
|
args.push(toDate.toISOString());
|
|
1266
3158
|
}
|
|
1267
3159
|
if (resourceId) {
|
|
1268
|
-
const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
3160
|
+
const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
1269
3161
|
if (hasResourceId) {
|
|
1270
3162
|
conditions.push("resourceId = ?");
|
|
1271
3163
|
args.push(resourceId);
|
|
@@ -1286,60 +3178,291 @@ var LibSQLStore = class extends storage.MastraStorage {
|
|
|
1286
3178
|
sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${limit !== void 0 && offset !== void 0 ? ` LIMIT ? OFFSET ?` : ""}`,
|
|
1287
3179
|
args: limit !== void 0 && offset !== void 0 ? [...args, limit, offset] : args
|
|
1288
3180
|
});
|
|
1289
|
-
const runs = (result.rows || []).map((row) =>
|
|
3181
|
+
const runs = (result.rows || []).map((row) => parseWorkflowRun(row));
|
|
1290
3182
|
return { runs, total: total || runs.length };
|
|
1291
|
-
} catch (error) {
|
|
1292
|
-
|
|
1293
|
-
|
|
3183
|
+
} catch (error$1) {
|
|
3184
|
+
throw new error.MastraError(
|
|
3185
|
+
{
|
|
3186
|
+
id: "LIBSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
|
|
3187
|
+
domain: error.ErrorDomain.STORAGE,
|
|
3188
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
3189
|
+
},
|
|
3190
|
+
error$1
|
|
3191
|
+
);
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
};
|
|
3195
|
+
|
|
3196
|
+
// src/storage/index.ts
|
|
3197
|
+
var LibSQLStore = class extends storage.MastraStorage {
|
|
3198
|
+
client;
|
|
3199
|
+
maxRetries;
|
|
3200
|
+
initialBackoffMs;
|
|
3201
|
+
stores;
|
|
3202
|
+
constructor(config) {
|
|
3203
|
+
super({ name: `LibSQLStore` });
|
|
3204
|
+
this.maxRetries = config.maxRetries ?? 5;
|
|
3205
|
+
this.initialBackoffMs = config.initialBackoffMs ?? 100;
|
|
3206
|
+
if ("url" in config) {
|
|
3207
|
+
if (config.url.endsWith(":memory:")) {
|
|
3208
|
+
this.shouldCacheInit = false;
|
|
3209
|
+
}
|
|
3210
|
+
this.client = client.createClient({
|
|
3211
|
+
url: config.url,
|
|
3212
|
+
...config.authToken ? { authToken: config.authToken } : {}
|
|
3213
|
+
});
|
|
3214
|
+
if (config.url.startsWith("file:") || config.url.includes(":memory:")) {
|
|
3215
|
+
this.client.execute("PRAGMA journal_mode=WAL;").then(() => this.logger.debug("LibSQLStore: PRAGMA journal_mode=WAL set.")).catch((err) => this.logger.warn("LibSQLStore: Failed to set PRAGMA journal_mode=WAL.", err));
|
|
3216
|
+
this.client.execute("PRAGMA busy_timeout = 5000;").then(() => this.logger.debug("LibSQLStore: PRAGMA busy_timeout=5000 set.")).catch((err) => this.logger.warn("LibSQLStore: Failed to set PRAGMA busy_timeout.", err));
|
|
3217
|
+
}
|
|
3218
|
+
} else {
|
|
3219
|
+
this.client = config.client;
|
|
1294
3220
|
}
|
|
3221
|
+
const operations = new StoreOperationsLibSQL({
|
|
3222
|
+
client: this.client,
|
|
3223
|
+
maxRetries: this.maxRetries,
|
|
3224
|
+
initialBackoffMs: this.initialBackoffMs
|
|
3225
|
+
});
|
|
3226
|
+
const scores = new ScoresLibSQL({ client: this.client, operations });
|
|
3227
|
+
const traces = new TracesLibSQL({ client: this.client, operations });
|
|
3228
|
+
const workflows = new WorkflowsLibSQL({ client: this.client, operations });
|
|
3229
|
+
const memory = new MemoryLibSQL({ client: this.client, operations });
|
|
3230
|
+
const legacyEvals = new LegacyEvalsLibSQL({ client: this.client });
|
|
3231
|
+
const observability = new ObservabilityLibSQL({ operations });
|
|
3232
|
+
this.stores = {
|
|
3233
|
+
operations,
|
|
3234
|
+
scores,
|
|
3235
|
+
traces,
|
|
3236
|
+
workflows,
|
|
3237
|
+
memory,
|
|
3238
|
+
legacyEvals,
|
|
3239
|
+
observability
|
|
3240
|
+
};
|
|
3241
|
+
}
|
|
3242
|
+
get supports() {
|
|
3243
|
+
return {
|
|
3244
|
+
selectByIncludeResourceScope: true,
|
|
3245
|
+
resourceWorkingMemory: true,
|
|
3246
|
+
hasColumn: true,
|
|
3247
|
+
createTable: true,
|
|
3248
|
+
deleteMessages: true,
|
|
3249
|
+
aiTracing: true
|
|
3250
|
+
};
|
|
3251
|
+
}
|
|
3252
|
+
async createTable({
|
|
3253
|
+
tableName,
|
|
3254
|
+
schema
|
|
3255
|
+
}) {
|
|
3256
|
+
await this.stores.operations.createTable({ tableName, schema });
|
|
3257
|
+
}
|
|
3258
|
+
/**
|
|
3259
|
+
* Alters table schema to add columns if they don't exist
|
|
3260
|
+
* @param tableName Name of the table
|
|
3261
|
+
* @param schema Schema of the table
|
|
3262
|
+
* @param ifNotExists Array of column names to add if they don't exist
|
|
3263
|
+
*/
|
|
3264
|
+
async alterTable({
|
|
3265
|
+
tableName,
|
|
3266
|
+
schema,
|
|
3267
|
+
ifNotExists
|
|
3268
|
+
}) {
|
|
3269
|
+
await this.stores.operations.alterTable({ tableName, schema, ifNotExists });
|
|
3270
|
+
}
|
|
3271
|
+
async clearTable({ tableName }) {
|
|
3272
|
+
await this.stores.operations.clearTable({ tableName });
|
|
3273
|
+
}
|
|
3274
|
+
async dropTable({ tableName }) {
|
|
3275
|
+
await this.stores.operations.dropTable({ tableName });
|
|
3276
|
+
}
|
|
3277
|
+
insert(args) {
|
|
3278
|
+
return this.stores.operations.insert(args);
|
|
3279
|
+
}
|
|
3280
|
+
batchInsert(args) {
|
|
3281
|
+
return this.stores.operations.batchInsert(args);
|
|
3282
|
+
}
|
|
3283
|
+
async load({ tableName, keys }) {
|
|
3284
|
+
return this.stores.operations.load({ tableName, keys });
|
|
3285
|
+
}
|
|
3286
|
+
async getThreadById({ threadId }) {
|
|
3287
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
3288
|
+
}
|
|
3289
|
+
/**
|
|
3290
|
+
* @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
|
|
3291
|
+
*/
|
|
3292
|
+
async getThreadsByResourceId(args) {
|
|
3293
|
+
return this.stores.memory.getThreadsByResourceId(args);
|
|
3294
|
+
}
|
|
3295
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
3296
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
3297
|
+
}
|
|
3298
|
+
async saveThread({ thread }) {
|
|
3299
|
+
return this.stores.memory.saveThread({ thread });
|
|
3300
|
+
}
|
|
3301
|
+
async updateThread({
|
|
3302
|
+
id,
|
|
3303
|
+
title,
|
|
3304
|
+
metadata
|
|
3305
|
+
}) {
|
|
3306
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
3307
|
+
}
|
|
3308
|
+
async deleteThread({ threadId }) {
|
|
3309
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
3310
|
+
}
|
|
3311
|
+
async getMessages({
|
|
3312
|
+
threadId,
|
|
3313
|
+
selectBy,
|
|
3314
|
+
format
|
|
3315
|
+
}) {
|
|
3316
|
+
return this.stores.memory.getMessages({ threadId, selectBy, format });
|
|
3317
|
+
}
|
|
3318
|
+
async getMessagesById({
|
|
3319
|
+
messageIds,
|
|
3320
|
+
format
|
|
3321
|
+
}) {
|
|
3322
|
+
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
3323
|
+
}
|
|
3324
|
+
async getMessagesPaginated(args) {
|
|
3325
|
+
return this.stores.memory.getMessagesPaginated(args);
|
|
3326
|
+
}
|
|
3327
|
+
async saveMessages(args) {
|
|
3328
|
+
return this.stores.memory.saveMessages(args);
|
|
3329
|
+
}
|
|
3330
|
+
async updateMessages({
|
|
3331
|
+
messages
|
|
3332
|
+
}) {
|
|
3333
|
+
return this.stores.memory.updateMessages({ messages });
|
|
3334
|
+
}
|
|
3335
|
+
async deleteMessages(messageIds) {
|
|
3336
|
+
return this.stores.memory.deleteMessages(messageIds);
|
|
3337
|
+
}
|
|
3338
|
+
/** @deprecated use getEvals instead */
|
|
3339
|
+
async getEvalsByAgentName(agentName, type) {
|
|
3340
|
+
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
3341
|
+
}
|
|
3342
|
+
async getEvals(options = {}) {
|
|
3343
|
+
return this.stores.legacyEvals.getEvals(options);
|
|
3344
|
+
}
|
|
3345
|
+
async getScoreById({ id }) {
|
|
3346
|
+
return this.stores.scores.getScoreById({ id });
|
|
3347
|
+
}
|
|
3348
|
+
async saveScore(score) {
|
|
3349
|
+
return this.stores.scores.saveScore(score);
|
|
3350
|
+
}
|
|
3351
|
+
async getScoresByScorerId({
|
|
3352
|
+
scorerId,
|
|
3353
|
+
entityId,
|
|
3354
|
+
entityType,
|
|
3355
|
+
source,
|
|
3356
|
+
pagination
|
|
3357
|
+
}) {
|
|
3358
|
+
return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
|
|
3359
|
+
}
|
|
3360
|
+
async getScoresByRunId({
|
|
3361
|
+
runId,
|
|
3362
|
+
pagination
|
|
3363
|
+
}) {
|
|
3364
|
+
return this.stores.scores.getScoresByRunId({ runId, pagination });
|
|
3365
|
+
}
|
|
3366
|
+
async getScoresByEntityId({
|
|
3367
|
+
entityId,
|
|
3368
|
+
entityType,
|
|
3369
|
+
pagination
|
|
3370
|
+
}) {
|
|
3371
|
+
return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
|
|
3372
|
+
}
|
|
3373
|
+
/**
|
|
3374
|
+
* TRACES
|
|
3375
|
+
*/
|
|
3376
|
+
/**
|
|
3377
|
+
* @deprecated use getTracesPaginated instead.
|
|
3378
|
+
*/
|
|
3379
|
+
async getTraces(args) {
|
|
3380
|
+
return this.stores.traces.getTraces(args);
|
|
3381
|
+
}
|
|
3382
|
+
async getTracesPaginated(args) {
|
|
3383
|
+
return this.stores.traces.getTracesPaginated(args);
|
|
3384
|
+
}
|
|
3385
|
+
async batchTraceInsert(args) {
|
|
3386
|
+
return this.stores.traces.batchTraceInsert(args);
|
|
3387
|
+
}
|
|
3388
|
+
/**
|
|
3389
|
+
* WORKFLOWS
|
|
3390
|
+
*/
|
|
3391
|
+
async updateWorkflowResults({
|
|
3392
|
+
workflowName,
|
|
3393
|
+
runId,
|
|
3394
|
+
stepId,
|
|
3395
|
+
result,
|
|
3396
|
+
runtimeContext
|
|
3397
|
+
}) {
|
|
3398
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
|
|
3399
|
+
}
|
|
3400
|
+
async updateWorkflowState({
|
|
3401
|
+
workflowName,
|
|
3402
|
+
runId,
|
|
3403
|
+
opts
|
|
3404
|
+
}) {
|
|
3405
|
+
return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
|
|
3406
|
+
}
|
|
3407
|
+
async persistWorkflowSnapshot({
|
|
3408
|
+
workflowName,
|
|
3409
|
+
runId,
|
|
3410
|
+
snapshot
|
|
3411
|
+
}) {
|
|
3412
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
|
|
3413
|
+
}
|
|
3414
|
+
async loadWorkflowSnapshot({
|
|
3415
|
+
workflowName,
|
|
3416
|
+
runId
|
|
3417
|
+
}) {
|
|
3418
|
+
return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
|
|
3419
|
+
}
|
|
3420
|
+
async getWorkflowRuns({
|
|
3421
|
+
workflowName,
|
|
3422
|
+
fromDate,
|
|
3423
|
+
toDate,
|
|
3424
|
+
limit,
|
|
3425
|
+
offset,
|
|
3426
|
+
resourceId
|
|
3427
|
+
} = {}) {
|
|
3428
|
+
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
1295
3429
|
}
|
|
1296
3430
|
async getWorkflowRunById({
|
|
1297
3431
|
runId,
|
|
1298
3432
|
workflowName
|
|
1299
3433
|
}) {
|
|
1300
|
-
|
|
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]);
|
|
3434
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
1319
3435
|
}
|
|
1320
|
-
async
|
|
1321
|
-
|
|
1322
|
-
sql: `PRAGMA table_info(${table})`
|
|
1323
|
-
});
|
|
1324
|
-
return (await result.rows)?.some((row) => row.name === column);
|
|
3436
|
+
async getResourceById({ resourceId }) {
|
|
3437
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
1325
3438
|
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
3439
|
+
async saveResource({ resource }) {
|
|
3440
|
+
return this.stores.memory.saveResource({ resource });
|
|
3441
|
+
}
|
|
3442
|
+
async updateResource({
|
|
3443
|
+
resourceId,
|
|
3444
|
+
workingMemory,
|
|
3445
|
+
metadata
|
|
3446
|
+
}) {
|
|
3447
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
3448
|
+
}
|
|
3449
|
+
async createAISpan(span) {
|
|
3450
|
+
return this.stores.observability.createAISpan(span);
|
|
3451
|
+
}
|
|
3452
|
+
async updateAISpan(params) {
|
|
3453
|
+
return this.stores.observability.updateAISpan(params);
|
|
3454
|
+
}
|
|
3455
|
+
async getAITrace(traceId) {
|
|
3456
|
+
return this.stores.observability.getAITrace(traceId);
|
|
3457
|
+
}
|
|
3458
|
+
async getAITracesPaginated(args) {
|
|
3459
|
+
return this.stores.observability.getAITracesPaginated(args);
|
|
3460
|
+
}
|
|
3461
|
+
async batchCreateAISpans(args) {
|
|
3462
|
+
return this.stores.observability.batchCreateAISpans(args);
|
|
3463
|
+
}
|
|
3464
|
+
async batchUpdateAISpans(args) {
|
|
3465
|
+
return this.stores.observability.batchUpdateAISpans(args);
|
|
1343
3466
|
}
|
|
1344
3467
|
};
|
|
1345
3468
|
|
|
@@ -1446,3 +3569,5 @@ exports.DefaultStorage = LibSQLStore;
|
|
|
1446
3569
|
exports.LIBSQL_PROMPT = LIBSQL_PROMPT;
|
|
1447
3570
|
exports.LibSQLStore = LibSQLStore;
|
|
1448
3571
|
exports.LibSQLVector = LibSQLVector;
|
|
3572
|
+
//# sourceMappingURL=index.cjs.map
|
|
3573
|
+
//# sourceMappingURL=index.cjs.map
|