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