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