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