@mastra/cloudflare 1.6.0-alpha.0 → 1.6.0

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.
@@ -1,2435 +0,0 @@
1
- 'use strict';
2
-
3
- var error = require('@mastra/core/error');
4
- var storage = require('@mastra/core/storage');
5
- var Cloudflare = require('cloudflare');
6
- var base = require('@mastra/core/base');
7
- var agent = require('@mastra/core/agent');
8
- var evals = require('@mastra/core/evals');
9
-
10
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- var Cloudflare__default = /*#__PURE__*/_interopDefault(Cloudflare);
13
-
14
- // src/kv/index.ts
15
- function resolveCloudflareConfig(config) {
16
- if ("client" in config) {
17
- return {
18
- client: config.client,
19
- accountId: config.accountId,
20
- namespacePrefix: config.namespacePrefix
21
- };
22
- }
23
- if ("bindings" in config) {
24
- return {
25
- bindings: config.bindings,
26
- namespacePrefix: config.keyPrefix
27
- };
28
- }
29
- return {
30
- client: new Cloudflare__default.default({ apiToken: config.apiToken }),
31
- accountId: config.accountId,
32
- namespacePrefix: config.namespacePrefix
33
- };
34
- }
35
- var CloudflareKVDB = class extends base.MastraBase {
36
- bindings;
37
- client;
38
- accountId;
39
- namespacePrefix;
40
- constructor(config) {
41
- super({
42
- component: "STORAGE",
43
- name: "CLOUDFLARE_KV_DB"
44
- });
45
- this.bindings = config.bindings;
46
- this.namespacePrefix = config.namespacePrefix || "";
47
- this.client = config.client;
48
- this.accountId = config.accountId;
49
- }
50
- getBinding(tableName) {
51
- if (!this.bindings) {
52
- throw new Error(`Cannot use Workers API binding for ${tableName}: Store initialized with REST API configuration`);
53
- }
54
- const binding = this.bindings[tableName];
55
- if (!binding) throw new Error(`No binding found for namespace ${tableName}`);
56
- return binding;
57
- }
58
- getKey(tableName, record) {
59
- const prefix = this.namespacePrefix ? `${this.namespacePrefix}:` : "";
60
- switch (tableName) {
61
- case storage.TABLE_THREADS:
62
- if (!record.id) throw new Error("Thread ID is required");
63
- return `${prefix}${tableName}:${record.id}`;
64
- case storage.TABLE_MESSAGES:
65
- if (!record.threadId || !record.id) throw new Error("Thread ID and Message ID are required");
66
- return `${prefix}${tableName}:${record.threadId}:${record.id}`;
67
- case storage.TABLE_WORKFLOW_SNAPSHOT:
68
- if (!record.workflow_name || !record.run_id) {
69
- throw new Error("Workflow name, and run ID are required");
70
- }
71
- let key = `${prefix}${tableName}:${record.workflow_name}:${record.run_id}`;
72
- if (record.resourceId) {
73
- key = `${key}:${record.resourceId}`;
74
- }
75
- return key;
76
- case storage.TABLE_TRACES:
77
- if (!record.id) throw new Error("Trace ID is required");
78
- return `${prefix}${tableName}:${record.id}`;
79
- case storage.TABLE_SCORERS:
80
- if (!record.id) throw new Error("Score ID is required");
81
- return `${prefix}${tableName}:${record.id}`;
82
- default:
83
- throw new Error(`Unsupported table: ${tableName}`);
84
- }
85
- }
86
- getSchemaKey(tableName) {
87
- const prefix = this.namespacePrefix ? `${this.namespacePrefix}:` : "";
88
- return `${prefix}schema:${tableName}`;
89
- }
90
- /**
91
- * Helper to safely parse data from KV storage
92
- */
93
- safeParse(text) {
94
- if (!text) return null;
95
- try {
96
- const data = JSON.parse(text);
97
- if (data && typeof data === "object" && "value" in data) {
98
- if (typeof data.value === "string") {
99
- try {
100
- return JSON.parse(data.value);
101
- } catch {
102
- return data.value;
103
- }
104
- }
105
- return null;
106
- }
107
- return data;
108
- } catch (error) {
109
- const message = error instanceof Error ? error.message : String(error);
110
- this.logger.error("Failed to parse text:", { message, text });
111
- return null;
112
- }
113
- }
114
- async createNamespaceById(title) {
115
- if (this.bindings) {
116
- return {
117
- id: title,
118
- title,
119
- supports_url_encoding: true
120
- };
121
- }
122
- return await this.client.kv.namespaces.create({
123
- account_id: this.accountId,
124
- title
125
- });
126
- }
127
- async createNamespace(namespaceName) {
128
- try {
129
- const response = await this.createNamespaceById(namespaceName);
130
- return response.id;
131
- } catch (error) {
132
- if (error.message && error.message.includes("already exists")) {
133
- const namespaces = await this.listNamespaces();
134
- const namespace = namespaces.result.find((ns) => ns.title === namespaceName);
135
- if (namespace) return namespace.id;
136
- }
137
- this.logger.error("Error creating namespace:", error);
138
- throw new Error(`Failed to create namespace ${namespaceName}: ${error.message}`);
139
- }
140
- }
141
- async listNamespaces() {
142
- if (this.bindings) {
143
- return {
144
- result: Object.keys(this.bindings).map((name) => ({
145
- id: name,
146
- title: name,
147
- supports_url_encoding: true
148
- }))
149
- };
150
- }
151
- let allNamespaces = [];
152
- let currentPage = 1;
153
- const perPage = 50;
154
- let morePagesExist = true;
155
- while (morePagesExist) {
156
- const response = await this.client.kv.namespaces.list({
157
- account_id: this.accountId,
158
- page: currentPage,
159
- per_page: perPage
160
- });
161
- if (response.result) {
162
- allNamespaces = allNamespaces.concat(response.result);
163
- }
164
- morePagesExist = response.result ? response.result.length === perPage : false;
165
- if (morePagesExist) {
166
- currentPage++;
167
- }
168
- }
169
- return { result: allNamespaces };
170
- }
171
- async getNamespaceIdByName(namespaceName) {
172
- try {
173
- const response = await this.listNamespaces();
174
- const namespace = response.result.find((ns) => ns.title === namespaceName);
175
- return namespace ? namespace.id : null;
176
- } catch (error) {
177
- this.logger.error(`Failed to get namespace ID for ${namespaceName}:`, error);
178
- return null;
179
- }
180
- }
181
- async getOrCreateNamespaceId(namespaceName) {
182
- let namespaceId = await this.getNamespaceIdByName(namespaceName);
183
- if (!namespaceId) {
184
- namespaceId = await this.createNamespace(namespaceName);
185
- }
186
- return namespaceId;
187
- }
188
- async getNamespaceId(tableName) {
189
- const prefix = this.namespacePrefix ? `${this.namespacePrefix}_` : "";
190
- try {
191
- return await this.getOrCreateNamespaceId(`${prefix}${tableName}`);
192
- } catch (error) {
193
- this.logger.error("Error fetching namespace ID:", error);
194
- throw new Error(`Failed to fetch namespace ID for table ${tableName}: ${error.message}`);
195
- }
196
- }
197
- async getNamespaceValue(tableName, key) {
198
- try {
199
- if (this.bindings) {
200
- const binding = this.getBinding(tableName);
201
- const result = await binding.getWithMetadata(key, "text");
202
- if (!result) return null;
203
- return JSON.stringify(result);
204
- } else {
205
- const namespaceId = await this.getNamespaceId(tableName);
206
- const response = await this.client.kv.namespaces.values.get(namespaceId, key, {
207
- account_id: this.accountId
208
- });
209
- return await response.text();
210
- }
211
- } catch (error) {
212
- if (error.message && error.message.includes("key not found")) {
213
- return null;
214
- }
215
- const message = error instanceof Error ? error.message : String(error);
216
- this.logger.error(`Failed to get value for ${tableName} ${key}:`, { message });
217
- throw error;
218
- }
219
- }
220
- async getKV(tableName, key) {
221
- try {
222
- const text = await this.getNamespaceValue(tableName, key);
223
- return this.safeParse(text);
224
- } catch (error) {
225
- this.logger.error(`Failed to get KV value for ${tableName}:${key}:`, error);
226
- throw new Error(`Failed to get KV value: ${error.message}`);
227
- }
228
- }
229
- async getTableSchema(tableName) {
230
- try {
231
- const schemaKey = this.getSchemaKey(tableName);
232
- return await this.getKV(tableName, schemaKey);
233
- } catch (error) {
234
- const message = error instanceof Error ? error.message : String(error);
235
- this.logger.error(`Failed to get schema for ${tableName}:`, { message });
236
- return null;
237
- }
238
- }
239
- validateColumnValue(value, column) {
240
- if (value === void 0 || value === null) {
241
- return column.nullable ?? false;
242
- }
243
- switch (column.type) {
244
- case "text":
245
- case "uuid":
246
- return typeof value === "string";
247
- case "integer":
248
- case "bigint":
249
- return typeof value === "number";
250
- case "timestamp":
251
- return value instanceof Date || typeof value === "string" && !isNaN(Date.parse(value));
252
- case "jsonb":
253
- if (typeof value !== "object") return false;
254
- try {
255
- JSON.stringify(value);
256
- return true;
257
- } catch {
258
- return false;
259
- }
260
- default:
261
- return false;
262
- }
263
- }
264
- async validateAgainstSchema(record, schema) {
265
- try {
266
- if (!schema || typeof schema !== "object" || schema.value === null) {
267
- throw new Error("Invalid schema format");
268
- }
269
- for (const [columnName, column] of Object.entries(schema)) {
270
- const value = record[columnName];
271
- if (column.primaryKey && (value === void 0 || value === null)) {
272
- throw new Error(`Missing primary key value for column ${columnName}`);
273
- }
274
- if (!this.validateColumnValue(value, column)) {
275
- const valueType = value === null ? "null" : typeof value;
276
- throw new Error(`Invalid value for column ${columnName}: expected ${column.type}, got ${valueType}`);
277
- }
278
- }
279
- } catch (error) {
280
- const message = error instanceof Error ? error.message : String(error);
281
- this.logger.error(`Error validating record against schema:`, { message, record, schema });
282
- throw error;
283
- }
284
- }
285
- async validateRecord(record, tableName) {
286
- try {
287
- if (!record || typeof record !== "object") {
288
- throw new Error("Record must be an object");
289
- }
290
- const recordTyped = record;
291
- const schema = await this.getTableSchema(tableName);
292
- if (schema) {
293
- await this.validateAgainstSchema(recordTyped, schema);
294
- return;
295
- }
296
- switch (tableName) {
297
- case storage.TABLE_THREADS:
298
- if (!("id" in recordTyped) || !("resourceId" in recordTyped) || !("title" in recordTyped)) {
299
- throw new Error("Thread record missing required fields");
300
- }
301
- break;
302
- case storage.TABLE_MESSAGES:
303
- if (!("id" in recordTyped) || !("threadId" in recordTyped) || !("content" in recordTyped) || !("role" in recordTyped)) {
304
- throw new Error("Message record missing required fields");
305
- }
306
- break;
307
- case storage.TABLE_WORKFLOW_SNAPSHOT:
308
- if (!("workflow_name" in recordTyped) || !("run_id" in recordTyped)) {
309
- throw new Error("Workflow record missing required fields");
310
- }
311
- break;
312
- case storage.TABLE_TRACES:
313
- if (!("id" in recordTyped)) {
314
- throw new Error("Trace record missing required fields");
315
- }
316
- break;
317
- case storage.TABLE_SCORERS:
318
- if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
319
- throw new Error("Score record missing required fields");
320
- }
321
- break;
322
- default:
323
- throw new Error(`Unknown table type: ${tableName}`);
324
- }
325
- } catch (error) {
326
- const message = error instanceof Error ? error.message : String(error);
327
- this.logger.error(`Failed to validate record for ${tableName}:`, { message, record });
328
- throw error;
329
- }
330
- }
331
- async insert({ tableName, record }) {
332
- try {
333
- const key = this.getKey(tableName, record);
334
- const processedRecord = { ...record };
335
- await this.validateRecord(processedRecord, tableName);
336
- await this.putKV({ tableName, key, value: processedRecord });
337
- } catch (error$1) {
338
- throw new error.MastraError(
339
- {
340
- id: storage.createStorageErrorId("CLOUDFLARE", "INSERT", "FAILED"),
341
- domain: error.ErrorDomain.STORAGE,
342
- category: error.ErrorCategory.THIRD_PARTY,
343
- details: {
344
- tableName
345
- }
346
- },
347
- error$1
348
- );
349
- }
350
- }
351
- async load({ tableName, keys }) {
352
- try {
353
- const key = this.getKey(tableName, keys);
354
- const data = await this.getKV(tableName, key);
355
- if (!data) return null;
356
- return data;
357
- } catch (error$1) {
358
- const mastraError = new error.MastraError(
359
- {
360
- id: storage.createStorageErrorId("CLOUDFLARE", "LOAD", "FAILED"),
361
- domain: error.ErrorDomain.STORAGE,
362
- category: error.ErrorCategory.THIRD_PARTY,
363
- details: {
364
- tableName
365
- }
366
- },
367
- error$1
368
- );
369
- this.logger?.trackException(mastraError);
370
- this.logger?.error(mastraError.toString());
371
- return null;
372
- }
373
- }
374
- async batchInsert(input) {
375
- if (!input.records || input.records.length === 0) return;
376
- try {
377
- await Promise.all(
378
- input.records.map(async (record) => {
379
- const key = this.getKey(input.tableName, record);
380
- await this.putKV({ tableName: input.tableName, key, value: record });
381
- })
382
- );
383
- } catch (error$1) {
384
- throw new error.MastraError(
385
- {
386
- id: storage.createStorageErrorId("CLOUDFLARE", "BATCH_INSERT", "FAILED"),
387
- domain: error.ErrorDomain.STORAGE,
388
- category: error.ErrorCategory.THIRD_PARTY,
389
- text: `Error in batch insert for table ${input.tableName}`,
390
- details: {
391
- tableName: input.tableName
392
- }
393
- },
394
- error$1
395
- );
396
- }
397
- }
398
- safeSerialize(data) {
399
- return typeof data === "string" ? data : JSON.stringify(data);
400
- }
401
- async putNamespaceValue({
402
- tableName,
403
- key,
404
- value,
405
- metadata
406
- }) {
407
- try {
408
- const serializedValue = this.safeSerialize(value);
409
- const serializedMetadata = metadata ? this.safeSerialize(metadata) : "";
410
- if (this.bindings) {
411
- const binding = this.getBinding(tableName);
412
- await binding.put(key, serializedValue, { metadata: serializedMetadata });
413
- } else {
414
- const namespaceId = await this.getNamespaceId(tableName);
415
- await this.client.kv.namespaces.values.update(namespaceId, key, {
416
- account_id: this.accountId,
417
- value: serializedValue,
418
- metadata: serializedMetadata
419
- });
420
- }
421
- } catch (error) {
422
- const message = error instanceof Error ? error.message : String(error);
423
- this.logger.error(`Failed to put value for ${tableName} ${key}:`, { message });
424
- throw error;
425
- }
426
- }
427
- async putKV({
428
- tableName,
429
- key,
430
- value,
431
- metadata
432
- }) {
433
- try {
434
- await this.putNamespaceValue({ tableName, key, value, metadata });
435
- } catch (error) {
436
- this.logger.error(`Failed to put KV value for ${tableName}:${key}:`, error);
437
- throw new Error(`Failed to put KV value: ${error.message}`);
438
- }
439
- }
440
- async createTable({
441
- tableName,
442
- schema
443
- }) {
444
- try {
445
- const schemaKey = this.getSchemaKey(tableName);
446
- const metadata = {
447
- type: "table_schema",
448
- tableName,
449
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
450
- };
451
- await this.putKV({ tableName, key: schemaKey, value: schema, metadata });
452
- } catch (error$1) {
453
- throw new error.MastraError(
454
- {
455
- id: storage.createStorageErrorId("CLOUDFLARE", "CREATE_TABLE", "FAILED"),
456
- domain: error.ErrorDomain.STORAGE,
457
- category: error.ErrorCategory.THIRD_PARTY,
458
- details: {
459
- tableName
460
- }
461
- },
462
- error$1
463
- );
464
- }
465
- }
466
- async clearTable({ tableName }) {
467
- try {
468
- const keys = await this.listKV(tableName);
469
- if (keys.length > 0) {
470
- await Promise.all(keys.map((keyObj) => this.deleteKV(tableName, keyObj.name)));
471
- }
472
- } catch (error$1) {
473
- throw new error.MastraError(
474
- {
475
- id: storage.createStorageErrorId("CLOUDFLARE", "CLEAR_TABLE", "FAILED"),
476
- domain: error.ErrorDomain.STORAGE,
477
- category: error.ErrorCategory.THIRD_PARTY,
478
- details: {
479
- tableName
480
- }
481
- },
482
- error$1
483
- );
484
- }
485
- }
486
- async dropTable({ tableName }) {
487
- try {
488
- const keys = await this.listKV(tableName);
489
- if (keys.length > 0) {
490
- await Promise.all(keys.map((keyObj) => this.deleteKV(tableName, keyObj.name)));
491
- }
492
- } catch (error$1) {
493
- throw new error.MastraError(
494
- {
495
- id: storage.createStorageErrorId("CLOUDFLARE", "DROP_TABLE", "FAILED"),
496
- domain: error.ErrorDomain.STORAGE,
497
- category: error.ErrorCategory.THIRD_PARTY,
498
- details: {
499
- tableName
500
- }
501
- },
502
- error$1
503
- );
504
- }
505
- }
506
- async listNamespaceKeys(tableName, options) {
507
- try {
508
- if (this.bindings) {
509
- const binding = this.getBinding(tableName);
510
- const response = await binding.list({
511
- limit: options?.limit || 1e3,
512
- prefix: options?.prefix
513
- });
514
- return response.keys;
515
- } else {
516
- const namespaceId = await this.getNamespaceId(tableName);
517
- const response = await this.client.kv.namespaces.keys.list(namespaceId, {
518
- account_id: this.accountId,
519
- limit: options?.limit || 1e3,
520
- prefix: options?.prefix
521
- });
522
- return response.result;
523
- }
524
- } catch (error$1) {
525
- throw new error.MastraError(
526
- {
527
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_NAMESPACE_KEYS", "FAILED"),
528
- domain: error.ErrorDomain.STORAGE,
529
- category: error.ErrorCategory.THIRD_PARTY,
530
- details: {
531
- tableName
532
- }
533
- },
534
- error$1
535
- );
536
- }
537
- }
538
- async deleteNamespaceValue(tableName, key) {
539
- if (this.bindings) {
540
- const binding = this.getBinding(tableName);
541
- await binding.delete(key);
542
- } else {
543
- const namespaceId = await this.getNamespaceId(tableName);
544
- await this.client.kv.namespaces.values.delete(namespaceId, key, {
545
- account_id: this.accountId
546
- });
547
- }
548
- }
549
- async deleteKV(tableName, key) {
550
- try {
551
- await this.deleteNamespaceValue(tableName, key);
552
- } catch (error) {
553
- this.logger.error(`Failed to delete KV value for ${tableName}:${key}:`, error);
554
- throw new Error(`Failed to delete KV value: ${error.message}`);
555
- }
556
- }
557
- async listKV(tableName, options) {
558
- try {
559
- return await this.listNamespaceKeys(tableName, options);
560
- } catch (error) {
561
- this.logger.error(`Failed to list KV for ${tableName}:`, error);
562
- throw new Error(`Failed to list KV: ${error.message}`);
563
- }
564
- }
565
- };
566
-
567
- // src/kv/storage/domains/background-tasks/index.ts
568
- function toRecord(task) {
569
- return {
570
- id: task.id,
571
- tool_call_id: task.toolCallId,
572
- tool_name: task.toolName,
573
- agent_id: task.agentId,
574
- thread_id: task.threadId ?? null,
575
- resource_id: task.resourceId ?? null,
576
- run_id: task.runId,
577
- status: task.status,
578
- args: task.args,
579
- result: task.result ?? null,
580
- error: task.error ?? null,
581
- suspend_payload: task.suspendPayload ?? null,
582
- retry_count: task.retryCount,
583
- max_retries: task.maxRetries,
584
- timeout_ms: task.timeoutMs,
585
- createdAt: task.createdAt.toISOString(),
586
- startedAt: task.startedAt?.toISOString() ?? null,
587
- suspendedAt: task.suspendedAt?.toISOString() ?? null,
588
- completedAt: task.completedAt?.toISOString() ?? null
589
- };
590
- }
591
- function fromRecord(record) {
592
- return {
593
- id: record.id,
594
- status: record.status,
595
- toolName: record.tool_name,
596
- toolCallId: record.tool_call_id,
597
- args: record.args ?? {},
598
- agentId: record.agent_id,
599
- threadId: record.thread_id ?? void 0,
600
- resourceId: record.resource_id ?? void 0,
601
- runId: record.run_id ?? "",
602
- result: record.result ?? void 0,
603
- error: record.error ?? void 0,
604
- suspendPayload: record.suspend_payload ?? void 0,
605
- retryCount: Number(record.retry_count ?? 0),
606
- maxRetries: Number(record.max_retries ?? 0),
607
- timeoutMs: Number(record.timeout_ms ?? 3e5),
608
- createdAt: new Date(record.createdAt),
609
- startedAt: record.startedAt ? new Date(record.startedAt) : void 0,
610
- suspendedAt: record.suspendedAt ? new Date(record.suspendedAt) : void 0,
611
- completedAt: record.completedAt ? new Date(record.completedAt) : void 0
612
- };
613
- }
614
- var BackgroundTasksStorageCloudflare = class extends storage.BackgroundTasksStorage {
615
- #db;
616
- constructor(config) {
617
- super();
618
- this.#db = new CloudflareKVDB(resolveCloudflareConfig(config));
619
- }
620
- async dangerouslyClearAll() {
621
- await this.#db.clearTable({ tableName: storage.TABLE_BACKGROUND_TASKS });
622
- }
623
- async createTask(task) {
624
- await this.#db.putKV({ tableName: storage.TABLE_BACKGROUND_TASKS, key: task.id, value: toRecord(task) });
625
- }
626
- async updateTask(taskId, update) {
627
- const existing = await this.getTask(taskId);
628
- if (!existing) return;
629
- const merged = { ...existing };
630
- if ("status" in update) merged.status = update.status;
631
- if ("result" in update) merged.result = update.result;
632
- if ("error" in update) merged.error = update.error;
633
- if ("suspendPayload" in update) merged.suspendPayload = update.suspendPayload;
634
- if ("retryCount" in update) merged.retryCount = update.retryCount;
635
- if ("startedAt" in update) merged.startedAt = update.startedAt;
636
- if ("suspendedAt" in update) merged.suspendedAt = update.suspendedAt;
637
- if ("completedAt" in update) merged.completedAt = update.completedAt;
638
- await this.#db.putKV({ tableName: storage.TABLE_BACKGROUND_TASKS, key: taskId, value: toRecord(merged) });
639
- }
640
- async getTask(taskId) {
641
- const data = await this.#db.getKV(storage.TABLE_BACKGROUND_TASKS, taskId);
642
- return data ? fromRecord(data) : null;
643
- }
644
- async listTasks(filter) {
645
- const keys = await this.#db.listKV(storage.TABLE_BACKGROUND_TASKS);
646
- if (keys.length === 0) return { tasks: [], total: 0 };
647
- const records = await Promise.all(keys.map((k) => this.#db.getKV(storage.TABLE_BACKGROUND_TASKS, k.name)));
648
- let tasks = records.filter(Boolean).map((r) => fromRecord(r));
649
- if (filter.status) {
650
- const s = Array.isArray(filter.status) ? filter.status : [filter.status];
651
- tasks = tasks.filter((t) => s.includes(t.status));
652
- }
653
- if (filter.agentId) tasks = tasks.filter((t) => t.agentId === filter.agentId);
654
- if (filter.threadId) tasks = tasks.filter((t) => t.threadId === filter.threadId);
655
- if (filter.toolName) tasks = tasks.filter((t) => t.toolName === filter.toolName);
656
- if (filter.toolCallId) tasks = tasks.filter((t) => t.toolCallId === filter.toolCallId);
657
- if (filter.runId) tasks = tasks.filter((t) => t.runId === filter.runId);
658
- const dateCol = filter.dateFilterBy ?? "createdAt";
659
- if (filter.fromDate) {
660
- tasks = tasks.filter((t) => {
661
- const val = t[dateCol];
662
- return val != null && val >= filter.fromDate;
663
- });
664
- }
665
- if (filter.toDate) {
666
- tasks = tasks.filter((t) => {
667
- const val = t[dateCol];
668
- return val != null && val < filter.toDate;
669
- });
670
- }
671
- const orderBy = filter.orderBy ?? "createdAt";
672
- const dir = filter.orderDirection === "desc" ? -1 : 1;
673
- tasks.sort((a, b) => ((a[orderBy]?.getTime() ?? 0) - (b[orderBy]?.getTime() ?? 0)) * dir);
674
- const total = tasks.length;
675
- if (filter.page != null && filter.perPage != null) {
676
- const start = filter.page * filter.perPage;
677
- tasks = tasks.slice(start, start + filter.perPage);
678
- } else if (filter.perPage != null) {
679
- tasks = tasks.slice(0, filter.perPage);
680
- }
681
- return { tasks, total };
682
- }
683
- async deleteTask(taskId) {
684
- await this.#db.deleteKV(storage.TABLE_BACKGROUND_TASKS, taskId);
685
- }
686
- async deleteTasks(filter) {
687
- const { tasks } = await this.listTasks(filter);
688
- await Promise.all(tasks.map((t) => this.#db.deleteKV(storage.TABLE_BACKGROUND_TASKS, t.id)));
689
- }
690
- async getRunningCount() {
691
- const { total } = await this.listTasks({ status: "running" });
692
- return total;
693
- }
694
- async getRunningCountByAgent(agentId) {
695
- const { total } = await this.listTasks({ status: "running", agentId });
696
- return total;
697
- }
698
- };
699
- var MemoryStorageCloudflare = class extends storage.MemoryStorage {
700
- #db;
701
- constructor(config) {
702
- super();
703
- this.#db = new CloudflareKVDB(resolveCloudflareConfig(config));
704
- }
705
- async init() {
706
- }
707
- async dangerouslyClearAll() {
708
- await this.#db.clearTable({ tableName: storage.TABLE_MESSAGES });
709
- await this.#db.clearTable({ tableName: storage.TABLE_THREADS });
710
- await this.#db.clearTable({ tableName: storage.TABLE_RESOURCES });
711
- }
712
- ensureMetadata(metadata) {
713
- if (!metadata) return void 0;
714
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
715
- }
716
- /**
717
- * Summarizes message content without exposing raw data (for logging).
718
- * Returns type, length, and keys only to prevent PII leakage.
719
- */
720
- summarizeMessageContent(content) {
721
- if (!content) return { type: "undefined" };
722
- if (typeof content === "string") return { type: "string", length: content.length };
723
- if (Array.isArray(content)) return { type: "array", length: content.length };
724
- if (typeof content === "object") return { type: "object", keys: Object.keys(content) };
725
- return { type: typeof content };
726
- }
727
- async getThreadById({
728
- threadId,
729
- resourceId
730
- }) {
731
- const thread = await this.#db.load({ tableName: storage.TABLE_THREADS, keys: { id: threadId } });
732
- if (!thread || resourceId !== void 0 && thread.resourceId !== resourceId) return null;
733
- try {
734
- return {
735
- ...thread,
736
- createdAt: storage.ensureDate(thread.createdAt),
737
- updatedAt: storage.ensureDate(thread.updatedAt),
738
- metadata: this.ensureMetadata(thread.metadata)
739
- };
740
- } catch (error$1) {
741
- const mastraError = new error.MastraError(
742
- {
743
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_THREAD_BY_ID", "FAILED"),
744
- domain: error.ErrorDomain.STORAGE,
745
- category: error.ErrorCategory.THIRD_PARTY,
746
- details: {
747
- threadId
748
- }
749
- },
750
- error$1
751
- );
752
- this.logger?.trackException(mastraError);
753
- this.logger?.error(mastraError.toString());
754
- return null;
755
- }
756
- }
757
- async listThreads(args) {
758
- const { page = 0, perPage: perPageInput, orderBy, filter } = args;
759
- try {
760
- this.validatePaginationInput(page, perPageInput ?? 100);
761
- } catch (error$1) {
762
- throw new error.MastraError(
763
- {
764
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_THREADS", "INVALID_PAGE"),
765
- domain: error.ErrorDomain.STORAGE,
766
- category: error.ErrorCategory.USER,
767
- details: { page, ...perPageInput !== void 0 && { perPage: perPageInput } }
768
- },
769
- error$1 instanceof Error ? error$1 : new Error("Invalid pagination parameters")
770
- );
771
- }
772
- const perPage = storage.normalizePerPage(perPageInput, 100);
773
- try {
774
- const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
775
- const { field, direction } = this.parseOrderBy(orderBy);
776
- const prefix = this.#db.namespacePrefix ? `${this.#db.namespacePrefix}:` : "";
777
- const keyObjs = await this.#db.listKV(storage.TABLE_THREADS, { prefix: `${prefix}${storage.TABLE_THREADS}` });
778
- const threads = [];
779
- for (const { name: key } of keyObjs) {
780
- const data = await this.#db.getKV(storage.TABLE_THREADS, key);
781
- if (!data) continue;
782
- if (filter?.resourceId && data.resourceId !== filter.resourceId) {
783
- continue;
784
- }
785
- if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
786
- const metadata = this.ensureMetadata(data.metadata);
787
- if (!metadata) continue;
788
- const matches = Object.entries(filter.metadata).every(([key2, value]) => metadata[key2] === value);
789
- if (!matches) continue;
790
- }
791
- threads.push(data);
792
- }
793
- threads.sort((a, b) => {
794
- const aTime = new Date(a[field] || 0).getTime();
795
- const bTime = new Date(b[field] || 0).getTime();
796
- return direction === "ASC" ? aTime - bTime : bTime - aTime;
797
- });
798
- const end = perPageInput === false ? threads.length : offset + perPage;
799
- const paginatedThreads = threads.slice(offset, end);
800
- return {
801
- page,
802
- perPage: perPageForResponse,
803
- total: threads.length,
804
- hasMore: perPageInput === false ? false : offset + perPage < threads.length,
805
- threads: paginatedThreads
806
- };
807
- } catch (error$1) {
808
- throw new error.MastraError(
809
- {
810
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_THREADS", "FAILED"),
811
- domain: error.ErrorDomain.STORAGE,
812
- category: error.ErrorCategory.THIRD_PARTY,
813
- text: "Failed to list threads with filters"
814
- },
815
- error$1
816
- );
817
- }
818
- }
819
- async saveThread({ thread }) {
820
- try {
821
- await this.#db.insert({ tableName: storage.TABLE_THREADS, record: thread });
822
- return thread;
823
- } catch (error$1) {
824
- throw new error.MastraError(
825
- {
826
- id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_THREAD", "FAILED"),
827
- domain: error.ErrorDomain.STORAGE,
828
- category: error.ErrorCategory.THIRD_PARTY,
829
- details: {
830
- threadId: thread.id
831
- }
832
- },
833
- error$1
834
- );
835
- }
836
- }
837
- async updateThread({
838
- id,
839
- title,
840
- metadata
841
- }) {
842
- try {
843
- const thread = await this.getThreadById({ threadId: id });
844
- if (!thread) {
845
- throw new Error(`Thread ${id} not found`);
846
- }
847
- const updatedThread = {
848
- ...thread,
849
- title,
850
- metadata: this.ensureMetadata({
851
- ...thread.metadata ?? {},
852
- ...metadata
853
- }),
854
- updatedAt: /* @__PURE__ */ new Date()
855
- };
856
- await this.#db.insert({ tableName: storage.TABLE_THREADS, record: updatedThread });
857
- return updatedThread;
858
- } catch (error$1) {
859
- throw new error.MastraError(
860
- {
861
- id: storage.createStorageErrorId("CLOUDFLARE", "UPDATE_THREAD", "FAILED"),
862
- domain: error.ErrorDomain.STORAGE,
863
- category: error.ErrorCategory.THIRD_PARTY,
864
- details: {
865
- threadId: id,
866
- title
867
- }
868
- },
869
- error$1
870
- );
871
- }
872
- }
873
- getMessageKey(threadId, messageId) {
874
- try {
875
- return this.#db.getKey(storage.TABLE_MESSAGES, { threadId, id: messageId });
876
- } catch (error) {
877
- const message = error instanceof Error ? error.message : String(error);
878
- this.logger?.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
879
- throw error;
880
- }
881
- }
882
- getThreadMessagesKey(threadId) {
883
- try {
884
- return this.#db.getKey(storage.TABLE_MESSAGES, { threadId, id: "messages" });
885
- } catch (error) {
886
- const message = error instanceof Error ? error.message : String(error);
887
- this.logger?.error(`Error getting thread messages key for thread ${threadId}:`, { message });
888
- throw error;
889
- }
890
- }
891
- async deleteThread({ threadId }) {
892
- try {
893
- const thread = await this.getThreadById({ threadId });
894
- if (!thread) {
895
- throw new Error(`Thread ${threadId} not found`);
896
- }
897
- const messageKeys = await this.#db.listKV(storage.TABLE_MESSAGES);
898
- const threadMessageKeys = messageKeys.filter((key) => key.name.includes(`${storage.TABLE_MESSAGES}:${threadId}:`));
899
- await Promise.all([
900
- // Delete message order
901
- this.#db.deleteKV(storage.TABLE_MESSAGES, this.getThreadMessagesKey(threadId)),
902
- // Delete all messages
903
- ...threadMessageKeys.map((key) => this.#db.deleteKV(storage.TABLE_MESSAGES, key.name)),
904
- // Delete thread
905
- this.#db.deleteKV(storage.TABLE_THREADS, this.#db.getKey(storage.TABLE_THREADS, { id: threadId }))
906
- ]);
907
- } catch (error$1) {
908
- throw new error.MastraError(
909
- {
910
- id: storage.createStorageErrorId("CLOUDFLARE", "DELETE_THREAD", "FAILED"),
911
- domain: error.ErrorDomain.STORAGE,
912
- category: error.ErrorCategory.THIRD_PARTY,
913
- details: {
914
- threadId
915
- }
916
- },
917
- error$1
918
- );
919
- }
920
- }
921
- /**
922
- * Searches all threads in the KV store to find a message by its ID.
923
- *
924
- * **Performance Warning**: This method sequentially scans all threads to locate
925
- * the message. For stores with many threads, this can result in significant
926
- * latency and API calls. When possible, callers should provide the `threadId`
927
- * directly to avoid this full scan.
928
- *
929
- * @param messageId - The globally unique message ID to search for
930
- * @returns The message with its threadId if found, null otherwise
931
- */
932
- async findMessageInAnyThread(messageId) {
933
- try {
934
- const prefix = this.#db.namespacePrefix ? `${this.#db.namespacePrefix}:` : "";
935
- const threadKeys = await this.#db.listKV(storage.TABLE_THREADS, { prefix: `${prefix}${storage.TABLE_THREADS}` });
936
- for (const { name: threadKey } of threadKeys) {
937
- const threadId = threadKey.split(":").pop();
938
- if (!threadId || threadId === "messages") continue;
939
- const messageKey = this.getMessageKey(threadId, messageId);
940
- const message = await this.#db.getKV(storage.TABLE_MESSAGES, messageKey);
941
- if (message) {
942
- return { ...message, threadId };
943
- }
944
- }
945
- return null;
946
- } catch (error) {
947
- this.logger?.error(`Error finding message ${messageId} in any thread:`, error);
948
- return null;
949
- }
950
- }
951
- /**
952
- * Queue for serializing sorted order updates.
953
- * Updates the sorted order for a given key. This operation is eventually consistent.
954
- */
955
- updateQueue = /* @__PURE__ */ new Map();
956
- async updateSorting(threadMessages) {
957
- return threadMessages.map((msg) => ({
958
- message: msg,
959
- // Use _index if available, otherwise timestamp, matching Upstash
960
- score: msg._index !== void 0 ? msg._index : msg.createdAt.getTime()
961
- })).sort((a, b) => a.score - b.score).map((item) => ({
962
- id: item.message.id,
963
- score: item.score
964
- }));
965
- }
966
- /**
967
- * Updates the sorted order for a given key. This operation is eventually consistent.
968
- * Note: Operations on the same orderKey are serialized using a queue to prevent
969
- * concurrent updates from conflicting with each other.
970
- */
971
- async updateSortedMessages(orderKey, newEntries) {
972
- const currentPromise = this.updateQueue.get(orderKey) || Promise.resolve();
973
- const nextPromise = currentPromise.then(async () => {
974
- try {
975
- const currentOrder = await this.getSortedMessages(orderKey);
976
- const orderMap = new Map(currentOrder.map((entry) => [entry.id, entry]));
977
- for (const entry of newEntries) {
978
- orderMap.set(entry.id, entry);
979
- }
980
- const updatedOrder = Array.from(orderMap.values()).sort((a, b) => a.score - b.score);
981
- await this.#db.putKV({
982
- tableName: storage.TABLE_MESSAGES,
983
- key: orderKey,
984
- value: JSON.stringify(updatedOrder)
985
- });
986
- } catch (error) {
987
- const message = error instanceof Error ? error.message : String(error);
988
- this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
989
- throw error;
990
- } finally {
991
- if (this.updateQueue.get(orderKey) === nextPromise) {
992
- this.updateQueue.delete(orderKey);
993
- }
994
- }
995
- });
996
- this.updateQueue.set(orderKey, nextPromise);
997
- return nextPromise;
998
- }
999
- async getSortedMessages(orderKey) {
1000
- const raw = await this.#db.getKV(storage.TABLE_MESSAGES, orderKey);
1001
- if (!raw) return [];
1002
- try {
1003
- const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
1004
- return Array.isArray(arr) ? arr : [];
1005
- } catch (e) {
1006
- this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
1007
- return [];
1008
- }
1009
- }
1010
- async migrateMessage(messageId, fromThreadId, toThreadId) {
1011
- try {
1012
- const oldMessageKey = this.getMessageKey(fromThreadId, messageId);
1013
- const message = await this.#db.getKV(storage.TABLE_MESSAGES, oldMessageKey);
1014
- if (!message) return;
1015
- const updatedMessage = {
1016
- ...message,
1017
- threadId: toThreadId
1018
- };
1019
- const newMessageKey = this.getMessageKey(toThreadId, messageId);
1020
- await this.#db.putKV({ tableName: storage.TABLE_MESSAGES, key: newMessageKey, value: updatedMessage });
1021
- const oldOrderKey = this.getThreadMessagesKey(fromThreadId);
1022
- const oldEntries = await this.getSortedMessages(oldOrderKey);
1023
- const filteredEntries = oldEntries.filter((entry) => entry.id !== messageId);
1024
- await this.updateSortedMessages(oldOrderKey, filteredEntries);
1025
- const newOrderKey = this.getThreadMessagesKey(toThreadId);
1026
- const newEntries = await this.getSortedMessages(newOrderKey);
1027
- const newEntry = { id: messageId, score: Date.now() };
1028
- newEntries.push(newEntry);
1029
- await this.updateSortedMessages(newOrderKey, newEntries);
1030
- await this.#db.deleteKV(storage.TABLE_MESSAGES, oldMessageKey);
1031
- } catch (error) {
1032
- this.logger?.error(`Error migrating message ${messageId} from ${fromThreadId} to ${toThreadId}:`, error);
1033
- throw error;
1034
- }
1035
- }
1036
- async saveMessages(args) {
1037
- const { messages } = args;
1038
- if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
1039
- try {
1040
- const validatedMessages = messages.map((message, index) => {
1041
- const errors = [];
1042
- if (!message.id) errors.push("id is required");
1043
- if (!message.threadId) errors.push("threadId is required");
1044
- if (!message.content) errors.push("content is required");
1045
- if (!message.role) errors.push("role is required");
1046
- if (!message.createdAt) errors.push("createdAt is required");
1047
- if (message.resourceId === null || message.resourceId === void 0) errors.push("resourceId is required");
1048
- if (errors.length > 0) {
1049
- throw new Error(`Invalid message at index ${index}: ${errors.join(", ")}`);
1050
- }
1051
- return {
1052
- ...message,
1053
- createdAt: storage.ensureDate(message.createdAt),
1054
- type: message.type || "v2",
1055
- _index: index
1056
- };
1057
- }).filter((m) => !!m);
1058
- const messageMigrationTasks = [];
1059
- for (const message of validatedMessages) {
1060
- const existingMessage = await this.findMessageInAnyThread(message.id);
1061
- this.logger?.debug(
1062
- `Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`
1063
- );
1064
- if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
1065
- this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
1066
- messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
1067
- }
1068
- }
1069
- await Promise.all(messageMigrationTasks);
1070
- const messagesByThread = validatedMessages.reduce((acc, message) => {
1071
- if (message.threadId && !acc.has(message.threadId)) {
1072
- acc.set(message.threadId, []);
1073
- }
1074
- if (message.threadId) {
1075
- acc.get(message.threadId).push(message);
1076
- }
1077
- return acc;
1078
- }, /* @__PURE__ */ new Map());
1079
- await Promise.all(
1080
- Array.from(messagesByThread.entries()).map(async ([threadId, threadMessages]) => {
1081
- try {
1082
- const thread = await this.getThreadById({ threadId });
1083
- if (!thread) {
1084
- throw new Error(`Thread ${threadId} not found`);
1085
- }
1086
- await Promise.all(
1087
- threadMessages.map(async (message) => {
1088
- const key = this.getMessageKey(threadId, message.id);
1089
- const { _index, ...cleanMessage } = message;
1090
- const serializedMessage = {
1091
- ...cleanMessage,
1092
- createdAt: storage.serializeDate(cleanMessage.createdAt)
1093
- };
1094
- this.logger?.debug(`Saving message ${message.id}`, {
1095
- contentSummary: this.summarizeMessageContent(serializedMessage.content)
1096
- });
1097
- await this.#db.putKV({ tableName: storage.TABLE_MESSAGES, key, value: serializedMessage });
1098
- })
1099
- );
1100
- const orderKey = this.getThreadMessagesKey(threadId);
1101
- const entries = await this.updateSorting(threadMessages);
1102
- await this.updateSortedMessages(orderKey, entries);
1103
- const updatedThread = {
1104
- ...thread,
1105
- updatedAt: /* @__PURE__ */ new Date()
1106
- };
1107
- await this.#db.putKV({
1108
- tableName: storage.TABLE_THREADS,
1109
- key: this.#db.getKey(storage.TABLE_THREADS, { id: threadId }),
1110
- value: updatedThread
1111
- });
1112
- } catch (error$1) {
1113
- throw new error.MastraError(
1114
- {
1115
- id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_MESSAGES", "FAILED"),
1116
- domain: error.ErrorDomain.STORAGE,
1117
- category: error.ErrorCategory.THIRD_PARTY,
1118
- details: {
1119
- threadId
1120
- }
1121
- },
1122
- error$1
1123
- );
1124
- }
1125
- })
1126
- );
1127
- const prepared = validatedMessages.map(
1128
- ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
1129
- );
1130
- const list = new agent.MessageList().add(prepared, "memory");
1131
- return { messages: list.get.all.db() };
1132
- } catch (error$1) {
1133
- throw new error.MastraError(
1134
- {
1135
- id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_MESSAGES", "FAILED"),
1136
- domain: error.ErrorDomain.STORAGE,
1137
- category: error.ErrorCategory.THIRD_PARTY
1138
- },
1139
- error$1
1140
- );
1141
- }
1142
- }
1143
- async getRank(orderKey, id) {
1144
- const order = await this.getSortedMessages(orderKey);
1145
- const index = order.findIndex((item) => item.id === id);
1146
- return index >= 0 ? index : null;
1147
- }
1148
- async getRange(orderKey, start, end) {
1149
- const order = await this.getSortedMessages(orderKey);
1150
- const actualStart = start < 0 ? Math.max(0, order.length + start) : start;
1151
- const actualEnd = end < 0 ? order.length + end : Math.min(end, order.length - 1);
1152
- const sliced = order.slice(actualStart, actualEnd + 1);
1153
- return sliced.map((item) => item.id);
1154
- }
1155
- async getLastN(orderKey, n) {
1156
- return this.getRange(orderKey, -n, -1);
1157
- }
1158
- async getFullOrder(orderKey) {
1159
- return this.getRange(orderKey, 0, -1);
1160
- }
1161
- /**
1162
- * Retrieves messages specified in the include array along with their surrounding context.
1163
- *
1164
- * **Performance Note**: When `threadId` is not provided in an include entry, this method
1165
- * must call `findMessageInAnyThread` which sequentially scans all threads in the KV store.
1166
- * For optimal performance, callers should provide `threadId` in include entries when known.
1167
- *
1168
- * @param include - Array of message IDs to include, optionally with context windows
1169
- * @param messageIds - Set to accumulate the message IDs that should be fetched
1170
- */
1171
- _sortMessages(messages, field, direction) {
1172
- return messages.sort((a, b) => {
1173
- const isDateField = field === "createdAt" || field === "updatedAt";
1174
- const aVal = isDateField ? new Date(a[field]).getTime() : a[field];
1175
- const bVal = isDateField ? new Date(b[field]).getTime() : b[field];
1176
- if (aVal == null && bVal == null) return a.id.localeCompare(b.id);
1177
- if (aVal == null) return 1;
1178
- if (bVal == null) return -1;
1179
- if (typeof aVal === "number" && typeof bVal === "number") {
1180
- const cmp2 = direction === "ASC" ? aVal - bVal : bVal - aVal;
1181
- return cmp2 !== 0 ? cmp2 : a.id.localeCompare(b.id);
1182
- }
1183
- const cmp = direction === "ASC" ? String(aVal).localeCompare(String(bVal)) : String(bVal).localeCompare(String(aVal));
1184
- return cmp !== 0 ? cmp : a.id.localeCompare(b.id);
1185
- });
1186
- }
1187
- async getIncludedMessagesWithContext(include, messageIds) {
1188
- await Promise.all(
1189
- include.map(async (item) => {
1190
- let targetThreadId = item.threadId;
1191
- if (!targetThreadId) {
1192
- const foundMessage = await this.findMessageInAnyThread(item.id);
1193
- if (!foundMessage) return;
1194
- targetThreadId = foundMessage.threadId;
1195
- }
1196
- if (!targetThreadId) return;
1197
- const threadMessagesKey = this.getThreadMessagesKey(targetThreadId);
1198
- messageIds.add(item.id);
1199
- if (!item.withPreviousMessages && !item.withNextMessages) return;
1200
- const rank = await this.getRank(threadMessagesKey, item.id);
1201
- if (rank === null) return;
1202
- if (item.withPreviousMessages) {
1203
- const prevIds = await this.getRange(
1204
- threadMessagesKey,
1205
- Math.max(0, rank - item.withPreviousMessages),
1206
- rank - 1
1207
- );
1208
- prevIds.forEach((id) => messageIds.add(id));
1209
- }
1210
- if (item.withNextMessages) {
1211
- const nextIds = await this.getRange(threadMessagesKey, rank + 1, rank + item.withNextMessages);
1212
- nextIds.forEach((id) => messageIds.add(id));
1213
- }
1214
- })
1215
- );
1216
- }
1217
- async getRecentMessages(threadId, limit, messageIds) {
1218
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1219
- if (limit <= 0) return;
1220
- try {
1221
- const threadMessagesKey = this.getThreadMessagesKey(threadId);
1222
- const latestIds = await this.getLastN(threadMessagesKey, limit);
1223
- latestIds.forEach((id) => messageIds.add(id));
1224
- } catch {
1225
- this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
1226
- }
1227
- }
1228
- /**
1229
- * Fetches and parses messages from one or more threads.
1230
- *
1231
- * **Performance Note**: When neither `include` entries with `threadId` nor `targetThreadId`
1232
- * are provided, this method falls back to `findMessageInAnyThread` which scans all threads.
1233
- * For optimal performance, provide `threadId` in include entries or specify `targetThreadId`.
1234
- */
1235
- async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
1236
- const messageIdToThreadId = /* @__PURE__ */ new Map();
1237
- if (include) {
1238
- for (const item of include) {
1239
- if (item.threadId) {
1240
- messageIdToThreadId.set(item.id, item.threadId);
1241
- }
1242
- }
1243
- }
1244
- const messages = await Promise.all(
1245
- messageIds.map(async (id) => {
1246
- try {
1247
- let threadId = messageIdToThreadId.get(id);
1248
- if (!threadId) {
1249
- if (targetThreadId) {
1250
- threadId = targetThreadId;
1251
- } else {
1252
- const foundMessage = await this.findMessageInAnyThread(id);
1253
- if (foundMessage) {
1254
- threadId = foundMessage.threadId;
1255
- }
1256
- }
1257
- }
1258
- if (!threadId) return null;
1259
- const key = this.getMessageKey(threadId, id);
1260
- const data = await this.#db.getKV(storage.TABLE_MESSAGES, key);
1261
- if (!data) return null;
1262
- const parsed = typeof data === "string" ? JSON.parse(data) : data;
1263
- this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
1264
- contentSummary: this.summarizeMessageContent(parsed.content)
1265
- });
1266
- return parsed;
1267
- } catch (error) {
1268
- const message = error instanceof Error ? error.message : String(error);
1269
- this.logger?.error(`Error retrieving message ${id}:`, { message });
1270
- return null;
1271
- }
1272
- })
1273
- );
1274
- return messages.filter((msg) => msg !== null);
1275
- }
1276
- /**
1277
- * Retrieves messages by their IDs.
1278
- *
1279
- * **Performance Warning**: This method calls `findMessageInAnyThread` for each message ID,
1280
- * which scans all threads in the KV store. For large numbers of messages or threads,
1281
- * this can result in significant latency. Consider using `listMessages` with specific
1282
- * thread IDs when the thread context is known.
1283
- */
1284
- async listMessagesById({ messageIds }) {
1285
- if (messageIds.length === 0) return { messages: [] };
1286
- try {
1287
- const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
1288
- (result) => !!result
1289
- );
1290
- const prepared = messages.map(({ _index, ...message }) => ({
1291
- ...message,
1292
- ...message.type !== `v2` && { type: message.type },
1293
- createdAt: storage.ensureDate(message.createdAt)
1294
- }));
1295
- const list = new agent.MessageList().add(prepared, "memory");
1296
- return { messages: list.get.all.db() };
1297
- } catch (error$1) {
1298
- const mastraError = new error.MastraError(
1299
- {
1300
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES_BY_ID", "FAILED"),
1301
- domain: error.ErrorDomain.STORAGE,
1302
- category: error.ErrorCategory.THIRD_PARTY,
1303
- text: `Error retrieving messages by ID`,
1304
- details: {
1305
- messageIds: JSON.stringify(messageIds)
1306
- }
1307
- },
1308
- error$1
1309
- );
1310
- this.logger?.trackException(mastraError);
1311
- this.logger?.error(mastraError.toString());
1312
- return { messages: [] };
1313
- }
1314
- }
1315
- async listMessages(args) {
1316
- const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1317
- const threadIds = Array.isArray(threadId) ? threadId : [threadId];
1318
- const isValidThreadId = (id) => typeof id === "string" && id.trim().length > 0;
1319
- if (threadIds.length === 0 || threadIds.some((id) => !isValidThreadId(id))) {
1320
- throw new error.MastraError(
1321
- {
1322
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "INVALID_THREAD_ID"),
1323
- domain: error.ErrorDomain.STORAGE,
1324
- category: error.ErrorCategory.THIRD_PARTY,
1325
- details: { threadId: Array.isArray(threadId) ? JSON.stringify(threadId) : String(threadId) }
1326
- },
1327
- new Error("threadId must be a non-empty string or array of non-empty strings")
1328
- );
1329
- }
1330
- const perPage = storage.normalizePerPage(perPageInput, 40);
1331
- const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1332
- const metadataFilter = storage.validateStorageMetadataFilter(filter?.metadata);
1333
- try {
1334
- if (page < 0) {
1335
- throw new error.MastraError(
1336
- {
1337
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "INVALID_PAGE"),
1338
- domain: error.ErrorDomain.STORAGE,
1339
- category: error.ErrorCategory.USER,
1340
- details: { page }
1341
- },
1342
- new Error("page must be >= 0")
1343
- );
1344
- }
1345
- const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1346
- if (perPage === 0 && include && include.length > 0) {
1347
- const includedMessageIds = /* @__PURE__ */ new Set();
1348
- await this.getIncludedMessagesWithContext(include, includedMessageIds);
1349
- const includedMessages2 = await this.fetchAndParseMessagesFromMultipleThreads(
1350
- Array.from(includedMessageIds),
1351
- include,
1352
- void 0
1353
- );
1354
- const list2 = new agent.MessageList().add(includedMessages2, "memory");
1355
- return {
1356
- messages: this._sortMessages(list2.get.all.db(), field, direction),
1357
- total: 0,
1358
- page,
1359
- perPage: perPageForResponse,
1360
- hasMore: false
1361
- };
1362
- }
1363
- if (perPage === 0 && (!include || include.length === 0)) {
1364
- return { messages: [], total: 0, page, perPage: perPageForResponse, hasMore: false };
1365
- }
1366
- const threadMessageIds = /* @__PURE__ */ new Set();
1367
- for (const tid of threadIds) {
1368
- try {
1369
- const threadMessagesKey = this.getThreadMessagesKey(tid);
1370
- const allIds = await this.getFullOrder(threadMessagesKey);
1371
- allIds.forEach((id) => threadMessageIds.add(id));
1372
- } catch {
1373
- }
1374
- }
1375
- const threadMessages = await this.fetchAndParseMessagesFromMultipleThreads(
1376
- Array.from(threadMessageIds),
1377
- void 0,
1378
- threadIds.length === 1 ? threadIds[0] : void 0
1379
- );
1380
- let filteredThreadMessages = threadMessages;
1381
- if (resourceId) {
1382
- filteredThreadMessages = filteredThreadMessages.filter((msg) => msg.resourceId === resourceId);
1383
- }
1384
- filteredThreadMessages = storage.filterByDateRange(
1385
- filteredThreadMessages,
1386
- (msg) => new Date(msg.createdAt),
1387
- filter?.dateRange
1388
- );
1389
- filteredThreadMessages = filteredThreadMessages.filter(
1390
- (message) => storage.storageMessageMatchesMetadataFilter(message.content, metadataFilter)
1391
- );
1392
- const total = filteredThreadMessages.length;
1393
- filteredThreadMessages.sort((a, b) => {
1394
- const timeA = new Date(a.createdAt).getTime();
1395
- const timeB = new Date(b.createdAt).getTime();
1396
- const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
1397
- if (timeDiff === 0) {
1398
- return a.id.localeCompare(b.id);
1399
- }
1400
- return timeDiff;
1401
- });
1402
- let paginatedMessages;
1403
- if (perPage === 0) {
1404
- paginatedMessages = [];
1405
- } else if (perPage === Number.MAX_SAFE_INTEGER) {
1406
- paginatedMessages = filteredThreadMessages;
1407
- } else {
1408
- paginatedMessages = filteredThreadMessages.slice(offset, offset + perPage);
1409
- }
1410
- let includedMessages = [];
1411
- if (include && include.length > 0) {
1412
- const includedMessageIds = /* @__PURE__ */ new Set();
1413
- await this.getIncludedMessagesWithContext(include, includedMessageIds);
1414
- const paginatedIds = new Set(paginatedMessages.map((m) => m.id));
1415
- const idsToFetch = Array.from(includedMessageIds).filter((id) => !paginatedIds.has(id));
1416
- if (idsToFetch.length > 0) {
1417
- includedMessages = await this.fetchAndParseMessagesFromMultipleThreads(idsToFetch, include, void 0);
1418
- }
1419
- }
1420
- const seenIds = /* @__PURE__ */ new Set();
1421
- const allMessages = [];
1422
- for (const msg of paginatedMessages) {
1423
- if (!seenIds.has(msg.id)) {
1424
- allMessages.push(msg);
1425
- seenIds.add(msg.id);
1426
- }
1427
- }
1428
- for (const msg of includedMessages) {
1429
- if (!seenIds.has(msg.id)) {
1430
- allMessages.push(msg);
1431
- seenIds.add(msg.id);
1432
- }
1433
- }
1434
- allMessages.sort((a, b) => {
1435
- const timeA = new Date(a.createdAt).getTime();
1436
- const timeB = new Date(b.createdAt).getTime();
1437
- const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
1438
- if (timeDiff === 0) {
1439
- return a.id.localeCompare(b.id);
1440
- }
1441
- return timeDiff;
1442
- });
1443
- let filteredMessages = allMessages;
1444
- const paginatedCount = paginatedMessages.length;
1445
- if (total === 0 && filteredMessages.length === 0 && (!include || include.length === 0)) {
1446
- return {
1447
- messages: [],
1448
- total: 0,
1449
- page,
1450
- perPage: perPageForResponse,
1451
- hasMore: false
1452
- };
1453
- }
1454
- const prepared = filteredMessages.map(({ _index, ...message }) => ({
1455
- ...message,
1456
- type: message.type !== "v2" ? message.type : void 0,
1457
- createdAt: storage.ensureDate(message.createdAt)
1458
- }));
1459
- const primaryThreadId = Array.isArray(threadId) ? threadId[0] : threadId;
1460
- const list = new agent.MessageList({ threadId: primaryThreadId, resourceId }).add(
1461
- prepared,
1462
- "memory"
1463
- );
1464
- const finalMessages = this._sortMessages(list.get.all.db(), field, direction);
1465
- const threadIdSet = new Set(threadIds);
1466
- const returnedThreadMessageIds = new Set(
1467
- finalMessages.filter((message) => message.threadId && threadIdSet.has(message.threadId)).map((message) => message.id)
1468
- );
1469
- const hasMore = perPageInput !== false && (metadataFilter || returnedThreadMessageIds.size < total) && offset + paginatedCount < total;
1470
- return {
1471
- messages: finalMessages,
1472
- total,
1473
- page,
1474
- perPage: perPageForResponse,
1475
- hasMore
1476
- };
1477
- } catch (error$1) {
1478
- const mastraError = new error.MastraError(
1479
- {
1480
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "FAILED"),
1481
- domain: error.ErrorDomain.STORAGE,
1482
- category: error.ErrorCategory.THIRD_PARTY,
1483
- text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1484
- details: {
1485
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
1486
- resourceId: resourceId ?? ""
1487
- }
1488
- },
1489
- error$1
1490
- );
1491
- this.logger?.error?.(mastraError.toString());
1492
- this.logger?.trackException?.(mastraError);
1493
- return {
1494
- messages: [],
1495
- total: 0,
1496
- page,
1497
- perPage: perPageForResponse,
1498
- hasMore: false
1499
- };
1500
- }
1501
- }
1502
- async updateMessages(args) {
1503
- try {
1504
- const { messages } = args;
1505
- const updatedMessages = [];
1506
- for (const messageUpdate of messages) {
1507
- const { id, content, ...otherFields } = messageUpdate;
1508
- const prefix = this.#db.namespacePrefix ? `${this.#db.namespacePrefix}:` : "";
1509
- const keyObjs = await this.#db.listKV(storage.TABLE_MESSAGES, { prefix: `${prefix}${storage.TABLE_MESSAGES}` });
1510
- let existingMessage = null;
1511
- let messageKey = "";
1512
- for (const { name: key } of keyObjs) {
1513
- const data = await this.#db.getKV(storage.TABLE_MESSAGES, key);
1514
- if (data && data.id === id) {
1515
- existingMessage = data;
1516
- messageKey = key;
1517
- break;
1518
- }
1519
- }
1520
- if (!existingMessage) {
1521
- continue;
1522
- }
1523
- const updatedMessage = {
1524
- ...existingMessage,
1525
- ...otherFields,
1526
- id
1527
- };
1528
- if (content) {
1529
- if (content.metadata !== void 0) {
1530
- updatedMessage.content = {
1531
- ...updatedMessage.content,
1532
- metadata: {
1533
- ...updatedMessage.content?.metadata,
1534
- ...content.metadata
1535
- }
1536
- };
1537
- }
1538
- if (content.content !== void 0) {
1539
- updatedMessage.content = {
1540
- ...updatedMessage.content,
1541
- content: content.content
1542
- };
1543
- }
1544
- }
1545
- if ("threadId" in messageUpdate && messageUpdate.threadId && messageUpdate.threadId !== existingMessage.threadId) {
1546
- await this.#db.deleteKV(storage.TABLE_MESSAGES, messageKey);
1547
- updatedMessage.threadId = messageUpdate.threadId;
1548
- const newMessageKey = this.getMessageKey(messageUpdate.threadId, id);
1549
- await this.#db.putKV({
1550
- tableName: storage.TABLE_MESSAGES,
1551
- key: newMessageKey,
1552
- value: updatedMessage
1553
- });
1554
- if (existingMessage.threadId) {
1555
- const sourceOrderKey = this.getThreadMessagesKey(existingMessage.threadId);
1556
- const sourceEntries = await this.getSortedMessages(sourceOrderKey);
1557
- const filteredEntries = sourceEntries.filter((entry) => entry.id !== id);
1558
- await this.updateSortedMessages(sourceOrderKey, filteredEntries);
1559
- }
1560
- const destOrderKey = this.getThreadMessagesKey(messageUpdate.threadId);
1561
- const destEntries = await this.getSortedMessages(destOrderKey);
1562
- const newEntry = { id, score: Date.now() };
1563
- destEntries.push(newEntry);
1564
- await this.updateSortedMessages(destOrderKey, destEntries);
1565
- } else {
1566
- await this.#db.putKV({
1567
- tableName: storage.TABLE_MESSAGES,
1568
- key: messageKey,
1569
- value: updatedMessage
1570
- });
1571
- }
1572
- const threadsToUpdate = /* @__PURE__ */ new Set();
1573
- if (updatedMessage.threadId) {
1574
- threadsToUpdate.add(updatedMessage.threadId);
1575
- }
1576
- if ("threadId" in messageUpdate && messageUpdate.threadId && messageUpdate.threadId !== existingMessage.threadId) {
1577
- if (existingMessage.threadId) {
1578
- threadsToUpdate.add(existingMessage.threadId);
1579
- }
1580
- threadsToUpdate.add(messageUpdate.threadId);
1581
- }
1582
- for (const threadId of threadsToUpdate) {
1583
- const thread = await this.getThreadById({ threadId });
1584
- if (thread) {
1585
- const updatedThread = {
1586
- ...thread,
1587
- updatedAt: /* @__PURE__ */ new Date()
1588
- };
1589
- await this.#db.putKV({
1590
- tableName: storage.TABLE_THREADS,
1591
- key: this.#db.getKey(storage.TABLE_THREADS, { id: threadId }),
1592
- value: updatedThread
1593
- });
1594
- }
1595
- }
1596
- updatedMessages.push(updatedMessage);
1597
- }
1598
- return updatedMessages;
1599
- } catch (error$1) {
1600
- throw new error.MastraError(
1601
- {
1602
- id: storage.createStorageErrorId("CLOUDFLARE", "UPDATE_MESSAGES", "FAILED"),
1603
- domain: error.ErrorDomain.STORAGE,
1604
- category: error.ErrorCategory.THIRD_PARTY,
1605
- text: "Failed to update messages"
1606
- },
1607
- error$1
1608
- );
1609
- }
1610
- }
1611
- async getResourceById({ resourceId }) {
1612
- try {
1613
- const data = await this.#db.getKV(storage.TABLE_RESOURCES, resourceId);
1614
- if (!data) return null;
1615
- const resource = typeof data === "string" ? JSON.parse(data) : data;
1616
- return {
1617
- ...resource,
1618
- createdAt: storage.ensureDate(resource.createdAt),
1619
- updatedAt: storage.ensureDate(resource.updatedAt),
1620
- metadata: this.ensureMetadata(resource.metadata)
1621
- };
1622
- } catch (error$1) {
1623
- const mastraError = new error.MastraError(
1624
- {
1625
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_RESOURCE_BY_ID", "FAILED"),
1626
- domain: error.ErrorDomain.STORAGE,
1627
- category: error.ErrorCategory.THIRD_PARTY,
1628
- details: {
1629
- resourceId
1630
- }
1631
- },
1632
- error$1
1633
- );
1634
- this.logger?.trackException(mastraError);
1635
- this.logger?.error(mastraError.toString());
1636
- return null;
1637
- }
1638
- }
1639
- async saveResource({ resource }) {
1640
- try {
1641
- const resourceToSave = {
1642
- ...resource,
1643
- metadata: resource.metadata ? JSON.stringify(resource.metadata) : null
1644
- };
1645
- await this.#db.putKV({
1646
- tableName: storage.TABLE_RESOURCES,
1647
- key: resource.id,
1648
- value: resourceToSave
1649
- });
1650
- return resource;
1651
- } catch (error$1) {
1652
- throw new error.MastraError(
1653
- {
1654
- id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_RESOURCE", "FAILED"),
1655
- domain: error.ErrorDomain.STORAGE,
1656
- category: error.ErrorCategory.THIRD_PARTY,
1657
- details: {
1658
- resourceId: resource.id
1659
- }
1660
- },
1661
- error$1
1662
- );
1663
- }
1664
- }
1665
- async updateResource({
1666
- resourceId,
1667
- workingMemory,
1668
- metadata
1669
- }) {
1670
- const existingResource = await this.getResourceById({ resourceId });
1671
- if (!existingResource) {
1672
- const newResource = {
1673
- id: resourceId,
1674
- workingMemory,
1675
- metadata: metadata || {},
1676
- createdAt: /* @__PURE__ */ new Date(),
1677
- updatedAt: /* @__PURE__ */ new Date()
1678
- };
1679
- return this.saveResource({ resource: newResource });
1680
- }
1681
- const updatedAt = /* @__PURE__ */ new Date();
1682
- const updatedResource = {
1683
- ...existingResource,
1684
- workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1685
- metadata: {
1686
- ...existingResource.metadata,
1687
- ...metadata
1688
- },
1689
- updatedAt
1690
- };
1691
- return this.saveResource({ resource: updatedResource });
1692
- }
1693
- async deleteMessages(messageIds) {
1694
- if (messageIds.length === 0) return;
1695
- try {
1696
- const threadIds = /* @__PURE__ */ new Set();
1697
- for (const messageId of messageIds) {
1698
- const message = await this.findMessageInAnyThread(messageId);
1699
- if (message?.threadId) {
1700
- threadIds.add(message.threadId);
1701
- const messageKey = this.getMessageKey(message.threadId, messageId);
1702
- await this.#db.deleteKV(storage.TABLE_MESSAGES, messageKey);
1703
- const orderKey = this.getThreadMessagesKey(message.threadId);
1704
- const entries = await this.getSortedMessages(orderKey);
1705
- const filteredEntries = entries.filter((entry) => entry.id !== messageId);
1706
- if (filteredEntries.length > 0) {
1707
- await this.#db.putKV({
1708
- tableName: storage.TABLE_MESSAGES,
1709
- key: orderKey,
1710
- value: JSON.stringify(filteredEntries)
1711
- });
1712
- } else {
1713
- await this.#db.deleteKV(storage.TABLE_MESSAGES, orderKey);
1714
- }
1715
- }
1716
- }
1717
- for (const threadId of threadIds) {
1718
- const thread = await this.getThreadById({ threadId });
1719
- if (thread) {
1720
- const updatedThread = {
1721
- ...thread,
1722
- updatedAt: /* @__PURE__ */ new Date()
1723
- };
1724
- await this.#db.putKV({
1725
- tableName: storage.TABLE_THREADS,
1726
- key: this.#db.getKey(storage.TABLE_THREADS, { id: threadId }),
1727
- value: updatedThread
1728
- });
1729
- }
1730
- }
1731
- } catch (error$1) {
1732
- throw new error.MastraError(
1733
- {
1734
- id: storage.createStorageErrorId("CLOUDFLARE", "DELETE_MESSAGES", "FAILED"),
1735
- domain: error.ErrorDomain.STORAGE,
1736
- category: error.ErrorCategory.THIRD_PARTY,
1737
- details: { messageIds: JSON.stringify(messageIds) }
1738
- },
1739
- error$1
1740
- );
1741
- }
1742
- }
1743
- };
1744
- function transformScoreRow(row) {
1745
- return storage.transformScoreRow(row);
1746
- }
1747
- function matchesTenancy(score, filters) {
1748
- if (filters?.organizationId !== void 0 && score.organizationId !== filters.organizationId) return false;
1749
- if (filters?.projectId !== void 0 && score.projectId !== filters.projectId) return false;
1750
- return true;
1751
- }
1752
- var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1753
- #db;
1754
- constructor(config) {
1755
- super();
1756
- this.#db = new CloudflareKVDB(resolveCloudflareConfig(config));
1757
- }
1758
- async init() {
1759
- }
1760
- async dangerouslyClearAll() {
1761
- await this.#db.clearTable({ tableName: storage.TABLE_SCORERS });
1762
- }
1763
- async getScoreById({ id }) {
1764
- try {
1765
- const score = await this.#db.getKV(storage.TABLE_SCORERS, id);
1766
- if (!score) {
1767
- return null;
1768
- }
1769
- return transformScoreRow(score);
1770
- } catch (error$1) {
1771
- const mastraError = new error.MastraError(
1772
- {
1773
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORE_BY_ID", "FAILED"),
1774
- domain: error.ErrorDomain.STORAGE,
1775
- category: error.ErrorCategory.THIRD_PARTY,
1776
- text: `Failed to get score by id: ${id}`
1777
- },
1778
- error$1
1779
- );
1780
- this.logger?.trackException(mastraError);
1781
- this.logger?.error(mastraError.toString());
1782
- return null;
1783
- }
1784
- }
1785
- async saveScore(score) {
1786
- let parsedScore;
1787
- try {
1788
- parsedScore = evals.saveScorePayloadSchema.parse(score);
1789
- } catch (error$1) {
1790
- throw new error.MastraError(
1791
- {
1792
- id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_SCORE", "VALIDATION_FAILED"),
1793
- domain: error.ErrorDomain.STORAGE,
1794
- category: error.ErrorCategory.USER,
1795
- details: {
1796
- scorer: typeof score.scorer?.id === "string" ? score.scorer.id : String(score.scorer?.id ?? "unknown"),
1797
- entityId: score.entityId ?? "unknown",
1798
- entityType: score.entityType ?? "unknown",
1799
- traceId: score.traceId ?? "",
1800
- spanId: score.spanId ?? ""
1801
- }
1802
- },
1803
- error$1
1804
- );
1805
- }
1806
- const id = crypto.randomUUID();
1807
- try {
1808
- const serializedRecord = {};
1809
- for (const [key, value] of Object.entries(parsedScore)) {
1810
- if (value !== null && value !== void 0) {
1811
- if (typeof value === "object") {
1812
- serializedRecord[key] = JSON.stringify(value);
1813
- } else {
1814
- serializedRecord[key] = value;
1815
- }
1816
- } else {
1817
- serializedRecord[key] = null;
1818
- }
1819
- }
1820
- const now = /* @__PURE__ */ new Date();
1821
- serializedRecord.id = id;
1822
- serializedRecord.createdAt = now.toISOString();
1823
- serializedRecord.updatedAt = now.toISOString();
1824
- await this.#db.putKV({
1825
- tableName: storage.TABLE_SCORERS,
1826
- key: id,
1827
- value: serializedRecord
1828
- });
1829
- return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1830
- } catch (error$1) {
1831
- const mastraError = new error.MastraError(
1832
- {
1833
- id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_SCORE", "FAILED"),
1834
- domain: error.ErrorDomain.STORAGE,
1835
- category: error.ErrorCategory.THIRD_PARTY,
1836
- details: { id }
1837
- },
1838
- error$1
1839
- );
1840
- this.logger?.trackException(mastraError);
1841
- this.logger?.error(mastraError.toString());
1842
- throw mastraError;
1843
- }
1844
- }
1845
- async listScoresByScorerId({
1846
- scorerId,
1847
- entityId,
1848
- entityType,
1849
- source,
1850
- pagination,
1851
- filters
1852
- }) {
1853
- try {
1854
- const keys = await this.#db.listKV(storage.TABLE_SCORERS);
1855
- const scores = [];
1856
- for (const { name: key } of keys) {
1857
- const score = await this.#db.getKV(storage.TABLE_SCORERS, key);
1858
- if (entityId && score.entityId !== entityId) {
1859
- continue;
1860
- }
1861
- if (entityType && score.entityType !== entityType) {
1862
- continue;
1863
- }
1864
- if (source && score.source !== source) {
1865
- continue;
1866
- }
1867
- if (!matchesTenancy(score, filters)) {
1868
- continue;
1869
- }
1870
- if (score && score.scorerId === scorerId) {
1871
- scores.push(transformScoreRow(score));
1872
- }
1873
- }
1874
- scores.sort((a, b) => {
1875
- const dateA = new Date(a.createdAt || 0).getTime();
1876
- const dateB = new Date(b.createdAt || 0).getTime();
1877
- return dateB - dateA;
1878
- });
1879
- const { page, perPage: perPageInput } = pagination;
1880
- const perPage = storage.normalizePerPage(perPageInput, 100);
1881
- const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1882
- const total = scores.length;
1883
- const end = perPageInput === false ? scores.length : start + perPage;
1884
- const pagedScores = scores.slice(start, end);
1885
- return {
1886
- pagination: {
1887
- total,
1888
- page,
1889
- perPage: perPageForResponse,
1890
- hasMore: end < total
1891
- },
1892
- scores: pagedScores
1893
- };
1894
- } catch (error$1) {
1895
- const mastraError = new error.MastraError(
1896
- {
1897
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1898
- domain: error.ErrorDomain.STORAGE,
1899
- category: error.ErrorCategory.THIRD_PARTY,
1900
- text: `Failed to get scores by scorer id: ${scorerId}`
1901
- },
1902
- error$1
1903
- );
1904
- this.logger?.trackException(mastraError);
1905
- this.logger?.error(mastraError.toString());
1906
- return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1907
- }
1908
- }
1909
- async listScoresByRunId({
1910
- runId,
1911
- pagination,
1912
- filters
1913
- }) {
1914
- try {
1915
- const keys = await this.#db.listKV(storage.TABLE_SCORERS);
1916
- const scores = [];
1917
- for (const { name: key } of keys) {
1918
- const score = await this.#db.getKV(storage.TABLE_SCORERS, key);
1919
- if (score && score.runId === runId && matchesTenancy(score, filters)) {
1920
- scores.push(transformScoreRow(score));
1921
- }
1922
- }
1923
- scores.sort((a, b) => {
1924
- const dateA = new Date(a.createdAt || 0).getTime();
1925
- const dateB = new Date(b.createdAt || 0).getTime();
1926
- return dateB - dateA;
1927
- });
1928
- const { page, perPage: perPageInput } = pagination;
1929
- const perPage = storage.normalizePerPage(perPageInput, 100);
1930
- const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1931
- const total = scores.length;
1932
- const end = perPageInput === false ? scores.length : start + perPage;
1933
- const pagedScores = scores.slice(start, end);
1934
- return {
1935
- pagination: {
1936
- total,
1937
- page,
1938
- perPage: perPageForResponse,
1939
- hasMore: end < total
1940
- },
1941
- scores: pagedScores
1942
- };
1943
- } catch (error$1) {
1944
- const mastraError = new error.MastraError(
1945
- {
1946
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_RUN_ID", "FAILED"),
1947
- domain: error.ErrorDomain.STORAGE,
1948
- category: error.ErrorCategory.THIRD_PARTY,
1949
- text: `Failed to get scores by run id: ${runId}`
1950
- },
1951
- error$1
1952
- );
1953
- this.logger?.trackException(mastraError);
1954
- this.logger?.error(mastraError.toString());
1955
- return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1956
- }
1957
- }
1958
- async listScoresByEntityId({
1959
- entityId,
1960
- entityType,
1961
- pagination,
1962
- filters
1963
- }) {
1964
- try {
1965
- const keys = await this.#db.listKV(storage.TABLE_SCORERS);
1966
- const scores = [];
1967
- for (const { name: key } of keys) {
1968
- const score = await this.#db.getKV(storage.TABLE_SCORERS, key);
1969
- if (score && score.entityId === entityId && score.entityType === entityType && matchesTenancy(score, filters)) {
1970
- scores.push(transformScoreRow(score));
1971
- }
1972
- }
1973
- scores.sort((a, b) => {
1974
- const dateA = new Date(a.createdAt || 0).getTime();
1975
- const dateB = new Date(b.createdAt || 0).getTime();
1976
- return dateB - dateA;
1977
- });
1978
- const { page, perPage: perPageInput } = pagination;
1979
- const perPage = storage.normalizePerPage(perPageInput, 100);
1980
- const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1981
- const total = scores.length;
1982
- const end = perPageInput === false ? scores.length : start + perPage;
1983
- const pagedScores = scores.slice(start, end);
1984
- return {
1985
- pagination: {
1986
- total,
1987
- page,
1988
- perPage: perPageForResponse,
1989
- hasMore: end < total
1990
- },
1991
- scores: pagedScores
1992
- };
1993
- } catch (error$1) {
1994
- const mastraError = new error.MastraError(
1995
- {
1996
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
1997
- domain: error.ErrorDomain.STORAGE,
1998
- category: error.ErrorCategory.THIRD_PARTY,
1999
- text: `Failed to get scores by entity id: ${entityId}, type: ${entityType}`
2000
- },
2001
- error$1
2002
- );
2003
- this.logger?.trackException(mastraError);
2004
- this.logger?.error(mastraError.toString());
2005
- return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
2006
- }
2007
- }
2008
- async listScoresBySpan({
2009
- traceId,
2010
- spanId,
2011
- pagination,
2012
- filters
2013
- }) {
2014
- try {
2015
- const keys = await this.#db.listKV(storage.TABLE_SCORERS);
2016
- const scores = [];
2017
- for (const { name: key } of keys) {
2018
- const score = await this.#db.getKV(storage.TABLE_SCORERS, key);
2019
- if (score && score.traceId === traceId && score.spanId === spanId && matchesTenancy(score, filters)) {
2020
- scores.push(transformScoreRow(score));
2021
- }
2022
- }
2023
- scores.sort((a, b) => {
2024
- const dateA = new Date(a.createdAt || 0).getTime();
2025
- const dateB = new Date(b.createdAt || 0).getTime();
2026
- return dateB - dateA;
2027
- });
2028
- const { page, perPage: perPageInput } = pagination;
2029
- const perPage = storage.normalizePerPage(perPageInput, 100);
2030
- const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2031
- const total = scores.length;
2032
- const end = perPageInput === false ? scores.length : start + perPage;
2033
- const pagedScores = scores.slice(start, end);
2034
- return {
2035
- pagination: {
2036
- total,
2037
- page,
2038
- perPage: perPageForResponse,
2039
- hasMore: end < total
2040
- },
2041
- scores: pagedScores
2042
- };
2043
- } catch (error$1) {
2044
- const mastraError = new error.MastraError(
2045
- {
2046
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_SPAN", "FAILED"),
2047
- domain: error.ErrorDomain.STORAGE,
2048
- category: error.ErrorCategory.THIRD_PARTY,
2049
- text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
2050
- },
2051
- error$1
2052
- );
2053
- this.logger?.trackException(mastraError);
2054
- this.logger?.error(mastraError.toString());
2055
- return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
2056
- }
2057
- }
2058
- };
2059
- var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2060
- #db;
2061
- constructor(config) {
2062
- super();
2063
- this.#db = new CloudflareKVDB(resolveCloudflareConfig(config));
2064
- }
2065
- supportsConcurrentUpdates() {
2066
- return false;
2067
- }
2068
- async init() {
2069
- }
2070
- async dangerouslyClearAll() {
2071
- await this.#db.clearTable({ tableName: storage.TABLE_WORKFLOW_SNAPSHOT });
2072
- }
2073
- validateWorkflowParams(params) {
2074
- const { workflowName, runId } = params;
2075
- if (!workflowName || !runId) {
2076
- throw new Error("Invalid workflow snapshot parameters");
2077
- }
2078
- }
2079
- async updateWorkflowResults(_args) {
2080
- throw new Error(
2081
- "updateWorkflowResults is not implemented for Cloudflare KV storage. Cloudflare KV is eventually-consistent and does not support atomic read-modify-write operations needed for concurrent workflow updates."
2082
- );
2083
- }
2084
- async updateWorkflowState(_args) {
2085
- throw new Error(
2086
- "updateWorkflowState is not implemented for Cloudflare KV storage. Cloudflare KV is eventually-consistent and does not support atomic read-modify-write operations needed for concurrent workflow updates."
2087
- );
2088
- }
2089
- async persistWorkflowSnapshot(params) {
2090
- try {
2091
- const { workflowName, runId, resourceId, snapshot, createdAt, updatedAt } = params;
2092
- const now = /* @__PURE__ */ new Date();
2093
- const existingKey = this.#db.getKey(storage.TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId });
2094
- const existing = await this.#db.getKV(storage.TABLE_WORKFLOW_SNAPSHOT, existingKey);
2095
- await this.#db.putKV({
2096
- tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
2097
- key: existingKey,
2098
- value: {
2099
- workflow_name: workflowName,
2100
- run_id: runId,
2101
- resourceId,
2102
- snapshot: JSON.stringify(snapshot),
2103
- createdAt: existing?.createdAt ?? createdAt ?? now,
2104
- updatedAt: updatedAt ?? now
2105
- }
2106
- });
2107
- } catch (error$1) {
2108
- throw new error.MastraError(
2109
- {
2110
- id: storage.createStorageErrorId("CLOUDFLARE", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2111
- domain: error.ErrorDomain.STORAGE,
2112
- category: error.ErrorCategory.THIRD_PARTY,
2113
- text: `Error persisting workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
2114
- details: {
2115
- workflowName: params.workflowName,
2116
- runId: params.runId
2117
- }
2118
- },
2119
- error$1
2120
- );
2121
- }
2122
- }
2123
- async loadWorkflowSnapshot(params) {
2124
- try {
2125
- this.validateWorkflowParams(params);
2126
- const { workflowName, runId } = params;
2127
- const key = this.#db.getKey(storage.TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId });
2128
- const data = await this.#db.getKV(storage.TABLE_WORKFLOW_SNAPSHOT, key);
2129
- if (!data) return null;
2130
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2131
- return snapshotData;
2132
- } catch (error$1) {
2133
- const mastraError = new error.MastraError(
2134
- {
2135
- id: storage.createStorageErrorId("CLOUDFLARE", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2136
- domain: error.ErrorDomain.STORAGE,
2137
- category: error.ErrorCategory.THIRD_PARTY,
2138
- text: `Error loading workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
2139
- details: {
2140
- workflowName: params.workflowName,
2141
- runId: params.runId
2142
- }
2143
- },
2144
- error$1
2145
- );
2146
- this.logger.trackException?.(mastraError);
2147
- this.logger.error(mastraError.toString());
2148
- return null;
2149
- }
2150
- }
2151
- parseWorkflowRun(row) {
2152
- let parsedSnapshot = row.snapshot;
2153
- if (typeof parsedSnapshot === "string") {
2154
- try {
2155
- parsedSnapshot = JSON.parse(row.snapshot);
2156
- } catch (e) {
2157
- this.logger.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
2158
- }
2159
- }
2160
- return {
2161
- workflowName: row.workflow_name,
2162
- runId: row.run_id,
2163
- snapshot: parsedSnapshot,
2164
- createdAt: storage.ensureDate(row.createdAt),
2165
- updatedAt: storage.ensureDate(row.updatedAt),
2166
- resourceId: row.resourceId
2167
- };
2168
- }
2169
- buildWorkflowSnapshotPrefix({
2170
- workflowName,
2171
- runId,
2172
- resourceId
2173
- }) {
2174
- const prefix = this.#db.namespacePrefix ? `${this.#db.namespacePrefix}:` : "";
2175
- let key = `${prefix}${storage.TABLE_WORKFLOW_SNAPSHOT}`;
2176
- if (workflowName) key += `:${workflowName}`;
2177
- if (runId) key += `:${runId}`;
2178
- if (resourceId) key += `:${resourceId}`;
2179
- return key;
2180
- }
2181
- async listWorkflowRuns({
2182
- workflowName,
2183
- page = 0,
2184
- perPage = 20,
2185
- resourceId,
2186
- fromDate,
2187
- toDate,
2188
- status
2189
- } = {}) {
2190
- try {
2191
- if (page < 0 || !Number.isInteger(page)) {
2192
- throw new error.MastraError(
2193
- {
2194
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_WORKFLOW_RUNS", "INVALID_PAGE"),
2195
- domain: error.ErrorDomain.STORAGE,
2196
- category: error.ErrorCategory.USER,
2197
- details: { page }
2198
- },
2199
- new Error("page must be a non-negative integer")
2200
- );
2201
- }
2202
- const normalizedPerPage = storage.normalizePerPage(perPage, 20);
2203
- const offset = page * normalizedPerPage;
2204
- const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2205
- const keyObjs = await this.#db.listKV(storage.TABLE_WORKFLOW_SNAPSHOT, { prefix });
2206
- const runs = [];
2207
- for (const { name: key } of keyObjs) {
2208
- const parts = key.split(":");
2209
- const idx = parts.indexOf(storage.TABLE_WORKFLOW_SNAPSHOT);
2210
- if (idx === -1 || parts.length < idx + 3) continue;
2211
- const wfName = parts[idx + 1];
2212
- const keyResourceId = parts.length > idx + 3 ? parts[idx + 3] : void 0;
2213
- if (workflowName && wfName !== workflowName) continue;
2214
- const data = await this.#db.getKV(storage.TABLE_WORKFLOW_SNAPSHOT, key);
2215
- if (!data) continue;
2216
- try {
2217
- const effectiveResourceId = keyResourceId || data.resourceId;
2218
- if (resourceId && effectiveResourceId !== resourceId) continue;
2219
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2220
- if (status && snapshotData.status !== status) continue;
2221
- const createdAt = storage.ensureDate(data.createdAt);
2222
- if (fromDate && createdAt && createdAt < fromDate) continue;
2223
- if (toDate && createdAt && createdAt > toDate) continue;
2224
- const run = this.parseWorkflowRun({
2225
- ...data,
2226
- workflow_name: wfName,
2227
- resourceId: effectiveResourceId,
2228
- snapshot: snapshotData
2229
- });
2230
- runs.push(run);
2231
- } catch (err) {
2232
- this.logger.error("Failed to parse workflow snapshot:", { key, error: err });
2233
- }
2234
- }
2235
- runs.sort((a, b) => {
2236
- const aDate = a.createdAt ? new Date(a.createdAt).getTime() : 0;
2237
- const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2238
- return bDate - aDate;
2239
- });
2240
- const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2241
- return {
2242
- runs: pagedRuns,
2243
- total: runs.length
2244
- };
2245
- } catch (error$1) {
2246
- const mastraError = new error.MastraError(
2247
- {
2248
- id: storage.createStorageErrorId("CLOUDFLARE", "LIST_WORKFLOW_RUNS", "FAILED"),
2249
- domain: error.ErrorDomain.STORAGE,
2250
- category: error.ErrorCategory.THIRD_PARTY
2251
- },
2252
- error$1
2253
- );
2254
- this.logger.trackException?.(mastraError);
2255
- this.logger.error(mastraError.toString());
2256
- return { runs: [], total: 0 };
2257
- }
2258
- }
2259
- async getWorkflowRunById({
2260
- runId,
2261
- workflowName
2262
- }) {
2263
- try {
2264
- if (!runId || !workflowName) {
2265
- throw new Error("runId, workflowName, are required");
2266
- }
2267
- const prefix = this.buildWorkflowSnapshotPrefix({ workflowName, runId });
2268
- const keyObjs = await this.#db.listKV(storage.TABLE_WORKFLOW_SNAPSHOT, { prefix });
2269
- if (!keyObjs.length) return null;
2270
- const exactKey = keyObjs.find((k) => {
2271
- const parts = k.name.split(":");
2272
- const idx = parts.indexOf(storage.TABLE_WORKFLOW_SNAPSHOT);
2273
- if (idx === -1 || parts.length < idx + 3) return false;
2274
- const wfName = parts[idx + 1];
2275
- const rId = parts[idx + 2];
2276
- return wfName === workflowName && rId === runId;
2277
- });
2278
- if (!exactKey) return null;
2279
- const data = await this.#db.getKV(storage.TABLE_WORKFLOW_SNAPSHOT, exactKey.name);
2280
- if (!data) return null;
2281
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2282
- return this.parseWorkflowRun({ ...data, snapshot: snapshotData });
2283
- } catch (error$1) {
2284
- const mastraError = new error.MastraError(
2285
- {
2286
- id: storage.createStorageErrorId("CLOUDFLARE", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2287
- domain: error.ErrorDomain.STORAGE,
2288
- category: error.ErrorCategory.THIRD_PARTY,
2289
- details: {
2290
- workflowName,
2291
- runId
2292
- }
2293
- },
2294
- error$1
2295
- );
2296
- this.logger.trackException?.(mastraError);
2297
- this.logger.error(mastraError.toString());
2298
- return null;
2299
- }
2300
- }
2301
- async deleteWorkflowRunById({ runId, workflowName }) {
2302
- try {
2303
- if (!runId || !workflowName) {
2304
- throw new Error("runId and workflowName are required");
2305
- }
2306
- const key = this.#db.getKey(storage.TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId });
2307
- await this.#db.deleteKV(storage.TABLE_WORKFLOW_SNAPSHOT, key);
2308
- } catch (error$1) {
2309
- throw new error.MastraError(
2310
- {
2311
- id: storage.createStorageErrorId("CLOUDFLARE", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2312
- domain: error.ErrorDomain.STORAGE,
2313
- category: error.ErrorCategory.THIRD_PARTY,
2314
- details: {
2315
- workflowName,
2316
- runId
2317
- }
2318
- },
2319
- error$1
2320
- );
2321
- }
2322
- }
2323
- };
2324
-
2325
- // src/kv/storage/types.ts
2326
- function isWorkersConfig(config) {
2327
- return "bindings" in config;
2328
- }
2329
-
2330
- // src/kv/index.ts
2331
- var CloudflareKVStorage = class extends storage.MastraCompositeStore {
2332
- stores;
2333
- client;
2334
- accountId;
2335
- namespacePrefix;
2336
- bindings;
2337
- validateWorkersConfig(config) {
2338
- if (!isWorkersConfig(config)) {
2339
- throw new Error("Invalid Workers API configuration");
2340
- }
2341
- if (!config.bindings) {
2342
- throw new Error("KV bindings are required when using Workers Binding API");
2343
- }
2344
- const requiredTables = [
2345
- storage.TABLE_THREADS,
2346
- storage.TABLE_MESSAGES,
2347
- storage.TABLE_WORKFLOW_SNAPSHOT,
2348
- storage.TABLE_SCORERS,
2349
- storage.TABLE_BACKGROUND_TASKS
2350
- ];
2351
- for (const table of requiredTables) {
2352
- if (!(table in config.bindings)) {
2353
- throw new Error(`Missing KV binding for table: ${table}`);
2354
- }
2355
- }
2356
- }
2357
- validateRestConfig(config) {
2358
- if (isWorkersConfig(config)) {
2359
- throw new Error("Invalid REST API configuration");
2360
- }
2361
- if (!config.accountId?.trim()) {
2362
- throw new Error("accountId is required for REST API");
2363
- }
2364
- if (!config.apiToken?.trim()) {
2365
- throw new Error("apiToken is required for REST API");
2366
- }
2367
- }
2368
- constructor(config) {
2369
- super({ id: config.id, name: "Cloudflare", disableInit: config.disableInit });
2370
- try {
2371
- let workflows;
2372
- let memory;
2373
- let scores;
2374
- let backgroundTasks;
2375
- if (isWorkersConfig(config)) {
2376
- this.validateWorkersConfig(config);
2377
- this.bindings = config.bindings;
2378
- this.namespacePrefix = config.keyPrefix?.trim() || "";
2379
- this.logger.info("Using Cloudflare KV Workers Binding API");
2380
- const domainConfig = {
2381
- bindings: this.bindings,
2382
- keyPrefix: this.namespacePrefix
2383
- };
2384
- workflows = new WorkflowsStorageCloudflare(domainConfig);
2385
- memory = new MemoryStorageCloudflare(domainConfig);
2386
- scores = new ScoresStorageCloudflare(domainConfig);
2387
- backgroundTasks = new BackgroundTasksStorageCloudflare(domainConfig);
2388
- } else {
2389
- this.validateRestConfig(config);
2390
- this.accountId = config.accountId.trim();
2391
- this.namespacePrefix = config.namespacePrefix?.trim() || "";
2392
- this.client = new Cloudflare__default.default({
2393
- apiToken: config.apiToken.trim()
2394
- });
2395
- this.logger.info("Using Cloudflare KV REST API");
2396
- const domainConfig = {
2397
- client: this.client,
2398
- accountId: this.accountId,
2399
- namespacePrefix: this.namespacePrefix
2400
- };
2401
- workflows = new WorkflowsStorageCloudflare(domainConfig);
2402
- memory = new MemoryStorageCloudflare(domainConfig);
2403
- scores = new ScoresStorageCloudflare(domainConfig);
2404
- backgroundTasks = new BackgroundTasksStorageCloudflare(domainConfig);
2405
- }
2406
- this.stores = {
2407
- workflows,
2408
- memory,
2409
- scores,
2410
- backgroundTasks
2411
- };
2412
- } catch (error$1) {
2413
- throw new error.MastraError(
2414
- {
2415
- id: storage.createStorageErrorId("CLOUDFLARE", "INIT", "FAILED"),
2416
- domain: error.ErrorDomain.STORAGE,
2417
- category: error.ErrorCategory.THIRD_PARTY
2418
- },
2419
- error$1
2420
- );
2421
- }
2422
- }
2423
- async close() {
2424
- }
2425
- };
2426
- var CloudflareStore = CloudflareKVStorage;
2427
-
2428
- exports.BackgroundTasksStorageCloudflare = BackgroundTasksStorageCloudflare;
2429
- exports.CloudflareKVStorage = CloudflareKVStorage;
2430
- exports.CloudflareStore = CloudflareStore;
2431
- exports.MemoryStorageCloudflare = MemoryStorageCloudflare;
2432
- exports.ScoresStorageCloudflare = ScoresStorageCloudflare;
2433
- exports.WorkflowsStorageCloudflare = WorkflowsStorageCloudflare;
2434
- //# sourceMappingURL=chunk-KF35N26R.cjs.map
2435
- //# sourceMappingURL=chunk-KF35N26R.cjs.map