@mastra/cloudflare-d1 0.0.0-pg-pool-options-20250428183821 → 0.0.0-playground-studio-cloud-20251031080052
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 +1232 -0
- package/LICENSE.md +11 -42
- package/README.md +15 -0
- package/dist/index.cjs +2004 -570
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -5
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1981 -547
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +90 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +72 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +60 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +3 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +52 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +279 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/sql-builder.d.ts +128 -0
- package/dist/storage/sql-builder.d.ts.map +1 -0
- package/dist/storage/test-utils.d.ts +19 -0
- package/dist/storage/test-utils.d.ts.map +1 -0
- package/package.json +32 -17
- package/dist/_tsup-dts-rollup.d.cts +0 -313
- package/dist/_tsup-dts-rollup.d.ts +0 -313
- package/dist/index.d.cts +0 -5
package/dist/index.cjs
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var error = require('@mastra/core/error');
|
|
3
4
|
var storage = require('@mastra/core/storage');
|
|
4
5
|
var Cloudflare = require('cloudflare');
|
|
6
|
+
var utils = require('@mastra/core/utils');
|
|
7
|
+
var agent = require('@mastra/core/agent');
|
|
8
|
+
var scores = require('@mastra/core/scores');
|
|
5
9
|
|
|
6
10
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
7
11
|
|
|
8
12
|
var Cloudflare__default = /*#__PURE__*/_interopDefault(Cloudflare);
|
|
9
13
|
|
|
10
14
|
// src/storage/index.ts
|
|
11
|
-
|
|
12
|
-
// src/storage/sql-builder.ts
|
|
13
15
|
var SqlBuilder = class {
|
|
14
16
|
sql = "";
|
|
15
17
|
params = [];
|
|
@@ -19,12 +21,15 @@ var SqlBuilder = class {
|
|
|
19
21
|
if (!columns || Array.isArray(columns) && columns.length === 0) {
|
|
20
22
|
this.sql = "SELECT *";
|
|
21
23
|
} else {
|
|
22
|
-
|
|
24
|
+
const cols = Array.isArray(columns) ? columns : [columns];
|
|
25
|
+
const parsedCols = cols.map((col) => parseSelectIdentifier(col));
|
|
26
|
+
this.sql = `SELECT ${parsedCols.join(", ")}`;
|
|
23
27
|
}
|
|
24
28
|
return this;
|
|
25
29
|
}
|
|
26
30
|
from(table) {
|
|
27
|
-
|
|
31
|
+
const parsedTableName = utils.parseSqlIdentifier(table, "table name");
|
|
32
|
+
this.sql += ` FROM ${parsedTableName}`;
|
|
28
33
|
return this;
|
|
29
34
|
}
|
|
30
35
|
/**
|
|
@@ -61,7 +66,11 @@ var SqlBuilder = class {
|
|
|
61
66
|
return this;
|
|
62
67
|
}
|
|
63
68
|
orderBy(column, direction = "ASC") {
|
|
64
|
-
|
|
69
|
+
const parsedColumn = utils.parseSqlIdentifier(column, "column name");
|
|
70
|
+
if (!["ASC", "DESC"].includes(direction)) {
|
|
71
|
+
throw new Error(`Invalid sort direction: ${direction}`);
|
|
72
|
+
}
|
|
73
|
+
this.sql += ` ORDER BY ${parsedColumn} ${direction}`;
|
|
65
74
|
return this;
|
|
66
75
|
}
|
|
67
76
|
limit(count) {
|
|
@@ -74,6 +83,10 @@ var SqlBuilder = class {
|
|
|
74
83
|
this.params.push(count);
|
|
75
84
|
return this;
|
|
76
85
|
}
|
|
86
|
+
count() {
|
|
87
|
+
this.sql += "SELECT COUNT(*) AS count";
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
77
90
|
/**
|
|
78
91
|
* Insert a row, or update specific columns on conflict (upsert).
|
|
79
92
|
* @param table Table name
|
|
@@ -83,27 +96,33 @@ var SqlBuilder = class {
|
|
|
83
96
|
* @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
|
|
84
97
|
*/
|
|
85
98
|
insert(table, columns, values, conflictColumns, updateMap) {
|
|
86
|
-
const
|
|
99
|
+
const parsedTableName = utils.parseSqlIdentifier(table, "table name");
|
|
100
|
+
const parsedColumns = columns.map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
101
|
+
const placeholders = parsedColumns.map(() => "?").join(", ");
|
|
87
102
|
if (conflictColumns && updateMap) {
|
|
103
|
+
const parsedConflictColumns = conflictColumns.map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
88
104
|
const updateClause = Object.entries(updateMap).map(([col, expr]) => `${col} = ${expr}`).join(", ");
|
|
89
|
-
this.sql = `INSERT INTO ${
|
|
105
|
+
this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
|
|
90
106
|
this.params.push(...values);
|
|
91
107
|
return this;
|
|
92
108
|
}
|
|
93
|
-
this.sql = `INSERT INTO ${
|
|
109
|
+
this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
94
110
|
this.params.push(...values);
|
|
95
111
|
return this;
|
|
96
112
|
}
|
|
97
113
|
// Update operations
|
|
98
114
|
update(table, columns, values) {
|
|
99
|
-
const
|
|
100
|
-
|
|
115
|
+
const parsedTableName = utils.parseSqlIdentifier(table, "table name");
|
|
116
|
+
const parsedColumns = columns.map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
117
|
+
const setClause = parsedColumns.map((col) => `${col} = ?`).join(", ");
|
|
118
|
+
this.sql = `UPDATE ${parsedTableName} SET ${setClause}`;
|
|
101
119
|
this.params.push(...values);
|
|
102
120
|
return this;
|
|
103
121
|
}
|
|
104
122
|
// Delete operations
|
|
105
123
|
delete(table) {
|
|
106
|
-
|
|
124
|
+
const parsedTableName = utils.parseSqlIdentifier(table, "table name");
|
|
125
|
+
this.sql = `DELETE FROM ${parsedTableName}`;
|
|
107
126
|
return this;
|
|
108
127
|
}
|
|
109
128
|
/**
|
|
@@ -114,9 +133,16 @@ var SqlBuilder = class {
|
|
|
114
133
|
* @returns The builder instance
|
|
115
134
|
*/
|
|
116
135
|
createTable(table, columnDefinitions, tableConstraints) {
|
|
117
|
-
const
|
|
136
|
+
const parsedTableName = utils.parseSqlIdentifier(table, "table name");
|
|
137
|
+
const parsedColumnDefinitions = columnDefinitions.map((def) => {
|
|
138
|
+
const colName = def.split(/\s+/)[0];
|
|
139
|
+
if (!colName) throw new Error("Empty column name in definition");
|
|
140
|
+
utils.parseSqlIdentifier(colName, "column name");
|
|
141
|
+
return def;
|
|
142
|
+
});
|
|
143
|
+
const columns = parsedColumnDefinitions.join(", ");
|
|
118
144
|
const constraints = tableConstraints && tableConstraints.length > 0 ? ", " + tableConstraints.join(", ") : "";
|
|
119
|
-
this.sql = `CREATE TABLE IF NOT EXISTS ${
|
|
145
|
+
this.sql = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns}${constraints})`;
|
|
120
146
|
return this;
|
|
121
147
|
}
|
|
122
148
|
/**
|
|
@@ -139,13 +165,10 @@ var SqlBuilder = class {
|
|
|
139
165
|
* @returns The builder instance
|
|
140
166
|
*/
|
|
141
167
|
createIndex(indexName, tableName, columnName, indexType = "") {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
raw(sql, ...params) {
|
|
147
|
-
this.sql = sql;
|
|
148
|
-
this.params.push(...params);
|
|
168
|
+
const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
|
|
169
|
+
const parsedTableName = utils.parseSqlIdentifier(tableName, "table name");
|
|
170
|
+
const parsedColumnName = utils.parseSqlIdentifier(columnName, "column name");
|
|
171
|
+
this.sql = `CREATE ${indexType ? indexType + " " : ""}INDEX IF NOT EXISTS ${parsedIndexName} ON ${parsedTableName}(${parsedColumnName})`;
|
|
149
172
|
return this;
|
|
150
173
|
}
|
|
151
174
|
/**
|
|
@@ -155,11 +178,12 @@ var SqlBuilder = class {
|
|
|
155
178
|
* @param exact If true, will not add % wildcards
|
|
156
179
|
*/
|
|
157
180
|
like(column, value, exact = false) {
|
|
181
|
+
const parsedColumnName = utils.parseSqlIdentifier(column, "column name");
|
|
158
182
|
const likeValue = exact ? value : `%${value}%`;
|
|
159
183
|
if (this.whereAdded) {
|
|
160
|
-
this.sql += ` AND ${
|
|
184
|
+
this.sql += ` AND ${parsedColumnName} LIKE ?`;
|
|
161
185
|
} else {
|
|
162
|
-
this.sql += ` WHERE ${
|
|
186
|
+
this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
|
|
163
187
|
this.whereAdded = true;
|
|
164
188
|
}
|
|
165
189
|
this.params.push(likeValue);
|
|
@@ -172,11 +196,13 @@ var SqlBuilder = class {
|
|
|
172
196
|
* @param value The value to match
|
|
173
197
|
*/
|
|
174
198
|
jsonLike(column, key, value) {
|
|
175
|
-
const
|
|
199
|
+
const parsedColumnName = utils.parseSqlIdentifier(column, "column name");
|
|
200
|
+
const parsedKey = utils.parseSqlIdentifier(key, "key name");
|
|
201
|
+
const jsonPattern = `%"${parsedKey}":"${value}"%`;
|
|
176
202
|
if (this.whereAdded) {
|
|
177
|
-
this.sql += ` AND ${
|
|
203
|
+
this.sql += ` AND ${parsedColumnName} LIKE ?`;
|
|
178
204
|
} else {
|
|
179
|
-
this.sql += ` WHERE ${
|
|
205
|
+
this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
|
|
180
206
|
this.whereAdded = true;
|
|
181
207
|
}
|
|
182
208
|
this.params.push(jsonPattern);
|
|
@@ -206,331 +232,301 @@ var SqlBuilder = class {
|
|
|
206
232
|
function createSqlBuilder() {
|
|
207
233
|
return new SqlBuilder();
|
|
208
234
|
}
|
|
235
|
+
var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z0-9_]+(\s+AS\s+[a-zA-Z0-9_]+)?$/;
|
|
236
|
+
function parseSelectIdentifier(column) {
|
|
237
|
+
if (column !== "*" && !SQL_IDENTIFIER_PATTERN.test(column)) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
`Invalid column name: "${column}". Must be "*" or a valid identifier (letters, numbers, underscores), optionally with "AS alias".`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
return column;
|
|
243
|
+
}
|
|
209
244
|
|
|
210
|
-
// src/storage/
|
|
245
|
+
// src/storage/domains/utils.ts
|
|
211
246
|
function isArrayOfRecords(value) {
|
|
212
247
|
return value && Array.isArray(value) && value.length > 0;
|
|
213
248
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* Creates a new D1Store instance
|
|
223
|
-
* @param config Configuration for D1 access (either REST API or Workers Binding API)
|
|
224
|
-
*/
|
|
225
|
-
constructor(config) {
|
|
226
|
-
super({ name: "D1" });
|
|
227
|
-
this.tablePrefix = config.tablePrefix || "";
|
|
228
|
-
if ("binding" in config) {
|
|
229
|
-
if (!config.binding) {
|
|
230
|
-
throw new Error("D1 binding is required when using Workers Binding API");
|
|
231
|
-
}
|
|
232
|
-
this.binding = config.binding;
|
|
233
|
-
this.logger.info("Using D1 Workers Binding API");
|
|
234
|
-
} else {
|
|
235
|
-
if (!config.accountId || !config.databaseId || !config.apiToken) {
|
|
236
|
-
throw new Error("accountId, databaseId, and apiToken are required when using REST API");
|
|
237
|
-
}
|
|
238
|
-
this.accountId = config.accountId;
|
|
239
|
-
this.databaseId = config.databaseId;
|
|
240
|
-
this.client = new Cloudflare__default.default({
|
|
241
|
-
apiToken: config.apiToken
|
|
242
|
-
});
|
|
243
|
-
this.logger.info("Using D1 REST API");
|
|
249
|
+
function deserializeValue(value, type) {
|
|
250
|
+
if (value === null || value === void 0) return null;
|
|
251
|
+
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
252
|
+
try {
|
|
253
|
+
return JSON.parse(value);
|
|
254
|
+
} catch {
|
|
255
|
+
return value;
|
|
244
256
|
}
|
|
245
257
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
258
|
+
return value;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/storage/domains/legacy-evals/index.ts
|
|
262
|
+
var LegacyEvalsStorageD1 = class extends storage.LegacyEvalsStorage {
|
|
263
|
+
operations;
|
|
264
|
+
constructor({ operations }) {
|
|
265
|
+
super();
|
|
266
|
+
this.operations = operations;
|
|
252
267
|
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
const fullTableName = this.getTableName(
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
sql: checkSql,
|
|
262
|
-
params: checkParams,
|
|
263
|
-
first: true
|
|
264
|
-
});
|
|
265
|
-
if (!indexExists) {
|
|
266
|
-
const createQuery = createSqlBuilder().createIndex(indexName, fullTableName, columnName, indexType);
|
|
267
|
-
const { sql: createSql, params: createParams } = createQuery.build();
|
|
268
|
-
await this.executeQuery({ sql: createSql, params: createParams });
|
|
269
|
-
this.logger.debug(`Created index ${indexName} on ${fullTableName}(${columnName})`);
|
|
270
|
-
}
|
|
271
|
-
} catch (error) {
|
|
272
|
-
this.logger.error(`Error creating index on ${fullTableName}(${columnName}):`, {
|
|
273
|
-
message: error instanceof Error ? error.message : String(error)
|
|
274
|
-
});
|
|
268
|
+
async getEvals(options) {
|
|
269
|
+
const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
|
|
270
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
|
|
271
|
+
const conditions = [];
|
|
272
|
+
const queryParams = [];
|
|
273
|
+
if (agentName) {
|
|
274
|
+
conditions.push(`agent_name = ?`);
|
|
275
|
+
queryParams.push(agentName);
|
|
275
276
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
first = false
|
|
281
|
-
}) {
|
|
282
|
-
if (!this.binding) {
|
|
283
|
-
throw new Error("Workers binding is not configured");
|
|
277
|
+
if (type === "test") {
|
|
278
|
+
conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
|
|
279
|
+
} else if (type === "live") {
|
|
280
|
+
conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
|
|
284
281
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
let result;
|
|
289
|
-
if (formattedParams.length > 0) {
|
|
290
|
-
if (first) {
|
|
291
|
-
result = await statement.bind(...formattedParams).first();
|
|
292
|
-
if (!result) return null;
|
|
293
|
-
return result;
|
|
294
|
-
} else {
|
|
295
|
-
result = await statement.bind(...formattedParams).all();
|
|
296
|
-
const results = result.results || [];
|
|
297
|
-
if (result.meta) {
|
|
298
|
-
this.logger.debug("Query metadata", { meta: result.meta });
|
|
299
|
-
}
|
|
300
|
-
return results;
|
|
301
|
-
}
|
|
302
|
-
} else {
|
|
303
|
-
if (first) {
|
|
304
|
-
result = await statement.first();
|
|
305
|
-
if (!result) return null;
|
|
306
|
-
return result;
|
|
307
|
-
} else {
|
|
308
|
-
result = await statement.all();
|
|
309
|
-
const results = result.results || [];
|
|
310
|
-
if (result.meta) {
|
|
311
|
-
this.logger.debug("Query metadata", { meta: result.meta });
|
|
312
|
-
}
|
|
313
|
-
return results;
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
} catch (workerError) {
|
|
317
|
-
this.logger.error("Workers Binding API error", {
|
|
318
|
-
message: workerError instanceof Error ? workerError.message : String(workerError),
|
|
319
|
-
sql
|
|
320
|
-
});
|
|
321
|
-
throw new Error(`D1 Workers API error: ${workerError.message}`);
|
|
282
|
+
if (dateRange?.start) {
|
|
283
|
+
conditions.push(`created_at >= ?`);
|
|
284
|
+
queryParams.push(storage.serializeDate(dateRange.start));
|
|
322
285
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
throw new Error("Missing required REST API configuration");
|
|
286
|
+
if (dateRange?.end) {
|
|
287
|
+
conditions.push(`created_at <= ?`);
|
|
288
|
+
queryParams.push(storage.serializeDate(dateRange.end));
|
|
289
|
+
}
|
|
290
|
+
const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
|
|
291
|
+
if (conditions.length > 0) {
|
|
292
|
+
countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
331
293
|
}
|
|
294
|
+
const { sql: countSql, params: countParams } = countQueryBuilder.build();
|
|
332
295
|
try {
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
296
|
+
const countResult = await this.operations.executeQuery({
|
|
297
|
+
sql: countSql,
|
|
298
|
+
params: countParams,
|
|
299
|
+
first: true
|
|
337
300
|
});
|
|
338
|
-
const
|
|
339
|
-
const
|
|
340
|
-
if (
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
301
|
+
const total = Number(countResult?.count || 0);
|
|
302
|
+
const currentOffset = page * perPage;
|
|
303
|
+
if (total === 0) {
|
|
304
|
+
return {
|
|
305
|
+
evals: [],
|
|
306
|
+
total: 0,
|
|
307
|
+
page,
|
|
308
|
+
perPage,
|
|
309
|
+
hasMore: false
|
|
310
|
+
};
|
|
344
311
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
312
|
+
const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
|
|
313
|
+
if (conditions.length > 0) {
|
|
314
|
+
dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
315
|
+
}
|
|
316
|
+
dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
|
|
317
|
+
const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
|
|
318
|
+
const rows = await this.operations.executeQuery({
|
|
319
|
+
sql: dataSql,
|
|
320
|
+
params: dataParams
|
|
321
|
+
});
|
|
322
|
+
const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
|
|
323
|
+
const result = deserializeValue(row.result);
|
|
324
|
+
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
325
|
+
if (!result || typeof result !== "object" || !("score" in result)) {
|
|
326
|
+
throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
input: row.input,
|
|
330
|
+
output: row.output,
|
|
331
|
+
result,
|
|
332
|
+
agentName: row.agent_name,
|
|
333
|
+
metricName: row.metric_name,
|
|
334
|
+
instructions: row.instructions,
|
|
335
|
+
testInfo,
|
|
336
|
+
globalRunId: row.global_run_id,
|
|
337
|
+
runId: row.run_id,
|
|
338
|
+
createdAt: row.created_at
|
|
339
|
+
};
|
|
350
340
|
});
|
|
351
|
-
|
|
341
|
+
const hasMore = currentOffset + evals.length < total;
|
|
342
|
+
return {
|
|
343
|
+
evals,
|
|
344
|
+
total,
|
|
345
|
+
page,
|
|
346
|
+
perPage,
|
|
347
|
+
hasMore
|
|
348
|
+
};
|
|
349
|
+
} catch (error$1) {
|
|
350
|
+
throw new error.MastraError(
|
|
351
|
+
{
|
|
352
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
353
|
+
domain: error.ErrorDomain.STORAGE,
|
|
354
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
355
|
+
text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
356
|
+
details: { agentName: agentName ?? "", type: type ?? "" }
|
|
357
|
+
},
|
|
358
|
+
error$1
|
|
359
|
+
);
|
|
352
360
|
}
|
|
353
361
|
}
|
|
354
362
|
/**
|
|
355
|
-
*
|
|
356
|
-
* @param options Query options including SQL, parameters, and whether to return only the first result
|
|
357
|
-
* @returns Query results as an array or a single object if first=true
|
|
363
|
+
* @deprecated use getEvals instead
|
|
358
364
|
*/
|
|
359
|
-
async
|
|
360
|
-
const
|
|
365
|
+
async getEvalsByAgentName(agentName, type) {
|
|
366
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
|
|
361
367
|
try {
|
|
362
|
-
|
|
363
|
-
if (
|
|
364
|
-
|
|
365
|
-
} else if (
|
|
366
|
-
|
|
367
|
-
} else {
|
|
368
|
-
throw new Error("No valid D1 configuration provided");
|
|
368
|
+
let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
|
|
369
|
+
if (type === "test") {
|
|
370
|
+
query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
|
|
371
|
+
} else if (type === "live") {
|
|
372
|
+
query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
|
|
369
373
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
serializeDate(date) {
|
|
404
|
-
if (!date) return void 0;
|
|
405
|
-
const dateObj = this.ensureDate(date);
|
|
406
|
-
return dateObj?.toISOString();
|
|
407
|
-
}
|
|
408
|
-
// Helper to serialize objects to JSON strings
|
|
409
|
-
serializeValue(value) {
|
|
410
|
-
if (value === null || value === void 0) return null;
|
|
411
|
-
if (value instanceof Date) {
|
|
412
|
-
return this.serializeDate(value);
|
|
413
|
-
}
|
|
414
|
-
if (typeof value === "object") {
|
|
415
|
-
return JSON.stringify(value);
|
|
374
|
+
query.orderBy("created_at", "DESC");
|
|
375
|
+
const { sql, params } = query.build();
|
|
376
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
377
|
+
return isArrayOfRecords(results) ? results.map((row) => {
|
|
378
|
+
const result = deserializeValue(row.result);
|
|
379
|
+
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
380
|
+
return {
|
|
381
|
+
input: row.input || "",
|
|
382
|
+
output: row.output || "",
|
|
383
|
+
result,
|
|
384
|
+
agentName: row.agent_name || "",
|
|
385
|
+
metricName: row.metric_name || "",
|
|
386
|
+
instructions: row.instructions || "",
|
|
387
|
+
runId: row.run_id || "",
|
|
388
|
+
globalRunId: row.global_run_id || "",
|
|
389
|
+
createdAt: row.created_at || "",
|
|
390
|
+
testInfo
|
|
391
|
+
};
|
|
392
|
+
}) : [];
|
|
393
|
+
} catch (error$1) {
|
|
394
|
+
const mastraError = new error.MastraError(
|
|
395
|
+
{
|
|
396
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
397
|
+
domain: error.ErrorDomain.STORAGE,
|
|
398
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
399
|
+
text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
400
|
+
details: { agentName }
|
|
401
|
+
},
|
|
402
|
+
error$1
|
|
403
|
+
);
|
|
404
|
+
this.logger?.error(mastraError.toString());
|
|
405
|
+
this.logger?.trackException(mastraError);
|
|
406
|
+
return [];
|
|
416
407
|
}
|
|
417
|
-
return value;
|
|
418
408
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
if (type === "jsonb" && typeof value === "string") {
|
|
426
|
-
try {
|
|
427
|
-
return JSON.parse(value);
|
|
428
|
-
} catch {
|
|
429
|
-
return value;
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
433
|
-
try {
|
|
434
|
-
return JSON.parse(value);
|
|
435
|
-
} catch {
|
|
436
|
-
return value;
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
return value;
|
|
409
|
+
};
|
|
410
|
+
var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
411
|
+
operations;
|
|
412
|
+
constructor({ operations }) {
|
|
413
|
+
super();
|
|
414
|
+
this.operations = operations;
|
|
440
415
|
}
|
|
441
|
-
async
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
const fullTableName = this.getTableName(tableName);
|
|
446
|
-
const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
|
|
447
|
-
const type = this.getSqlType(colDef.type);
|
|
448
|
-
const nullable = colDef.nullable === false ? "NOT NULL" : "";
|
|
449
|
-
const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
|
|
450
|
-
return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
|
|
416
|
+
async getResourceById({ resourceId }) {
|
|
417
|
+
const resource = await this.operations.load({
|
|
418
|
+
tableName: storage.TABLE_RESOURCES,
|
|
419
|
+
keys: { id: resourceId }
|
|
451
420
|
});
|
|
452
|
-
|
|
453
|
-
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
454
|
-
tableConstraints.push("UNIQUE (workflow_name, run_id)");
|
|
455
|
-
}
|
|
456
|
-
const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
|
|
457
|
-
const { sql, params } = query.build();
|
|
458
|
-
try {
|
|
459
|
-
await this.executeQuery({ sql, params });
|
|
460
|
-
this.logger.debug(`Created table ${fullTableName}`);
|
|
461
|
-
} catch (error) {
|
|
462
|
-
this.logger.error(`Error creating table ${fullTableName}:`, {
|
|
463
|
-
message: error instanceof Error ? error.message : String(error)
|
|
464
|
-
});
|
|
465
|
-
throw new Error(`Failed to create table ${fullTableName}: ${error}`);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
async clearTable({ tableName }) {
|
|
469
|
-
const fullTableName = this.getTableName(tableName);
|
|
421
|
+
if (!resource) return null;
|
|
470
422
|
try {
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
423
|
+
return {
|
|
424
|
+
...resource,
|
|
425
|
+
createdAt: storage.ensureDate(resource.createdAt),
|
|
426
|
+
updatedAt: storage.ensureDate(resource.updatedAt),
|
|
427
|
+
metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
|
|
428
|
+
};
|
|
429
|
+
} catch (error$1) {
|
|
430
|
+
const mastraError = new error.MastraError(
|
|
431
|
+
{
|
|
432
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
|
|
433
|
+
domain: error.ErrorDomain.STORAGE,
|
|
434
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
435
|
+
text: `Error processing resource ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
436
|
+
details: { resourceId }
|
|
437
|
+
},
|
|
438
|
+
error$1
|
|
439
|
+
);
|
|
440
|
+
this.logger?.error(mastraError.toString());
|
|
441
|
+
this.logger?.trackException(mastraError);
|
|
442
|
+
return null;
|
|
486
443
|
}
|
|
487
|
-
return processedRecord;
|
|
488
444
|
}
|
|
489
|
-
async
|
|
490
|
-
const fullTableName = this.getTableName(
|
|
491
|
-
const
|
|
445
|
+
async saveResource({ resource }) {
|
|
446
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_RESOURCES);
|
|
447
|
+
const resourceToSave = {
|
|
448
|
+
id: resource.id,
|
|
449
|
+
workingMemory: resource.workingMemory,
|
|
450
|
+
metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
|
|
451
|
+
createdAt: resource.createdAt,
|
|
452
|
+
updatedAt: resource.updatedAt
|
|
453
|
+
};
|
|
454
|
+
const processedRecord = await this.operations.processRecord(resourceToSave);
|
|
492
455
|
const columns = Object.keys(processedRecord);
|
|
493
456
|
const values = Object.values(processedRecord);
|
|
494
|
-
const
|
|
457
|
+
const updateMap = {
|
|
458
|
+
workingMemory: "excluded.workingMemory",
|
|
459
|
+
metadata: "excluded.metadata",
|
|
460
|
+
createdAt: "excluded.createdAt",
|
|
461
|
+
updatedAt: "excluded.updatedAt"
|
|
462
|
+
};
|
|
463
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
|
|
495
464
|
const { sql, params } = query.build();
|
|
496
465
|
try {
|
|
497
|
-
await this.executeQuery({ sql, params });
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
throw new
|
|
466
|
+
await this.operations.executeQuery({ sql, params });
|
|
467
|
+
return resource;
|
|
468
|
+
} catch (error$1) {
|
|
469
|
+
throw new error.MastraError(
|
|
470
|
+
{
|
|
471
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
|
|
472
|
+
domain: error.ErrorDomain.STORAGE,
|
|
473
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
474
|
+
text: `Failed to save resource to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
475
|
+
details: { resourceId: resource.id }
|
|
476
|
+
},
|
|
477
|
+
error$1
|
|
478
|
+
);
|
|
501
479
|
}
|
|
502
480
|
}
|
|
503
|
-
async
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
481
|
+
async updateResource({
|
|
482
|
+
resourceId,
|
|
483
|
+
workingMemory,
|
|
484
|
+
metadata
|
|
485
|
+
}) {
|
|
486
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
487
|
+
if (!existingResource) {
|
|
488
|
+
const newResource = {
|
|
489
|
+
id: resourceId,
|
|
490
|
+
workingMemory,
|
|
491
|
+
metadata: metadata || {},
|
|
492
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
493
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
494
|
+
};
|
|
495
|
+
return this.saveResource({ resource: newResource });
|
|
514
496
|
}
|
|
515
|
-
|
|
497
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
498
|
+
const updatedResource = {
|
|
499
|
+
...existingResource,
|
|
500
|
+
workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
|
|
501
|
+
metadata: {
|
|
502
|
+
...existingResource.metadata,
|
|
503
|
+
...metadata
|
|
504
|
+
},
|
|
505
|
+
updatedAt
|
|
506
|
+
};
|
|
507
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_RESOURCES);
|
|
508
|
+
const columns = ["workingMemory", "metadata", "updatedAt"];
|
|
509
|
+
const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
|
|
510
|
+
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
|
|
516
511
|
const { sql, params } = query.build();
|
|
517
512
|
try {
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
513
|
+
await this.operations.executeQuery({ sql, params });
|
|
514
|
+
return updatedResource;
|
|
515
|
+
} catch (error$1) {
|
|
516
|
+
throw new error.MastraError(
|
|
517
|
+
{
|
|
518
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
|
|
519
|
+
domain: error.ErrorDomain.STORAGE,
|
|
520
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
521
|
+
text: `Failed to update resource ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
522
|
+
details: { resourceId }
|
|
523
|
+
},
|
|
524
|
+
error$1
|
|
525
|
+
);
|
|
530
526
|
}
|
|
531
527
|
}
|
|
532
528
|
async getThreadById({ threadId }) {
|
|
533
|
-
const thread = await this.load({
|
|
529
|
+
const thread = await this.operations.load({
|
|
534
530
|
tableName: storage.TABLE_THREADS,
|
|
535
531
|
keys: { id: threadId }
|
|
536
532
|
});
|
|
@@ -538,47 +534,113 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
538
534
|
try {
|
|
539
535
|
return {
|
|
540
536
|
...thread,
|
|
541
|
-
createdAt:
|
|
542
|
-
updatedAt:
|
|
537
|
+
createdAt: storage.ensureDate(thread.createdAt),
|
|
538
|
+
updatedAt: storage.ensureDate(thread.updatedAt),
|
|
543
539
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
544
540
|
};
|
|
545
|
-
} catch (error) {
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
541
|
+
} catch (error$1) {
|
|
542
|
+
const mastraError = new error.MastraError(
|
|
543
|
+
{
|
|
544
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
|
|
545
|
+
domain: error.ErrorDomain.STORAGE,
|
|
546
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
547
|
+
text: `Error processing thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
548
|
+
details: { threadId }
|
|
549
|
+
},
|
|
550
|
+
error$1
|
|
551
|
+
);
|
|
552
|
+
this.logger?.error(mastraError.toString());
|
|
553
|
+
this.logger?.trackException(mastraError);
|
|
549
554
|
return null;
|
|
550
555
|
}
|
|
551
556
|
}
|
|
557
|
+
/**
|
|
558
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
559
|
+
*/
|
|
552
560
|
async getThreadsByResourceId({ resourceId }) {
|
|
553
|
-
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
561
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
554
562
|
try {
|
|
555
563
|
const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
|
|
556
564
|
const { sql, params } = query.build();
|
|
557
|
-
const results = await this.executeQuery({ sql, params });
|
|
565
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
558
566
|
return (isArrayOfRecords(results) ? results : []).map((thread) => ({
|
|
559
567
|
...thread,
|
|
560
|
-
createdAt:
|
|
561
|
-
updatedAt:
|
|
568
|
+
createdAt: storage.ensureDate(thread.createdAt),
|
|
569
|
+
updatedAt: storage.ensureDate(thread.updatedAt),
|
|
562
570
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
563
571
|
}));
|
|
564
|
-
} catch (error) {
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
572
|
+
} catch (error$1) {
|
|
573
|
+
const mastraError = new error.MastraError(
|
|
574
|
+
{
|
|
575
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
|
|
576
|
+
domain: error.ErrorDomain.STORAGE,
|
|
577
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
578
|
+
text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
579
|
+
details: { resourceId }
|
|
580
|
+
},
|
|
581
|
+
error$1
|
|
582
|
+
);
|
|
583
|
+
this.logger?.error(mastraError.toString());
|
|
584
|
+
this.logger?.trackException(mastraError);
|
|
568
585
|
return [];
|
|
569
586
|
}
|
|
570
587
|
}
|
|
588
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
589
|
+
const { resourceId, page, perPage } = args;
|
|
590
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
591
|
+
const mapRowToStorageThreadType = (row) => ({
|
|
592
|
+
...row,
|
|
593
|
+
createdAt: storage.ensureDate(row.createdAt),
|
|
594
|
+
updatedAt: storage.ensureDate(row.updatedAt),
|
|
595
|
+
metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
|
|
596
|
+
});
|
|
597
|
+
try {
|
|
598
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
|
|
599
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
600
|
+
const total = Number(countResult?.[0]?.count ?? 0);
|
|
601
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
|
|
602
|
+
const results = await this.operations.executeQuery(selectQuery.build());
|
|
603
|
+
const threads = results.map(mapRowToStorageThreadType);
|
|
604
|
+
return {
|
|
605
|
+
threads,
|
|
606
|
+
total,
|
|
607
|
+
page,
|
|
608
|
+
perPage,
|
|
609
|
+
hasMore: page * perPage + threads.length < total
|
|
610
|
+
};
|
|
611
|
+
} catch (error$1) {
|
|
612
|
+
const mastraError = new error.MastraError(
|
|
613
|
+
{
|
|
614
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
|
|
615
|
+
domain: error.ErrorDomain.STORAGE,
|
|
616
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
617
|
+
text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
618
|
+
details: { resourceId }
|
|
619
|
+
},
|
|
620
|
+
error$1
|
|
621
|
+
);
|
|
622
|
+
this.logger?.error(mastraError.toString());
|
|
623
|
+
this.logger?.trackException(mastraError);
|
|
624
|
+
return {
|
|
625
|
+
threads: [],
|
|
626
|
+
total: 0,
|
|
627
|
+
page,
|
|
628
|
+
perPage,
|
|
629
|
+
hasMore: false
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
}
|
|
571
633
|
async saveThread({ thread }) {
|
|
572
|
-
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
634
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
573
635
|
const threadToSave = {
|
|
574
636
|
id: thread.id,
|
|
575
637
|
resourceId: thread.resourceId,
|
|
576
638
|
title: thread.title,
|
|
577
639
|
metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
|
|
578
|
-
createdAt: thread.createdAt,
|
|
579
|
-
updatedAt: thread.updatedAt
|
|
640
|
+
createdAt: thread.createdAt.toISOString(),
|
|
641
|
+
updatedAt: thread.updatedAt.toISOString()
|
|
580
642
|
};
|
|
581
|
-
const processedRecord = await this.processRecord(threadToSave);
|
|
643
|
+
const processedRecord = await this.operations.processRecord(threadToSave);
|
|
582
644
|
const columns = Object.keys(processedRecord);
|
|
583
645
|
const values = Object.values(processedRecord);
|
|
584
646
|
const updateMap = {
|
|
@@ -591,11 +653,19 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
591
653
|
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
|
|
592
654
|
const { sql, params } = query.build();
|
|
593
655
|
try {
|
|
594
|
-
await this.executeQuery({ sql, params });
|
|
656
|
+
await this.operations.executeQuery({ sql, params });
|
|
595
657
|
return thread;
|
|
596
|
-
} catch (error) {
|
|
597
|
-
|
|
598
|
-
|
|
658
|
+
} catch (error$1) {
|
|
659
|
+
throw new error.MastraError(
|
|
660
|
+
{
|
|
661
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
|
|
662
|
+
domain: error.ErrorDomain.STORAGE,
|
|
663
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
664
|
+
text: `Failed to save thread to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
665
|
+
details: { threadId: thread.id }
|
|
666
|
+
},
|
|
667
|
+
error$1
|
|
668
|
+
);
|
|
599
669
|
}
|
|
600
670
|
}
|
|
601
671
|
async updateThread({
|
|
@@ -604,20 +674,21 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
604
674
|
metadata
|
|
605
675
|
}) {
|
|
606
676
|
const thread = await this.getThreadById({ threadId: id });
|
|
607
|
-
if (!thread) {
|
|
608
|
-
throw new Error(`Thread ${id} not found`);
|
|
609
|
-
}
|
|
610
|
-
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
611
|
-
const mergedMetadata = {
|
|
612
|
-
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
613
|
-
...metadata
|
|
614
|
-
};
|
|
615
|
-
const columns = ["title", "metadata", "updatedAt"];
|
|
616
|
-
const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
|
|
617
|
-
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
|
|
618
|
-
const { sql, params } = query.build();
|
|
619
677
|
try {
|
|
620
|
-
|
|
678
|
+
if (!thread) {
|
|
679
|
+
throw new Error(`Thread ${id} not found`);
|
|
680
|
+
}
|
|
681
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
682
|
+
const mergedMetadata = {
|
|
683
|
+
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
684
|
+
...metadata
|
|
685
|
+
};
|
|
686
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
687
|
+
const columns = ["title", "metadata", "updatedAt"];
|
|
688
|
+
const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
|
|
689
|
+
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
|
|
690
|
+
const { sql, params } = query.build();
|
|
691
|
+
await this.operations.executeQuery({ sql, params });
|
|
621
692
|
return {
|
|
622
693
|
...thread,
|
|
623
694
|
title,
|
|
@@ -625,42 +696,66 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
625
696
|
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
626
697
|
...metadata
|
|
627
698
|
},
|
|
628
|
-
updatedAt
|
|
699
|
+
updatedAt
|
|
629
700
|
};
|
|
630
|
-
} catch (error) {
|
|
631
|
-
|
|
632
|
-
|
|
701
|
+
} catch (error$1) {
|
|
702
|
+
throw new error.MastraError(
|
|
703
|
+
{
|
|
704
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
|
|
705
|
+
domain: error.ErrorDomain.STORAGE,
|
|
706
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
707
|
+
text: `Failed to update thread ${id}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
708
|
+
details: { threadId: id }
|
|
709
|
+
},
|
|
710
|
+
error$1
|
|
711
|
+
);
|
|
633
712
|
}
|
|
634
713
|
}
|
|
635
714
|
async deleteThread({ threadId }) {
|
|
636
|
-
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
715
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
637
716
|
try {
|
|
638
717
|
const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
|
|
639
718
|
const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
|
|
640
|
-
await this.executeQuery({ sql: threadSql, params: threadParams });
|
|
641
|
-
const messagesTableName = this.getTableName(storage.TABLE_MESSAGES);
|
|
719
|
+
await this.operations.executeQuery({ sql: threadSql, params: threadParams });
|
|
720
|
+
const messagesTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
642
721
|
const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
|
|
643
722
|
const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
|
|
644
|
-
await this.executeQuery({ sql: messagesSql, params: messagesParams });
|
|
645
|
-
} catch (error) {
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
723
|
+
await this.operations.executeQuery({ sql: messagesSql, params: messagesParams });
|
|
724
|
+
} catch (error$1) {
|
|
725
|
+
throw new error.MastraError(
|
|
726
|
+
{
|
|
727
|
+
id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
|
|
728
|
+
domain: error.ErrorDomain.STORAGE,
|
|
729
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
730
|
+
text: `Failed to delete thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
731
|
+
details: { threadId }
|
|
732
|
+
},
|
|
733
|
+
error$1
|
|
734
|
+
);
|
|
650
735
|
}
|
|
651
736
|
}
|
|
652
|
-
|
|
653
|
-
|
|
737
|
+
async saveMessages(args) {
|
|
738
|
+
const { messages, format = "v1" } = args;
|
|
654
739
|
if (messages.length === 0) return [];
|
|
655
740
|
try {
|
|
656
741
|
const now = /* @__PURE__ */ new Date();
|
|
742
|
+
const threadId = messages[0]?.threadId;
|
|
657
743
|
for (const [i, message] of messages.entries()) {
|
|
658
744
|
if (!message.id) throw new Error(`Message at index ${i} missing id`);
|
|
659
|
-
if (!message.threadId)
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
745
|
+
if (!message.threadId) {
|
|
746
|
+
throw new Error(`Message at index ${i} missing threadId`);
|
|
747
|
+
}
|
|
748
|
+
if (!message.content) {
|
|
749
|
+
throw new Error(`Message at index ${i} missing content`);
|
|
750
|
+
}
|
|
751
|
+
if (!message.role) {
|
|
752
|
+
throw new Error(`Message at index ${i} missing role`);
|
|
753
|
+
}
|
|
754
|
+
if (!message.resourceId) {
|
|
755
|
+
throw new Error(`Message at index ${i} missing resourceId`);
|
|
756
|
+
}
|
|
757
|
+
const thread = await this.getThreadById({ threadId: message.threadId });
|
|
758
|
+
if (!thread) {
|
|
664
759
|
throw new Error(`Thread ${message.threadId} not found`);
|
|
665
760
|
}
|
|
666
761
|
}
|
|
@@ -672,74 +767,122 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
672
767
|
content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
673
768
|
createdAt: createdAt.toISOString(),
|
|
674
769
|
role: message.role,
|
|
675
|
-
type: message.type
|
|
770
|
+
type: message.type || "v2",
|
|
771
|
+
resourceId: message.resourceId
|
|
676
772
|
};
|
|
677
773
|
});
|
|
678
|
-
await
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
774
|
+
await Promise.all([
|
|
775
|
+
this.operations.batchUpsert({
|
|
776
|
+
tableName: storage.TABLE_MESSAGES,
|
|
777
|
+
records: messagesToInsert
|
|
778
|
+
}),
|
|
779
|
+
// Update thread's updatedAt timestamp
|
|
780
|
+
this.operations.executeQuery({
|
|
781
|
+
sql: `UPDATE ${this.operations.getTableName(storage.TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
|
|
782
|
+
params: [now.toISOString(), threadId]
|
|
783
|
+
})
|
|
784
|
+
]);
|
|
682
785
|
this.logger.debug(`Saved ${messages.length} messages`);
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
786
|
+
const list = new agent.MessageList().add(messages, "memory");
|
|
787
|
+
if (format === `v2`) return list.get.all.v2();
|
|
788
|
+
return list.get.all.v1();
|
|
789
|
+
} catch (error$1) {
|
|
790
|
+
throw new error.MastraError(
|
|
791
|
+
{
|
|
792
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
|
|
793
|
+
domain: error.ErrorDomain.STORAGE,
|
|
794
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
795
|
+
text: `Failed to save messages: ${error$1 instanceof Error ? error$1.message : String(error$1)}`
|
|
796
|
+
},
|
|
797
|
+
error$1
|
|
798
|
+
);
|
|
687
799
|
}
|
|
688
800
|
}
|
|
689
|
-
async
|
|
690
|
-
|
|
691
|
-
const
|
|
692
|
-
|
|
693
|
-
const
|
|
801
|
+
async _getIncludedMessages(threadId, selectBy) {
|
|
802
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
803
|
+
const include = selectBy?.include;
|
|
804
|
+
if (!include) return null;
|
|
805
|
+
const unionQueries = [];
|
|
806
|
+
const params = [];
|
|
807
|
+
let paramIdx = 1;
|
|
808
|
+
for (const inc of include) {
|
|
809
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
810
|
+
const searchId = inc.threadId || threadId;
|
|
811
|
+
unionQueries.push(`
|
|
812
|
+
SELECT * FROM (
|
|
813
|
+
WITH ordered_messages AS (
|
|
814
|
+
SELECT
|
|
815
|
+
*,
|
|
816
|
+
ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
|
|
817
|
+
FROM ${this.operations.getTableName(storage.TABLE_MESSAGES)}
|
|
818
|
+
WHERE thread_id = ?
|
|
819
|
+
)
|
|
820
|
+
SELECT
|
|
821
|
+
m.id,
|
|
822
|
+
m.content,
|
|
823
|
+
m.role,
|
|
824
|
+
m.type,
|
|
825
|
+
m.createdAt,
|
|
826
|
+
m.thread_id AS threadId,
|
|
827
|
+
m.resourceId
|
|
828
|
+
FROM ordered_messages m
|
|
829
|
+
WHERE m.id = ?
|
|
830
|
+
OR EXISTS (
|
|
831
|
+
SELECT 1 FROM ordered_messages target
|
|
832
|
+
WHERE target.id = ?
|
|
833
|
+
AND (
|
|
834
|
+
(m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
|
|
835
|
+
OR
|
|
836
|
+
(m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
|
|
837
|
+
)
|
|
838
|
+
)
|
|
839
|
+
) AS query_${paramIdx}
|
|
840
|
+
`);
|
|
841
|
+
params.push(searchId, id, id, withNextMessages, withPreviousMessages);
|
|
842
|
+
paramIdx++;
|
|
843
|
+
}
|
|
844
|
+
const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
|
|
845
|
+
const messages = await this.operations.executeQuery({ sql: finalQuery, params });
|
|
846
|
+
if (!Array.isArray(messages)) {
|
|
847
|
+
return [];
|
|
848
|
+
}
|
|
849
|
+
const processedMessages = messages.map((message) => {
|
|
850
|
+
const processedMsg = {};
|
|
851
|
+
for (const [key, value] of Object.entries(message)) {
|
|
852
|
+
if (key === `type` && value === `v2`) continue;
|
|
853
|
+
processedMsg[key] = deserializeValue(value);
|
|
854
|
+
}
|
|
855
|
+
return processedMsg;
|
|
856
|
+
});
|
|
857
|
+
return processedMessages;
|
|
858
|
+
}
|
|
859
|
+
async getMessages({
|
|
860
|
+
threadId,
|
|
861
|
+
resourceId,
|
|
862
|
+
selectBy,
|
|
863
|
+
format
|
|
864
|
+
}) {
|
|
694
865
|
try {
|
|
866
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
867
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
868
|
+
const limit = storage.resolveMessageLimit({
|
|
869
|
+
last: selectBy?.last,
|
|
870
|
+
defaultLimit: 40
|
|
871
|
+
});
|
|
872
|
+
const include = selectBy?.include || [];
|
|
873
|
+
const messages = [];
|
|
695
874
|
if (include.length) {
|
|
696
|
-
const
|
|
697
|
-
const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
|
|
698
|
-
const includeIds = include.map((i) => i.id);
|
|
699
|
-
const sql2 = `
|
|
700
|
-
WITH ordered_messages AS (
|
|
701
|
-
SELECT
|
|
702
|
-
*,
|
|
703
|
-
ROW_NUMBER() OVER (ORDER BY createdAt DESC) AS row_num
|
|
704
|
-
FROM ${fullTableName}
|
|
705
|
-
WHERE thread_id = ?
|
|
706
|
-
)
|
|
707
|
-
SELECT
|
|
708
|
-
m.id,
|
|
709
|
-
m.content,
|
|
710
|
-
m.role,
|
|
711
|
-
m.type,
|
|
712
|
-
m.createdAt,
|
|
713
|
-
m.thread_id AS "threadId"
|
|
714
|
-
FROM ordered_messages m
|
|
715
|
-
WHERE m.id IN (${includeIds.map(() => "?").join(",")})
|
|
716
|
-
OR EXISTS (
|
|
717
|
-
SELECT 1 FROM ordered_messages target
|
|
718
|
-
WHERE target.id IN (${includeIds.map(() => "?").join(",")})
|
|
719
|
-
AND (
|
|
720
|
-
(m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
|
|
721
|
-
OR
|
|
722
|
-
(m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
|
|
723
|
-
)
|
|
724
|
-
)
|
|
725
|
-
ORDER BY m.createdAt DESC
|
|
726
|
-
`;
|
|
727
|
-
const params2 = [
|
|
728
|
-
threadId,
|
|
729
|
-
...includeIds,
|
|
730
|
-
// for m.id IN (...)
|
|
731
|
-
...includeIds,
|
|
732
|
-
// for target.id IN (...)
|
|
733
|
-
prevMax,
|
|
734
|
-
nextMax
|
|
735
|
-
];
|
|
736
|
-
const includeResult = await this.executeQuery({ sql: sql2, params: params2 });
|
|
875
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
737
876
|
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
738
877
|
}
|
|
739
878
|
const excludeIds = messages.map((m) => m.id);
|
|
740
|
-
|
|
879
|
+
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
|
|
880
|
+
if (excludeIds.length > 0) {
|
|
881
|
+
query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
|
|
882
|
+
}
|
|
883
|
+
query.orderBy("createdAt", "DESC").limit(limit);
|
|
741
884
|
const { sql, params } = query.build();
|
|
742
|
-
const result = await this.executeQuery({ sql, params });
|
|
885
|
+
const result = await this.operations.executeQuery({ sql, params });
|
|
743
886
|
if (Array.isArray(result)) messages.push(...result);
|
|
744
887
|
messages.sort((a, b) => {
|
|
745
888
|
const aRecord = a;
|
|
@@ -751,186 +894,1475 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
751
894
|
const processedMessages = messages.map((message) => {
|
|
752
895
|
const processedMsg = {};
|
|
753
896
|
for (const [key, value] of Object.entries(message)) {
|
|
754
|
-
|
|
897
|
+
if (key === `type` && value === `v2`) continue;
|
|
898
|
+
processedMsg[key] = deserializeValue(value);
|
|
755
899
|
}
|
|
756
900
|
return processedMsg;
|
|
757
901
|
});
|
|
758
902
|
this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
903
|
+
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
904
|
+
if (format === `v2`) return list.get.all.v2();
|
|
905
|
+
return list.get.all.v1();
|
|
906
|
+
} catch (error$1) {
|
|
907
|
+
const mastraError = new error.MastraError(
|
|
908
|
+
{
|
|
909
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
|
|
910
|
+
domain: error.ErrorDomain.STORAGE,
|
|
911
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
912
|
+
text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
913
|
+
details: { threadId, resourceId: resourceId ?? "" }
|
|
914
|
+
},
|
|
915
|
+
error$1
|
|
916
|
+
);
|
|
917
|
+
this.logger?.error(mastraError.toString());
|
|
918
|
+
this.logger?.trackException(mastraError);
|
|
919
|
+
throw mastraError;
|
|
766
920
|
}
|
|
767
921
|
}
|
|
768
|
-
async
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
snapshot
|
|
922
|
+
async getMessagesById({
|
|
923
|
+
messageIds,
|
|
924
|
+
format
|
|
772
925
|
}) {
|
|
773
|
-
|
|
774
|
-
const
|
|
775
|
-
const
|
|
776
|
-
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
777
|
-
keys: { workflow_name: workflowName, run_id: runId }
|
|
778
|
-
});
|
|
779
|
-
const persisting = currentSnapshot ? {
|
|
780
|
-
...currentSnapshot,
|
|
781
|
-
snapshot: JSON.stringify(snapshot),
|
|
782
|
-
updatedAt: now
|
|
783
|
-
} : {
|
|
784
|
-
workflow_name: workflowName,
|
|
785
|
-
run_id: runId,
|
|
786
|
-
snapshot,
|
|
787
|
-
createdAt: now,
|
|
788
|
-
updatedAt: now
|
|
789
|
-
};
|
|
790
|
-
const processedRecord = await this.processRecord(persisting);
|
|
791
|
-
const columns = Object.keys(processedRecord);
|
|
792
|
-
const values = Object.values(processedRecord);
|
|
793
|
-
const updateMap = {
|
|
794
|
-
snapshot: "excluded.snapshot",
|
|
795
|
-
updatedAt: "excluded.updatedAt"
|
|
796
|
-
};
|
|
797
|
-
this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
|
|
798
|
-
const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
|
|
799
|
-
const { sql, params } = query.build();
|
|
926
|
+
if (messageIds.length === 0) return [];
|
|
927
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
928
|
+
const messages = [];
|
|
800
929
|
try {
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
930
|
+
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
|
|
931
|
+
query.orderBy("createdAt", "DESC");
|
|
932
|
+
const { sql, params } = query.build();
|
|
933
|
+
const result = await this.operations.executeQuery({ sql, params });
|
|
934
|
+
if (Array.isArray(result)) messages.push(...result);
|
|
935
|
+
const processedMessages = messages.map((message) => {
|
|
936
|
+
const processedMsg = {};
|
|
937
|
+
for (const [key, value] of Object.entries(message)) {
|
|
938
|
+
if (key === `type` && value === `v2`) continue;
|
|
939
|
+
processedMsg[key] = deserializeValue(value);
|
|
940
|
+
}
|
|
941
|
+
return processedMsg;
|
|
805
942
|
});
|
|
806
|
-
|
|
943
|
+
this.logger.debug(`Retrieved ${messages.length} messages`);
|
|
944
|
+
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
945
|
+
if (format === `v1`) return list.get.all.v1();
|
|
946
|
+
return list.get.all.v2();
|
|
947
|
+
} catch (error$1) {
|
|
948
|
+
const mastraError = new error.MastraError(
|
|
949
|
+
{
|
|
950
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
|
|
951
|
+
domain: error.ErrorDomain.STORAGE,
|
|
952
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
953
|
+
text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
954
|
+
details: { messageIds: JSON.stringify(messageIds) }
|
|
955
|
+
},
|
|
956
|
+
error$1
|
|
957
|
+
);
|
|
958
|
+
this.logger?.error(mastraError.toString());
|
|
959
|
+
this.logger?.trackException(mastraError);
|
|
960
|
+
throw mastraError;
|
|
807
961
|
}
|
|
808
962
|
}
|
|
809
|
-
async
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
963
|
+
async getMessagesPaginated({
|
|
964
|
+
threadId,
|
|
965
|
+
resourceId,
|
|
966
|
+
selectBy,
|
|
967
|
+
format
|
|
968
|
+
}) {
|
|
969
|
+
const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
|
|
970
|
+
const { start: fromDate, end: toDate } = dateRange || {};
|
|
971
|
+
const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
972
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
973
|
+
const messages = [];
|
|
974
|
+
try {
|
|
975
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
976
|
+
if (selectBy?.include?.length) {
|
|
977
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
978
|
+
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
817
979
|
}
|
|
818
|
-
|
|
819
|
-
|
|
980
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
|
|
981
|
+
if (fromDate) {
|
|
982
|
+
countQuery.andWhere("createdAt >= ?", storage.serializeDate(fromDate));
|
|
983
|
+
}
|
|
984
|
+
if (toDate) {
|
|
985
|
+
countQuery.andWhere("createdAt <= ?", storage.serializeDate(toDate));
|
|
986
|
+
}
|
|
987
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
988
|
+
const total = Number(countResult[0]?.count ?? 0);
|
|
989
|
+
if (total === 0 && messages.length === 0) {
|
|
990
|
+
return {
|
|
991
|
+
messages: [],
|
|
992
|
+
total: 0,
|
|
993
|
+
page,
|
|
994
|
+
perPage,
|
|
995
|
+
hasMore: false
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
const excludeIds = messages.map((m) => m.id);
|
|
999
|
+
const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
|
|
1000
|
+
let query;
|
|
1001
|
+
let queryParams = [threadId];
|
|
1002
|
+
if (fromDate) {
|
|
1003
|
+
queryParams.push(storage.serializeDate(fromDate));
|
|
1004
|
+
}
|
|
1005
|
+
if (toDate) {
|
|
1006
|
+
queryParams.push(storage.serializeDate(toDate));
|
|
1007
|
+
}
|
|
1008
|
+
if (excludeIds.length > 0) {
|
|
1009
|
+
queryParams.push(...excludeIds);
|
|
1010
|
+
}
|
|
1011
|
+
if (selectBy?.last && selectBy.last > 0) {
|
|
1012
|
+
query = `
|
|
1013
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1014
|
+
FROM ${fullTableName}
|
|
1015
|
+
WHERE thread_id = ?
|
|
1016
|
+
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1017
|
+
${toDate ? "AND createdAt <= ?" : ""}
|
|
1018
|
+
${excludeCondition}
|
|
1019
|
+
ORDER BY createdAt DESC
|
|
1020
|
+
LIMIT ?
|
|
1021
|
+
`;
|
|
1022
|
+
queryParams.push(selectBy.last);
|
|
1023
|
+
} else {
|
|
1024
|
+
query = `
|
|
1025
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1026
|
+
FROM ${fullTableName}
|
|
1027
|
+
WHERE thread_id = ?
|
|
1028
|
+
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1029
|
+
${toDate ? "AND createdAt <= ?" : ""}
|
|
1030
|
+
${excludeCondition}
|
|
1031
|
+
ORDER BY createdAt DESC
|
|
1032
|
+
LIMIT ? OFFSET ?
|
|
1033
|
+
`;
|
|
1034
|
+
queryParams.push(perPage, page * perPage);
|
|
1035
|
+
}
|
|
1036
|
+
const results = await this.operations.executeQuery({ sql: query, params: queryParams });
|
|
1037
|
+
const processedMessages = results.map((message) => {
|
|
1038
|
+
const processedMsg = {};
|
|
1039
|
+
for (const [key, value] of Object.entries(message)) {
|
|
1040
|
+
if (key === `type` && value === `v2`) continue;
|
|
1041
|
+
processedMsg[key] = deserializeValue(value);
|
|
1042
|
+
}
|
|
1043
|
+
return processedMsg;
|
|
1044
|
+
});
|
|
1045
|
+
if (selectBy?.last) {
|
|
1046
|
+
processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
1047
|
+
}
|
|
1048
|
+
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
1049
|
+
messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
|
|
1050
|
+
return {
|
|
1051
|
+
messages,
|
|
1052
|
+
total,
|
|
1053
|
+
page,
|
|
1054
|
+
perPage,
|
|
1055
|
+
hasMore: selectBy?.last ? false : page * perPage + messages.length < total
|
|
1056
|
+
};
|
|
1057
|
+
} catch (error$1) {
|
|
1058
|
+
const mastraError = new error.MastraError(
|
|
1059
|
+
{
|
|
1060
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
|
|
1061
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1062
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1063
|
+
text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1064
|
+
details: { threadId, resourceId: resourceId ?? "" }
|
|
1065
|
+
},
|
|
1066
|
+
error$1
|
|
1067
|
+
);
|
|
1068
|
+
this.logger?.error(mastraError.toString());
|
|
1069
|
+
this.logger?.trackException(mastraError);
|
|
1070
|
+
return {
|
|
1071
|
+
messages: [],
|
|
1072
|
+
total: 0,
|
|
1073
|
+
page,
|
|
1074
|
+
perPage,
|
|
1075
|
+
hasMore: false
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
820
1078
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
const fullTableName = this.getTableName(
|
|
1079
|
+
async updateMessages(args) {
|
|
1080
|
+
const { messages } = args;
|
|
1081
|
+
this.logger.debug("Updating messages", { count: messages.length });
|
|
1082
|
+
if (!messages.length) {
|
|
1083
|
+
return [];
|
|
1084
|
+
}
|
|
1085
|
+
const messageIds = messages.map((m) => m.id);
|
|
1086
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
1087
|
+
const threadsTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
829
1088
|
try {
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
return this.serializeValue(value);
|
|
842
|
-
});
|
|
843
|
-
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
844
|
-
const { sql, params } = query.build();
|
|
845
|
-
await this.executeQuery({ sql, params });
|
|
1089
|
+
const placeholders = messageIds.map(() => "?").join(",");
|
|
1090
|
+
const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
|
|
1091
|
+
const existingMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
|
|
1092
|
+
if (existingMessages.length === 0) {
|
|
1093
|
+
return [];
|
|
1094
|
+
}
|
|
1095
|
+
const parsedExistingMessages = existingMessages.map((msg) => {
|
|
1096
|
+
if (typeof msg.content === "string") {
|
|
1097
|
+
try {
|
|
1098
|
+
msg.content = JSON.parse(msg.content);
|
|
1099
|
+
} catch {
|
|
846
1100
|
}
|
|
847
1101
|
}
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
1102
|
+
return msg;
|
|
1103
|
+
});
|
|
1104
|
+
const threadIdsToUpdate = /* @__PURE__ */ new Set();
|
|
1105
|
+
const updateQueries = [];
|
|
1106
|
+
for (const existingMessage of parsedExistingMessages) {
|
|
1107
|
+
const updatePayload = messages.find((m) => m.id === existingMessage.id);
|
|
1108
|
+
if (!updatePayload) continue;
|
|
1109
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1110
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1111
|
+
threadIdsToUpdate.add(existingMessage.threadId);
|
|
1112
|
+
if ("threadId" in updatePayload && updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
1113
|
+
threadIdsToUpdate.add(updatePayload.threadId);
|
|
1114
|
+
}
|
|
1115
|
+
const setClauses = [];
|
|
1116
|
+
const values = [];
|
|
1117
|
+
const updatableFields = { ...fieldsToUpdate };
|
|
1118
|
+
if (updatableFields.content) {
|
|
1119
|
+
const existingContent = existingMessage.content || {};
|
|
1120
|
+
const newContent = {
|
|
1121
|
+
...existingContent,
|
|
1122
|
+
...updatableFields.content,
|
|
1123
|
+
// Deep merge metadata if it exists on both
|
|
1124
|
+
...existingContent?.metadata && updatableFields.content.metadata ? {
|
|
1125
|
+
metadata: {
|
|
1126
|
+
...existingContent.metadata,
|
|
1127
|
+
...updatableFields.content.metadata
|
|
1128
|
+
}
|
|
1129
|
+
} : {}
|
|
1130
|
+
};
|
|
1131
|
+
setClauses.push(`content = ?`);
|
|
1132
|
+
values.push(JSON.stringify(newContent));
|
|
1133
|
+
delete updatableFields.content;
|
|
1134
|
+
}
|
|
1135
|
+
for (const key in updatableFields) {
|
|
1136
|
+
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
1137
|
+
const dbColumn = key === "threadId" ? "thread_id" : key;
|
|
1138
|
+
setClauses.push(`${dbColumn} = ?`);
|
|
1139
|
+
values.push(updatableFields[key]);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
if (setClauses.length > 0) {
|
|
1143
|
+
values.push(id);
|
|
1144
|
+
const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
|
|
1145
|
+
updateQueries.push({ sql: updateQuery, params: values });
|
|
1146
|
+
}
|
|
851
1147
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1148
|
+
for (const query of updateQueries) {
|
|
1149
|
+
await this.operations.executeQuery(query);
|
|
1150
|
+
}
|
|
1151
|
+
if (threadIdsToUpdate.size > 0) {
|
|
1152
|
+
const threadPlaceholders = Array.from(threadIdsToUpdate).map(() => "?").join(",");
|
|
1153
|
+
const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadPlaceholders})`;
|
|
1154
|
+
const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
|
|
1155
|
+
await this.operations.executeQuery({ sql: threadUpdateQuery, params: threadUpdateParams });
|
|
1156
|
+
}
|
|
1157
|
+
const updatedMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
|
|
1158
|
+
return updatedMessages.map((message) => {
|
|
1159
|
+
if (typeof message.content === "string") {
|
|
1160
|
+
try {
|
|
1161
|
+
message.content = JSON.parse(message.content);
|
|
1162
|
+
} catch {
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
return message;
|
|
856
1166
|
});
|
|
857
|
-
|
|
1167
|
+
} catch (error$1) {
|
|
1168
|
+
throw new error.MastraError(
|
|
1169
|
+
{
|
|
1170
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
|
|
1171
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1172
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1173
|
+
details: { count: messages.length }
|
|
1174
|
+
},
|
|
1175
|
+
error$1
|
|
1176
|
+
);
|
|
858
1177
|
}
|
|
859
1178
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
1179
|
+
};
|
|
1180
|
+
var StoreOperationsD1 = class extends storage.StoreOperations {
|
|
1181
|
+
client;
|
|
1182
|
+
binding;
|
|
1183
|
+
tablePrefix;
|
|
1184
|
+
constructor(config) {
|
|
1185
|
+
super();
|
|
1186
|
+
this.client = config.client;
|
|
1187
|
+
this.binding = config.binding;
|
|
1188
|
+
this.tablePrefix = config.tablePrefix || "";
|
|
1189
|
+
}
|
|
1190
|
+
async hasColumn(table, column) {
|
|
1191
|
+
const fullTableName = table.startsWith(this.tablePrefix) ? table : `${this.tablePrefix}${table}`;
|
|
1192
|
+
const sql = `PRAGMA table_info(${fullTableName});`;
|
|
1193
|
+
const result = await this.executeQuery({ sql, params: [] });
|
|
1194
|
+
if (!result || !Array.isArray(result)) return false;
|
|
1195
|
+
return result.some((col) => col.name === column || col.name === column.toLowerCase());
|
|
1196
|
+
}
|
|
1197
|
+
getTableName(tableName) {
|
|
1198
|
+
return `${this.tablePrefix}${tableName}`;
|
|
1199
|
+
}
|
|
1200
|
+
formatSqlParams(params) {
|
|
1201
|
+
return params.map((p) => p === void 0 || p === null ? null : p);
|
|
1202
|
+
}
|
|
1203
|
+
async executeWorkersBindingQuery({
|
|
1204
|
+
sql,
|
|
1205
|
+
params = [],
|
|
1206
|
+
first = false
|
|
866
1207
|
}) {
|
|
867
|
-
|
|
1208
|
+
if (!this.binding) {
|
|
1209
|
+
throw new Error("Workers binding is not configured");
|
|
1210
|
+
}
|
|
868
1211
|
try {
|
|
869
|
-
const
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
1212
|
+
const statement = this.binding.prepare(sql);
|
|
1213
|
+
const formattedParams = this.formatSqlParams(params);
|
|
1214
|
+
let result;
|
|
1215
|
+
if (formattedParams.length > 0) {
|
|
1216
|
+
if (first) {
|
|
1217
|
+
result = await statement.bind(...formattedParams).first();
|
|
1218
|
+
if (!result) return null;
|
|
1219
|
+
return result;
|
|
1220
|
+
} else {
|
|
1221
|
+
result = await statement.bind(...formattedParams).all();
|
|
1222
|
+
const results = result.results || [];
|
|
1223
|
+
return results;
|
|
1224
|
+
}
|
|
1225
|
+
} else {
|
|
1226
|
+
if (first) {
|
|
1227
|
+
result = await statement.first();
|
|
1228
|
+
if (!result) return null;
|
|
1229
|
+
return result;
|
|
1230
|
+
} else {
|
|
1231
|
+
result = await statement.all();
|
|
1232
|
+
const results = result.results || [];
|
|
1233
|
+
return results;
|
|
879
1234
|
}
|
|
880
1235
|
}
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
})) : [];
|
|
892
|
-
} catch (error) {
|
|
893
|
-
this.logger.error("Error getting traces:", { message: error instanceof Error ? error.message : String(error) });
|
|
894
|
-
return [];
|
|
1236
|
+
} catch (error$1) {
|
|
1237
|
+
throw new error.MastraError(
|
|
1238
|
+
{
|
|
1239
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
|
|
1240
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1241
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1242
|
+
details: { sql }
|
|
1243
|
+
},
|
|
1244
|
+
error$1
|
|
1245
|
+
);
|
|
895
1246
|
}
|
|
896
1247
|
}
|
|
897
|
-
async
|
|
898
|
-
|
|
1248
|
+
async executeRestQuery({
|
|
1249
|
+
sql,
|
|
1250
|
+
params = [],
|
|
1251
|
+
first = false
|
|
1252
|
+
}) {
|
|
1253
|
+
if (!this.client) {
|
|
1254
|
+
throw new Error("D1 client is not configured");
|
|
1255
|
+
}
|
|
899
1256
|
try {
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
1257
|
+
const formattedParams = this.formatSqlParams(params);
|
|
1258
|
+
const response = await this.client.query({
|
|
1259
|
+
sql,
|
|
1260
|
+
params: formattedParams
|
|
1261
|
+
});
|
|
1262
|
+
const result = response.result || [];
|
|
1263
|
+
const results = result.flatMap((r) => r.results || []);
|
|
1264
|
+
if (first) {
|
|
1265
|
+
return results[0] || null;
|
|
905
1266
|
}
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
1267
|
+
return results;
|
|
1268
|
+
} catch (error$1) {
|
|
1269
|
+
throw new error.MastraError(
|
|
1270
|
+
{
|
|
1271
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
|
|
1272
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1273
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1274
|
+
details: { sql }
|
|
1275
|
+
},
|
|
1276
|
+
error$1
|
|
1277
|
+
);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
async executeQuery(options) {
|
|
1281
|
+
if (this.binding) {
|
|
1282
|
+
return this.executeWorkersBindingQuery(options);
|
|
1283
|
+
} else if (this.client) {
|
|
1284
|
+
return this.executeRestQuery(options);
|
|
1285
|
+
} else {
|
|
1286
|
+
throw new Error("Neither binding nor client is configured");
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
async getTableColumns(tableName) {
|
|
1290
|
+
try {
|
|
1291
|
+
const sql = `PRAGMA table_info(${tableName})`;
|
|
1292
|
+
const result = await this.executeQuery({ sql });
|
|
1293
|
+
if (!result || !Array.isArray(result)) {
|
|
1294
|
+
return [];
|
|
1295
|
+
}
|
|
1296
|
+
return result.map((row) => ({
|
|
1297
|
+
name: row.name,
|
|
1298
|
+
type: row.type
|
|
1299
|
+
}));
|
|
925
1300
|
} catch (error) {
|
|
926
|
-
this.logger.
|
|
927
|
-
message: error instanceof Error ? error.message : String(error)
|
|
928
|
-
});
|
|
1301
|
+
this.logger.warn(`Failed to get table columns for ${tableName}:`, error);
|
|
929
1302
|
return [];
|
|
930
1303
|
}
|
|
931
1304
|
}
|
|
932
|
-
|
|
933
|
-
|
|
1305
|
+
serializeValue(value) {
|
|
1306
|
+
if (value === null || value === void 0) {
|
|
1307
|
+
return null;
|
|
1308
|
+
}
|
|
1309
|
+
if (value instanceof Date) {
|
|
1310
|
+
return value.toISOString();
|
|
1311
|
+
}
|
|
1312
|
+
if (typeof value === "object") {
|
|
1313
|
+
return JSON.stringify(value);
|
|
1314
|
+
}
|
|
1315
|
+
return value;
|
|
1316
|
+
}
|
|
1317
|
+
getSqlType(type) {
|
|
1318
|
+
switch (type) {
|
|
1319
|
+
case "bigint":
|
|
1320
|
+
return "INTEGER";
|
|
1321
|
+
// SQLite uses INTEGER for all integer sizes
|
|
1322
|
+
case "jsonb":
|
|
1323
|
+
return "TEXT";
|
|
1324
|
+
// Store JSON as TEXT in SQLite
|
|
1325
|
+
default:
|
|
1326
|
+
return super.getSqlType(type);
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
async createTable({
|
|
1330
|
+
tableName,
|
|
1331
|
+
schema
|
|
1332
|
+
}) {
|
|
1333
|
+
try {
|
|
1334
|
+
const fullTableName = this.getTableName(tableName);
|
|
1335
|
+
const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
|
|
1336
|
+
const type = this.getSqlType(colDef.type);
|
|
1337
|
+
const nullable = colDef.nullable === false ? "NOT NULL" : "";
|
|
1338
|
+
const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
|
|
1339
|
+
return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
|
|
1340
|
+
});
|
|
1341
|
+
const tableConstraints = [];
|
|
1342
|
+
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
1343
|
+
tableConstraints.push("UNIQUE (workflow_name, run_id)");
|
|
1344
|
+
}
|
|
1345
|
+
const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
|
|
1346
|
+
const { sql, params } = query.build();
|
|
1347
|
+
await this.executeQuery({ sql, params });
|
|
1348
|
+
this.logger.debug(`Created table ${fullTableName}`);
|
|
1349
|
+
} catch (error$1) {
|
|
1350
|
+
throw new error.MastraError(
|
|
1351
|
+
{
|
|
1352
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
|
|
1353
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1354
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1355
|
+
details: { tableName }
|
|
1356
|
+
},
|
|
1357
|
+
error$1
|
|
1358
|
+
);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
async clearTable({ tableName }) {
|
|
1362
|
+
try {
|
|
1363
|
+
const fullTableName = this.getTableName(tableName);
|
|
1364
|
+
const query = createSqlBuilder().delete(fullTableName);
|
|
1365
|
+
const { sql, params } = query.build();
|
|
1366
|
+
await this.executeQuery({ sql, params });
|
|
1367
|
+
this.logger.debug(`Cleared table ${fullTableName}`);
|
|
1368
|
+
} catch (error$1) {
|
|
1369
|
+
throw new error.MastraError(
|
|
1370
|
+
{
|
|
1371
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
|
|
1372
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1373
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1374
|
+
details: { tableName }
|
|
1375
|
+
},
|
|
1376
|
+
error$1
|
|
1377
|
+
);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
async dropTable({ tableName }) {
|
|
1381
|
+
try {
|
|
1382
|
+
const fullTableName = this.getTableName(tableName);
|
|
1383
|
+
const sql = `DROP TABLE IF EXISTS ${fullTableName}`;
|
|
1384
|
+
await this.executeQuery({ sql });
|
|
1385
|
+
this.logger.debug(`Dropped table ${fullTableName}`);
|
|
1386
|
+
} catch (error$1) {
|
|
1387
|
+
throw new error.MastraError(
|
|
1388
|
+
{
|
|
1389
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
|
|
1390
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1391
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1392
|
+
details: { tableName }
|
|
1393
|
+
},
|
|
1394
|
+
error$1
|
|
1395
|
+
);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
async alterTable(args) {
|
|
1399
|
+
try {
|
|
1400
|
+
const fullTableName = this.getTableName(args.tableName);
|
|
1401
|
+
const existingColumns = await this.getTableColumns(fullTableName);
|
|
1402
|
+
const existingColumnNames = new Set(existingColumns.map((col) => col.name));
|
|
1403
|
+
for (const [columnName, column] of Object.entries(args.schema)) {
|
|
1404
|
+
if (!existingColumnNames.has(columnName) && args.ifNotExists.includes(columnName)) {
|
|
1405
|
+
const sqlType = this.getSqlType(column.type);
|
|
1406
|
+
const defaultValue = this.getDefaultValue(column.type);
|
|
1407
|
+
const sql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${defaultValue}`;
|
|
1408
|
+
await this.executeQuery({ sql });
|
|
1409
|
+
this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
} catch (error$1) {
|
|
1413
|
+
throw new error.MastraError(
|
|
1414
|
+
{
|
|
1415
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
|
|
1416
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1417
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1418
|
+
details: { tableName: args.tableName }
|
|
1419
|
+
},
|
|
1420
|
+
error$1
|
|
1421
|
+
);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
async insert({ tableName, record }) {
|
|
1425
|
+
try {
|
|
1426
|
+
const fullTableName = this.getTableName(tableName);
|
|
1427
|
+
const processedRecord = await this.processRecord(record);
|
|
1428
|
+
const columns = Object.keys(processedRecord);
|
|
1429
|
+
const values = Object.values(processedRecord);
|
|
1430
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1431
|
+
const { sql, params } = query.build();
|
|
1432
|
+
await this.executeQuery({ sql, params });
|
|
1433
|
+
} catch (error$1) {
|
|
1434
|
+
throw new error.MastraError(
|
|
1435
|
+
{
|
|
1436
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
|
|
1437
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1438
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1439
|
+
details: { tableName }
|
|
1440
|
+
},
|
|
1441
|
+
error$1
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
async batchInsert({ tableName, records }) {
|
|
1446
|
+
try {
|
|
1447
|
+
if (records.length === 0) return;
|
|
1448
|
+
const fullTableName = this.getTableName(tableName);
|
|
1449
|
+
const processedRecords = await Promise.all(records.map((record) => this.processRecord(record)));
|
|
1450
|
+
const columns = Object.keys(processedRecords[0] || {});
|
|
1451
|
+
for (const record of processedRecords) {
|
|
1452
|
+
const values = Object.values(record);
|
|
1453
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1454
|
+
const { sql, params } = query.build();
|
|
1455
|
+
await this.executeQuery({ sql, params });
|
|
1456
|
+
}
|
|
1457
|
+
} catch (error$1) {
|
|
1458
|
+
throw new error.MastraError(
|
|
1459
|
+
{
|
|
1460
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
|
|
1461
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1462
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1463
|
+
details: { tableName }
|
|
1464
|
+
},
|
|
1465
|
+
error$1
|
|
1466
|
+
);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
async load({ tableName, keys }) {
|
|
1470
|
+
try {
|
|
1471
|
+
const fullTableName = this.getTableName(tableName);
|
|
1472
|
+
const query = createSqlBuilder().select("*").from(fullTableName);
|
|
1473
|
+
let firstKey = true;
|
|
1474
|
+
for (const [key, value] of Object.entries(keys)) {
|
|
1475
|
+
if (firstKey) {
|
|
1476
|
+
query.where(`${key} = ?`, value);
|
|
1477
|
+
firstKey = false;
|
|
1478
|
+
} else {
|
|
1479
|
+
query.andWhere(`${key} = ?`, value);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
query.orderBy("createdAt", "DESC");
|
|
1483
|
+
query.limit(1);
|
|
1484
|
+
const { sql, params } = query.build();
|
|
1485
|
+
const result = await this.executeQuery({ sql, params, first: true });
|
|
1486
|
+
if (!result) {
|
|
1487
|
+
return null;
|
|
1488
|
+
}
|
|
1489
|
+
const deserializedResult = {};
|
|
1490
|
+
for (const [key, value] of Object.entries(result)) {
|
|
1491
|
+
deserializedResult[key] = deserializeValue(value);
|
|
1492
|
+
}
|
|
1493
|
+
return deserializedResult;
|
|
1494
|
+
} catch (error$1) {
|
|
1495
|
+
throw new error.MastraError(
|
|
1496
|
+
{
|
|
1497
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
|
|
1498
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1499
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1500
|
+
details: { tableName }
|
|
1501
|
+
},
|
|
1502
|
+
error$1
|
|
1503
|
+
);
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
async processRecord(record) {
|
|
1507
|
+
const processed = {};
|
|
1508
|
+
for (const [key, value] of Object.entries(record)) {
|
|
1509
|
+
processed[key] = this.serializeValue(value);
|
|
1510
|
+
}
|
|
1511
|
+
return processed;
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* Upsert multiple records in a batch operation
|
|
1515
|
+
* @param tableName The table to insert into
|
|
1516
|
+
* @param records The records to insert
|
|
1517
|
+
*/
|
|
1518
|
+
async batchUpsert({ tableName, records }) {
|
|
1519
|
+
if (records.length === 0) return;
|
|
1520
|
+
const fullTableName = this.getTableName(tableName);
|
|
1521
|
+
try {
|
|
1522
|
+
const batchSize = 50;
|
|
1523
|
+
for (let i = 0; i < records.length; i += batchSize) {
|
|
1524
|
+
const batch = records.slice(i, i + batchSize);
|
|
1525
|
+
const recordsToInsert = batch;
|
|
1526
|
+
if (recordsToInsert.length > 0) {
|
|
1527
|
+
const firstRecord = recordsToInsert[0];
|
|
1528
|
+
const columns = Object.keys(firstRecord || {});
|
|
1529
|
+
for (const record of recordsToInsert) {
|
|
1530
|
+
const values = columns.map((col) => {
|
|
1531
|
+
if (!record) return null;
|
|
1532
|
+
const value = typeof col === "string" ? record[col] : null;
|
|
1533
|
+
return this.serializeValue(value);
|
|
1534
|
+
});
|
|
1535
|
+
const recordToUpsert = columns.reduce(
|
|
1536
|
+
(acc, col) => {
|
|
1537
|
+
if (col !== "createdAt") acc[col] = `excluded.${col}`;
|
|
1538
|
+
return acc;
|
|
1539
|
+
},
|
|
1540
|
+
{}
|
|
1541
|
+
);
|
|
1542
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert);
|
|
1543
|
+
const { sql, params } = query.build();
|
|
1544
|
+
await this.executeQuery({ sql, params });
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
this.logger.debug(
|
|
1548
|
+
`Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
|
|
1549
|
+
);
|
|
1550
|
+
}
|
|
1551
|
+
this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
|
|
1552
|
+
} catch (error$1) {
|
|
1553
|
+
throw new error.MastraError(
|
|
1554
|
+
{
|
|
1555
|
+
id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
|
|
1556
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1557
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1558
|
+
text: `Failed to batch upsert into ${tableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1559
|
+
details: { tableName }
|
|
1560
|
+
},
|
|
1561
|
+
error$1
|
|
1562
|
+
);
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
};
|
|
1566
|
+
function transformScoreRow(row) {
|
|
1567
|
+
const deserialized = { ...row };
|
|
1568
|
+
deserialized.input = storage.safelyParseJSON(row.input);
|
|
1569
|
+
deserialized.output = storage.safelyParseJSON(row.output);
|
|
1570
|
+
deserialized.scorer = storage.safelyParseJSON(row.scorer);
|
|
1571
|
+
deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
|
|
1572
|
+
deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
|
|
1573
|
+
deserialized.metadata = storage.safelyParseJSON(row.metadata);
|
|
1574
|
+
deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
|
|
1575
|
+
deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
|
|
1576
|
+
deserialized.entity = storage.safelyParseJSON(row.entity);
|
|
1577
|
+
deserialized.createdAt = row.createdAtZ || row.createdAt;
|
|
1578
|
+
deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
|
|
1579
|
+
return deserialized;
|
|
1580
|
+
}
|
|
1581
|
+
var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
1582
|
+
operations;
|
|
1583
|
+
constructor({ operations }) {
|
|
1584
|
+
super();
|
|
1585
|
+
this.operations = operations;
|
|
1586
|
+
}
|
|
1587
|
+
async getScoreById({ id }) {
|
|
1588
|
+
try {
|
|
1589
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1590
|
+
const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
|
|
1591
|
+
const { sql, params } = query.build();
|
|
1592
|
+
const result = await this.operations.executeQuery({ sql, params, first: true });
|
|
1593
|
+
if (!result) {
|
|
1594
|
+
return null;
|
|
1595
|
+
}
|
|
1596
|
+
return transformScoreRow(result);
|
|
1597
|
+
} catch (error$1) {
|
|
1598
|
+
throw new error.MastraError(
|
|
1599
|
+
{
|
|
1600
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
|
|
1601
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1602
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1603
|
+
},
|
|
1604
|
+
error$1
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
async saveScore(score) {
|
|
1609
|
+
let parsedScore;
|
|
1610
|
+
try {
|
|
1611
|
+
parsedScore = scores.saveScorePayloadSchema.parse(score);
|
|
1612
|
+
} catch (error$1) {
|
|
1613
|
+
throw new error.MastraError(
|
|
1614
|
+
{
|
|
1615
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
|
|
1616
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1617
|
+
category: error.ErrorCategory.USER,
|
|
1618
|
+
details: { scoreId: score.id }
|
|
1619
|
+
},
|
|
1620
|
+
error$1
|
|
1621
|
+
);
|
|
1622
|
+
}
|
|
1623
|
+
try {
|
|
1624
|
+
const id = crypto.randomUUID();
|
|
1625
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1626
|
+
const serializedRecord = {};
|
|
1627
|
+
for (const [key, value] of Object.entries(parsedScore)) {
|
|
1628
|
+
if (value !== null && value !== void 0) {
|
|
1629
|
+
if (typeof value === "object") {
|
|
1630
|
+
serializedRecord[key] = JSON.stringify(value);
|
|
1631
|
+
} else {
|
|
1632
|
+
serializedRecord[key] = value;
|
|
1633
|
+
}
|
|
1634
|
+
} else {
|
|
1635
|
+
serializedRecord[key] = null;
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
serializedRecord.id = id;
|
|
1639
|
+
serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1640
|
+
serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1641
|
+
const columns = Object.keys(serializedRecord);
|
|
1642
|
+
const values = Object.values(serializedRecord);
|
|
1643
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1644
|
+
const { sql, params } = query.build();
|
|
1645
|
+
await this.operations.executeQuery({ sql, params });
|
|
1646
|
+
const scoreFromDb = await this.getScoreById({ id });
|
|
1647
|
+
return { score: scoreFromDb };
|
|
1648
|
+
} catch (error$1) {
|
|
1649
|
+
throw new error.MastraError(
|
|
1650
|
+
{
|
|
1651
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
|
|
1652
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1653
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1654
|
+
},
|
|
1655
|
+
error$1
|
|
1656
|
+
);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
async getScoresByScorerId({
|
|
1660
|
+
scorerId,
|
|
1661
|
+
entityId,
|
|
1662
|
+
entityType,
|
|
1663
|
+
source,
|
|
1664
|
+
pagination
|
|
1665
|
+
}) {
|
|
1666
|
+
try {
|
|
1667
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1668
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
|
|
1669
|
+
if (entityId) {
|
|
1670
|
+
countQuery.andWhere("entityId = ?", entityId);
|
|
1671
|
+
}
|
|
1672
|
+
if (entityType) {
|
|
1673
|
+
countQuery.andWhere("entityType = ?", entityType);
|
|
1674
|
+
}
|
|
1675
|
+
if (source) {
|
|
1676
|
+
countQuery.andWhere("source = ?", source);
|
|
1677
|
+
}
|
|
1678
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1679
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1680
|
+
if (total === 0) {
|
|
1681
|
+
return {
|
|
1682
|
+
pagination: {
|
|
1683
|
+
total: 0,
|
|
1684
|
+
page: pagination.page,
|
|
1685
|
+
perPage: pagination.perPage,
|
|
1686
|
+
hasMore: false
|
|
1687
|
+
},
|
|
1688
|
+
scores: []
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
|
|
1692
|
+
if (entityId) {
|
|
1693
|
+
selectQuery.andWhere("entityId = ?", entityId);
|
|
1694
|
+
}
|
|
1695
|
+
if (entityType) {
|
|
1696
|
+
selectQuery.andWhere("entityType = ?", entityType);
|
|
1697
|
+
}
|
|
1698
|
+
if (source) {
|
|
1699
|
+
selectQuery.andWhere("source = ?", source);
|
|
1700
|
+
}
|
|
1701
|
+
selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
|
|
1702
|
+
const { sql, params } = selectQuery.build();
|
|
1703
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1704
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1705
|
+
return {
|
|
1706
|
+
pagination: {
|
|
1707
|
+
total,
|
|
1708
|
+
page: pagination.page,
|
|
1709
|
+
perPage: pagination.perPage,
|
|
1710
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1711
|
+
},
|
|
1712
|
+
scores
|
|
1713
|
+
};
|
|
1714
|
+
} catch (error$1) {
|
|
1715
|
+
throw new error.MastraError(
|
|
1716
|
+
{
|
|
1717
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
1718
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1719
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1720
|
+
},
|
|
1721
|
+
error$1
|
|
1722
|
+
);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
async getScoresByRunId({
|
|
1726
|
+
runId,
|
|
1727
|
+
pagination
|
|
1728
|
+
}) {
|
|
1729
|
+
try {
|
|
1730
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1731
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
|
|
1732
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1733
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1734
|
+
if (total === 0) {
|
|
1735
|
+
return {
|
|
1736
|
+
pagination: {
|
|
1737
|
+
total: 0,
|
|
1738
|
+
page: pagination.page,
|
|
1739
|
+
perPage: pagination.perPage,
|
|
1740
|
+
hasMore: false
|
|
1741
|
+
},
|
|
1742
|
+
scores: []
|
|
1743
|
+
};
|
|
1744
|
+
}
|
|
1745
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
|
|
1746
|
+
const { sql, params } = selectQuery.build();
|
|
1747
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1748
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1749
|
+
return {
|
|
1750
|
+
pagination: {
|
|
1751
|
+
total,
|
|
1752
|
+
page: pagination.page,
|
|
1753
|
+
perPage: pagination.perPage,
|
|
1754
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1755
|
+
},
|
|
1756
|
+
scores
|
|
1757
|
+
};
|
|
1758
|
+
} catch (error$1) {
|
|
1759
|
+
throw new error.MastraError(
|
|
1760
|
+
{
|
|
1761
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
|
|
1762
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1763
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1764
|
+
},
|
|
1765
|
+
error$1
|
|
1766
|
+
);
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
async getScoresByEntityId({
|
|
1770
|
+
entityId,
|
|
1771
|
+
entityType,
|
|
1772
|
+
pagination
|
|
1773
|
+
}) {
|
|
1774
|
+
try {
|
|
1775
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1776
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
|
|
1777
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1778
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1779
|
+
if (total === 0) {
|
|
1780
|
+
return {
|
|
1781
|
+
pagination: {
|
|
1782
|
+
total: 0,
|
|
1783
|
+
page: pagination.page,
|
|
1784
|
+
perPage: pagination.perPage,
|
|
1785
|
+
hasMore: false
|
|
1786
|
+
},
|
|
1787
|
+
scores: []
|
|
1788
|
+
};
|
|
1789
|
+
}
|
|
1790
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
|
|
1791
|
+
const { sql, params } = selectQuery.build();
|
|
1792
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1793
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1794
|
+
return {
|
|
1795
|
+
pagination: {
|
|
1796
|
+
total,
|
|
1797
|
+
page: pagination.page,
|
|
1798
|
+
perPage: pagination.perPage,
|
|
1799
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1800
|
+
},
|
|
1801
|
+
scores
|
|
1802
|
+
};
|
|
1803
|
+
} catch (error$1) {
|
|
1804
|
+
throw new error.MastraError(
|
|
1805
|
+
{
|
|
1806
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
|
|
1807
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1808
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1809
|
+
},
|
|
1810
|
+
error$1
|
|
1811
|
+
);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
async getScoresBySpan({
|
|
1815
|
+
traceId,
|
|
1816
|
+
spanId,
|
|
1817
|
+
pagination
|
|
1818
|
+
}) {
|
|
1819
|
+
try {
|
|
1820
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1821
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
|
|
1822
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1823
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1824
|
+
if (total === 0) {
|
|
1825
|
+
return {
|
|
1826
|
+
pagination: {
|
|
1827
|
+
total: 0,
|
|
1828
|
+
page: pagination.page,
|
|
1829
|
+
perPage: pagination.perPage,
|
|
1830
|
+
hasMore: false
|
|
1831
|
+
},
|
|
1832
|
+
scores: []
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
const limit = pagination.perPage + 1;
|
|
1836
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
|
|
1837
|
+
const { sql, params } = selectQuery.build();
|
|
1838
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1839
|
+
const rows = Array.isArray(results) ? results : [];
|
|
1840
|
+
const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
|
|
1841
|
+
return {
|
|
1842
|
+
pagination: {
|
|
1843
|
+
total,
|
|
1844
|
+
page: pagination.page,
|
|
1845
|
+
perPage: pagination.perPage,
|
|
1846
|
+
hasMore: rows.length > pagination.perPage
|
|
1847
|
+
},
|
|
1848
|
+
scores
|
|
1849
|
+
};
|
|
1850
|
+
} catch (error$1) {
|
|
1851
|
+
throw new error.MastraError(
|
|
1852
|
+
{
|
|
1853
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
|
|
1854
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1855
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1856
|
+
},
|
|
1857
|
+
error$1
|
|
1858
|
+
);
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
};
|
|
1862
|
+
var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
|
|
1863
|
+
operations;
|
|
1864
|
+
constructor({ operations }) {
|
|
1865
|
+
super();
|
|
1866
|
+
this.operations = operations;
|
|
1867
|
+
}
|
|
1868
|
+
updateWorkflowResults({
|
|
1869
|
+
// workflowName,
|
|
1870
|
+
// runId,
|
|
1871
|
+
// stepId,
|
|
1872
|
+
// result,
|
|
1873
|
+
// runtimeContext,
|
|
1874
|
+
}) {
|
|
1875
|
+
throw new Error("Method not implemented.");
|
|
1876
|
+
}
|
|
1877
|
+
updateWorkflowState({
|
|
1878
|
+
// workflowName,
|
|
1879
|
+
// runId,
|
|
1880
|
+
// opts,
|
|
1881
|
+
}) {
|
|
1882
|
+
throw new Error("Method not implemented.");
|
|
1883
|
+
}
|
|
1884
|
+
async persistWorkflowSnapshot({
|
|
1885
|
+
workflowName,
|
|
1886
|
+
runId,
|
|
1887
|
+
resourceId,
|
|
1888
|
+
snapshot
|
|
1889
|
+
}) {
|
|
1890
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1891
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1892
|
+
const currentSnapshot = await this.operations.load({
|
|
1893
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
1894
|
+
keys: { workflow_name: workflowName, run_id: runId }
|
|
1895
|
+
});
|
|
1896
|
+
const persisting = currentSnapshot ? {
|
|
1897
|
+
...currentSnapshot,
|
|
1898
|
+
resourceId,
|
|
1899
|
+
snapshot: JSON.stringify(snapshot),
|
|
1900
|
+
updatedAt: now
|
|
1901
|
+
} : {
|
|
1902
|
+
workflow_name: workflowName,
|
|
1903
|
+
run_id: runId,
|
|
1904
|
+
resourceId,
|
|
1905
|
+
snapshot,
|
|
1906
|
+
createdAt: now,
|
|
1907
|
+
updatedAt: now
|
|
1908
|
+
};
|
|
1909
|
+
const processedRecord = await this.operations.processRecord(persisting);
|
|
1910
|
+
const columns = Object.keys(processedRecord);
|
|
1911
|
+
const values = Object.values(processedRecord);
|
|
1912
|
+
const updateMap = {
|
|
1913
|
+
snapshot: "excluded.snapshot",
|
|
1914
|
+
updatedAt: "excluded.updatedAt"
|
|
1915
|
+
};
|
|
1916
|
+
this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
|
|
1917
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
|
|
1918
|
+
const { sql, params } = query.build();
|
|
1919
|
+
try {
|
|
1920
|
+
await this.operations.executeQuery({ sql, params });
|
|
1921
|
+
} catch (error$1) {
|
|
1922
|
+
throw new error.MastraError(
|
|
1923
|
+
{
|
|
1924
|
+
id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
|
|
1925
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1926
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1927
|
+
text: `Failed to persist workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1928
|
+
details: { workflowName, runId }
|
|
1929
|
+
},
|
|
1930
|
+
error$1
|
|
1931
|
+
);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
async loadWorkflowSnapshot(params) {
|
|
1935
|
+
const { workflowName, runId } = params;
|
|
1936
|
+
this.logger.debug("Loading workflow snapshot", { workflowName, runId });
|
|
1937
|
+
try {
|
|
1938
|
+
const d = await this.operations.load({
|
|
1939
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
1940
|
+
keys: {
|
|
1941
|
+
workflow_name: workflowName,
|
|
1942
|
+
run_id: runId
|
|
1943
|
+
}
|
|
1944
|
+
});
|
|
1945
|
+
return d ? d.snapshot : null;
|
|
1946
|
+
} catch (error$1) {
|
|
1947
|
+
throw new error.MastraError(
|
|
1948
|
+
{
|
|
1949
|
+
id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
|
|
1950
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1951
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1952
|
+
text: `Failed to load workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1953
|
+
details: { workflowName, runId }
|
|
1954
|
+
},
|
|
1955
|
+
error$1
|
|
1956
|
+
);
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
parseWorkflowRun(row) {
|
|
1960
|
+
let parsedSnapshot = row.snapshot;
|
|
1961
|
+
if (typeof parsedSnapshot === "string") {
|
|
1962
|
+
try {
|
|
1963
|
+
parsedSnapshot = JSON.parse(row.snapshot);
|
|
1964
|
+
} catch (e) {
|
|
1965
|
+
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
return {
|
|
1969
|
+
workflowName: row.workflow_name,
|
|
1970
|
+
runId: row.run_id,
|
|
1971
|
+
snapshot: parsedSnapshot,
|
|
1972
|
+
createdAt: storage.ensureDate(row.createdAt),
|
|
1973
|
+
updatedAt: storage.ensureDate(row.updatedAt),
|
|
1974
|
+
resourceId: row.resourceId
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1977
|
+
async getWorkflowRuns({
|
|
1978
|
+
workflowName,
|
|
1979
|
+
fromDate,
|
|
1980
|
+
toDate,
|
|
1981
|
+
limit,
|
|
1982
|
+
offset,
|
|
1983
|
+
resourceId
|
|
1984
|
+
} = {}) {
|
|
1985
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1986
|
+
try {
|
|
1987
|
+
const builder = createSqlBuilder().select().from(fullTableName);
|
|
1988
|
+
const countBuilder = createSqlBuilder().count().from(fullTableName);
|
|
1989
|
+
if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
|
|
1990
|
+
if (resourceId) {
|
|
1991
|
+
const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
|
|
1992
|
+
if (hasResourceId) {
|
|
1993
|
+
builder.whereAnd("resourceId = ?", resourceId);
|
|
1994
|
+
countBuilder.whereAnd("resourceId = ?", resourceId);
|
|
1995
|
+
} else {
|
|
1996
|
+
console.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
if (fromDate) {
|
|
2000
|
+
builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
|
|
2001
|
+
countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
|
|
2002
|
+
}
|
|
2003
|
+
if (toDate) {
|
|
2004
|
+
builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
2005
|
+
countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
2006
|
+
}
|
|
2007
|
+
builder.orderBy("createdAt", "DESC");
|
|
2008
|
+
if (typeof limit === "number") builder.limit(limit);
|
|
2009
|
+
if (typeof offset === "number") builder.offset(offset);
|
|
2010
|
+
const { sql, params } = builder.build();
|
|
2011
|
+
let total = 0;
|
|
2012
|
+
if (limit !== void 0 && offset !== void 0) {
|
|
2013
|
+
const { sql: countSql, params: countParams } = countBuilder.build();
|
|
2014
|
+
const countResult = await this.operations.executeQuery({
|
|
2015
|
+
sql: countSql,
|
|
2016
|
+
params: countParams,
|
|
2017
|
+
first: true
|
|
2018
|
+
});
|
|
2019
|
+
total = Number(countResult?.count ?? 0);
|
|
2020
|
+
}
|
|
2021
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
2022
|
+
const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
|
|
2023
|
+
return { runs, total: total || runs.length };
|
|
2024
|
+
} catch (error$1) {
|
|
2025
|
+
throw new error.MastraError(
|
|
2026
|
+
{
|
|
2027
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
|
|
2028
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2029
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2030
|
+
text: `Failed to retrieve workflow runs: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
2031
|
+
details: {
|
|
2032
|
+
workflowName: workflowName ?? "",
|
|
2033
|
+
resourceId: resourceId ?? ""
|
|
2034
|
+
}
|
|
2035
|
+
},
|
|
2036
|
+
error$1
|
|
2037
|
+
);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
async getWorkflowRunById({
|
|
2041
|
+
runId,
|
|
2042
|
+
workflowName
|
|
2043
|
+
}) {
|
|
2044
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
2045
|
+
try {
|
|
2046
|
+
const conditions = [];
|
|
2047
|
+
const params = [];
|
|
2048
|
+
if (runId) {
|
|
2049
|
+
conditions.push("run_id = ?");
|
|
2050
|
+
params.push(runId);
|
|
2051
|
+
}
|
|
2052
|
+
if (workflowName) {
|
|
2053
|
+
conditions.push("workflow_name = ?");
|
|
2054
|
+
params.push(workflowName);
|
|
2055
|
+
}
|
|
2056
|
+
const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
|
2057
|
+
const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
|
|
2058
|
+
const result = await this.operations.executeQuery({ sql, params, first: true });
|
|
2059
|
+
if (!result) return null;
|
|
2060
|
+
return this.parseWorkflowRun(result);
|
|
2061
|
+
} catch (error$1) {
|
|
2062
|
+
throw new error.MastraError(
|
|
2063
|
+
{
|
|
2064
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
|
|
2065
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2066
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2067
|
+
text: `Failed to retrieve workflow run by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
2068
|
+
details: { runId, workflowName: workflowName ?? "" }
|
|
2069
|
+
},
|
|
2070
|
+
error$1
|
|
2071
|
+
);
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
};
|
|
2075
|
+
|
|
2076
|
+
// src/storage/index.ts
|
|
2077
|
+
var D1Store = class extends storage.MastraStorage {
|
|
2078
|
+
client;
|
|
2079
|
+
binding;
|
|
2080
|
+
// D1Database binding
|
|
2081
|
+
tablePrefix;
|
|
2082
|
+
stores;
|
|
2083
|
+
/**
|
|
2084
|
+
* Creates a new D1Store instance
|
|
2085
|
+
* @param config Configuration for D1 access (either REST API or Workers Binding API)
|
|
2086
|
+
*/
|
|
2087
|
+
constructor(config) {
|
|
2088
|
+
try {
|
|
2089
|
+
super({ name: "D1" });
|
|
2090
|
+
if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
|
|
2091
|
+
throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
|
|
2092
|
+
}
|
|
2093
|
+
this.tablePrefix = config.tablePrefix || "";
|
|
2094
|
+
if ("binding" in config) {
|
|
2095
|
+
if (!config.binding) {
|
|
2096
|
+
throw new Error("D1 binding is required when using Workers Binding API");
|
|
2097
|
+
}
|
|
2098
|
+
this.binding = config.binding;
|
|
2099
|
+
this.logger.info("Using D1 Workers Binding API");
|
|
2100
|
+
} else if ("client" in config) {
|
|
2101
|
+
if (!config.client) {
|
|
2102
|
+
throw new Error("D1 client is required when using D1ClientConfig");
|
|
2103
|
+
}
|
|
2104
|
+
this.client = config.client;
|
|
2105
|
+
this.logger.info("Using D1 Client");
|
|
2106
|
+
} else {
|
|
2107
|
+
if (!config.accountId || !config.databaseId || !config.apiToken) {
|
|
2108
|
+
throw new Error("accountId, databaseId, and apiToken are required when using REST API");
|
|
2109
|
+
}
|
|
2110
|
+
const cfClient = new Cloudflare__default.default({
|
|
2111
|
+
apiToken: config.apiToken
|
|
2112
|
+
});
|
|
2113
|
+
this.client = {
|
|
2114
|
+
query: ({ sql, params }) => {
|
|
2115
|
+
return cfClient.d1.database.query(config.databaseId, {
|
|
2116
|
+
account_id: config.accountId,
|
|
2117
|
+
sql,
|
|
2118
|
+
params
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
this.logger.info("Using D1 REST API");
|
|
2123
|
+
}
|
|
2124
|
+
} catch (error$1) {
|
|
2125
|
+
throw new error.MastraError(
|
|
2126
|
+
{
|
|
2127
|
+
id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
|
|
2128
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2129
|
+
category: error.ErrorCategory.SYSTEM,
|
|
2130
|
+
text: "Error initializing D1Store"
|
|
2131
|
+
},
|
|
2132
|
+
error$1
|
|
2133
|
+
);
|
|
2134
|
+
}
|
|
2135
|
+
const operations = new StoreOperationsD1({
|
|
2136
|
+
client: this.client,
|
|
2137
|
+
binding: this.binding,
|
|
2138
|
+
tablePrefix: this.tablePrefix
|
|
2139
|
+
});
|
|
2140
|
+
const scores = new ScoresStorageD1({
|
|
2141
|
+
operations
|
|
2142
|
+
});
|
|
2143
|
+
const legacyEvals = new LegacyEvalsStorageD1({
|
|
2144
|
+
operations
|
|
2145
|
+
});
|
|
2146
|
+
const workflows = new WorkflowsStorageD1({
|
|
2147
|
+
operations
|
|
2148
|
+
});
|
|
2149
|
+
const memory = new MemoryStorageD1({
|
|
2150
|
+
operations
|
|
2151
|
+
});
|
|
2152
|
+
this.stores = {
|
|
2153
|
+
operations,
|
|
2154
|
+
scores,
|
|
2155
|
+
legacyEvals,
|
|
2156
|
+
workflows,
|
|
2157
|
+
memory
|
|
2158
|
+
};
|
|
2159
|
+
}
|
|
2160
|
+
get supports() {
|
|
2161
|
+
return {
|
|
2162
|
+
selectByIncludeResourceScope: true,
|
|
2163
|
+
resourceWorkingMemory: true,
|
|
2164
|
+
hasColumn: true,
|
|
2165
|
+
createTable: true,
|
|
2166
|
+
deleteMessages: false,
|
|
2167
|
+
getScoresBySpan: true
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
async createTable({
|
|
2171
|
+
tableName,
|
|
2172
|
+
schema
|
|
2173
|
+
}) {
|
|
2174
|
+
return this.stores.operations.createTable({ tableName, schema });
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* Alters table schema to add columns if they don't exist
|
|
2178
|
+
* @param tableName Name of the table
|
|
2179
|
+
* @param schema Schema of the table
|
|
2180
|
+
* @param ifNotExists Array of column names to add if they don't exist
|
|
2181
|
+
*/
|
|
2182
|
+
async alterTable({
|
|
2183
|
+
tableName,
|
|
2184
|
+
schema,
|
|
2185
|
+
ifNotExists
|
|
2186
|
+
}) {
|
|
2187
|
+
return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
|
|
2188
|
+
}
|
|
2189
|
+
async clearTable({ tableName }) {
|
|
2190
|
+
return this.stores.operations.clearTable({ tableName });
|
|
2191
|
+
}
|
|
2192
|
+
async dropTable({ tableName }) {
|
|
2193
|
+
return this.stores.operations.dropTable({ tableName });
|
|
2194
|
+
}
|
|
2195
|
+
async hasColumn(table, column) {
|
|
2196
|
+
return this.stores.operations.hasColumn(table, column);
|
|
2197
|
+
}
|
|
2198
|
+
async insert({ tableName, record }) {
|
|
2199
|
+
return this.stores.operations.insert({ tableName, record });
|
|
2200
|
+
}
|
|
2201
|
+
async load({ tableName, keys }) {
|
|
2202
|
+
return this.stores.operations.load({ tableName, keys });
|
|
2203
|
+
}
|
|
2204
|
+
async getThreadById({ threadId }) {
|
|
2205
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
2206
|
+
}
|
|
2207
|
+
/**
|
|
2208
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
2209
|
+
*/
|
|
2210
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
2211
|
+
return this.stores.memory.getThreadsByResourceId({ resourceId });
|
|
2212
|
+
}
|
|
2213
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
2214
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
2215
|
+
}
|
|
2216
|
+
async saveThread({ thread }) {
|
|
2217
|
+
return this.stores.memory.saveThread({ thread });
|
|
2218
|
+
}
|
|
2219
|
+
async updateThread({
|
|
2220
|
+
id,
|
|
2221
|
+
title,
|
|
2222
|
+
metadata
|
|
2223
|
+
}) {
|
|
2224
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
2225
|
+
}
|
|
2226
|
+
async deleteThread({ threadId }) {
|
|
2227
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
2228
|
+
}
|
|
2229
|
+
async saveMessages(args) {
|
|
2230
|
+
return this.stores.memory.saveMessages(args);
|
|
2231
|
+
}
|
|
2232
|
+
async getMessages({
|
|
2233
|
+
threadId,
|
|
2234
|
+
selectBy,
|
|
2235
|
+
format
|
|
2236
|
+
}) {
|
|
2237
|
+
return this.stores.memory.getMessages({ threadId, selectBy, format });
|
|
2238
|
+
}
|
|
2239
|
+
async getMessagesById({
|
|
2240
|
+
messageIds,
|
|
2241
|
+
format
|
|
2242
|
+
}) {
|
|
2243
|
+
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
2244
|
+
}
|
|
2245
|
+
async getMessagesPaginated({
|
|
2246
|
+
threadId,
|
|
2247
|
+
selectBy,
|
|
2248
|
+
format
|
|
2249
|
+
}) {
|
|
2250
|
+
return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
|
|
2251
|
+
}
|
|
2252
|
+
async updateWorkflowResults({
|
|
2253
|
+
workflowName,
|
|
2254
|
+
runId,
|
|
2255
|
+
stepId,
|
|
2256
|
+
result,
|
|
2257
|
+
runtimeContext
|
|
2258
|
+
}) {
|
|
2259
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
|
|
2260
|
+
}
|
|
2261
|
+
async updateWorkflowState({
|
|
2262
|
+
workflowName,
|
|
2263
|
+
runId,
|
|
2264
|
+
opts
|
|
2265
|
+
}) {
|
|
2266
|
+
return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
|
|
2267
|
+
}
|
|
2268
|
+
async persistWorkflowSnapshot({
|
|
2269
|
+
workflowName,
|
|
2270
|
+
runId,
|
|
2271
|
+
resourceId,
|
|
2272
|
+
snapshot
|
|
2273
|
+
}) {
|
|
2274
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
|
|
2275
|
+
}
|
|
2276
|
+
async loadWorkflowSnapshot(params) {
|
|
2277
|
+
return this.stores.workflows.loadWorkflowSnapshot(params);
|
|
2278
|
+
}
|
|
2279
|
+
async getWorkflowRuns({
|
|
2280
|
+
workflowName,
|
|
2281
|
+
fromDate,
|
|
2282
|
+
toDate,
|
|
2283
|
+
limit,
|
|
2284
|
+
offset,
|
|
2285
|
+
resourceId
|
|
2286
|
+
} = {}) {
|
|
2287
|
+
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
2288
|
+
}
|
|
2289
|
+
async getWorkflowRunById({
|
|
2290
|
+
runId,
|
|
2291
|
+
workflowName
|
|
2292
|
+
}) {
|
|
2293
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
2294
|
+
}
|
|
2295
|
+
/**
|
|
2296
|
+
* Insert multiple records in a batch operation
|
|
2297
|
+
* @param tableName The table to insert into
|
|
2298
|
+
* @param records The records to insert
|
|
2299
|
+
*/
|
|
2300
|
+
async batchInsert({ tableName, records }) {
|
|
2301
|
+
return this.stores.operations.batchInsert({ tableName, records });
|
|
2302
|
+
}
|
|
2303
|
+
/**
|
|
2304
|
+
* @deprecated use getEvals instead
|
|
2305
|
+
*/
|
|
2306
|
+
async getEvalsByAgentName(agentName, type) {
|
|
2307
|
+
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
2308
|
+
}
|
|
2309
|
+
async getEvals(options) {
|
|
2310
|
+
return this.stores.legacyEvals.getEvals(options);
|
|
2311
|
+
}
|
|
2312
|
+
async updateMessages(_args) {
|
|
2313
|
+
return this.stores.memory.updateMessages(_args);
|
|
2314
|
+
}
|
|
2315
|
+
async getResourceById({ resourceId }) {
|
|
2316
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
2317
|
+
}
|
|
2318
|
+
async saveResource({ resource }) {
|
|
2319
|
+
return this.stores.memory.saveResource({ resource });
|
|
2320
|
+
}
|
|
2321
|
+
async updateResource({
|
|
2322
|
+
resourceId,
|
|
2323
|
+
workingMemory,
|
|
2324
|
+
metadata
|
|
2325
|
+
}) {
|
|
2326
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
2327
|
+
}
|
|
2328
|
+
async getScoreById({ id: _id }) {
|
|
2329
|
+
return this.stores.scores.getScoreById({ id: _id });
|
|
2330
|
+
}
|
|
2331
|
+
async saveScore(_score) {
|
|
2332
|
+
return this.stores.scores.saveScore(_score);
|
|
2333
|
+
}
|
|
2334
|
+
async getScoresByRunId({
|
|
2335
|
+
runId: _runId,
|
|
2336
|
+
pagination: _pagination
|
|
2337
|
+
}) {
|
|
2338
|
+
return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
2339
|
+
}
|
|
2340
|
+
async getScoresByEntityId({
|
|
2341
|
+
entityId: _entityId,
|
|
2342
|
+
entityType: _entityType,
|
|
2343
|
+
pagination: _pagination
|
|
2344
|
+
}) {
|
|
2345
|
+
return this.stores.scores.getScoresByEntityId({
|
|
2346
|
+
entityId: _entityId,
|
|
2347
|
+
entityType: _entityType,
|
|
2348
|
+
pagination: _pagination
|
|
2349
|
+
});
|
|
2350
|
+
}
|
|
2351
|
+
async getScoresByScorerId({
|
|
2352
|
+
scorerId,
|
|
2353
|
+
pagination,
|
|
2354
|
+
entityId,
|
|
2355
|
+
entityType,
|
|
2356
|
+
source
|
|
2357
|
+
}) {
|
|
2358
|
+
return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
2359
|
+
}
|
|
2360
|
+
async getScoresBySpan({
|
|
2361
|
+
traceId,
|
|
2362
|
+
spanId,
|
|
2363
|
+
pagination
|
|
2364
|
+
}) {
|
|
2365
|
+
return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
|
|
934
2366
|
}
|
|
935
2367
|
/**
|
|
936
2368
|
* Close the database connection
|
|
@@ -942,3 +2374,5 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
942
2374
|
};
|
|
943
2375
|
|
|
944
2376
|
exports.D1Store = D1Store;
|
|
2377
|
+
//# sourceMappingURL=index.cjs.map
|
|
2378
|
+
//# sourceMappingURL=index.cjs.map
|