@mastra/cloudflare 1.6.2 → 1.6.3-alpha.1

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,8 +1,8 @@
1
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
- import { BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, ScoresStorage, TABLE_BACKGROUND_TASKS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCORERS, TABLE_THREADS, TABLE_TRACES, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, filterByDateRange, normalizePerPage, serializeDate, storageMessageMatchesMetadataFilter, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
2
+ import { MastraCompositeStore, MemoryStorage, ScoresStorage, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCORERS, TABLE_THREADS, TABLE_TRACES, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, filterByDateRange, normalizePerPage, serializeDate, storageMessageMatchesMetadataFilter, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
3
3
  import Cloudflare from "cloudflare";
4
- import { MastraBase } from "@mastra/core/base";
5
4
  import { MessageList } from "@mastra/core/agent";
5
+ import { MastraBase } from "@mastra/core/base";
6
6
  import { saveScorePayloadSchema } from "@mastra/core/evals";
7
7
  //#region src/kv/storage/db/index.ts
8
8
  /**
@@ -348,7 +348,7 @@ var CloudflareKVDB = class extends MastraBase {
348
348
  await this.client.kv.namespaces.values.update(namespaceId, key, {
349
349
  account_id: this.accountId,
350
350
  value: serializedValue,
351
- metadata: serializedMetadata
351
+ ...serializedMetadata ? { metadata: serializedMetadata } : {}
352
352
  });
353
353
  }
354
354
  } catch (error) {
@@ -421,18 +421,35 @@ var CloudflareKVDB = class extends MastraBase {
421
421
  }
422
422
  async listNamespaceKeys(tableName, options) {
423
423
  try {
424
- if (this.bindings) return (await this.getBinding(tableName).list({
425
- limit: options?.limit || 1e3,
426
- prefix: options?.prefix
427
- })).keys;
428
- else {
424
+ const pageSize = options?.limit || 1e3;
425
+ const keys = [];
426
+ if (this.bindings) {
427
+ const binding = this.getBinding(tableName);
428
+ let cursor;
429
+ do {
430
+ const response = await binding.list({
431
+ limit: pageSize,
432
+ prefix: options?.prefix,
433
+ cursor
434
+ });
435
+ keys.push(...response.keys);
436
+ cursor = response.list_complete ? void 0 : response.cursor;
437
+ } while (cursor);
438
+ } else {
429
439
  const namespaceId = await this.getNamespaceId(tableName);
430
- return (await this.client.kv.namespaces.keys.list(namespaceId, {
431
- account_id: this.accountId,
432
- limit: options?.limit || 1e3,
433
- prefix: options?.prefix
434
- })).result;
440
+ let cursor;
441
+ do {
442
+ const page = await this.client.kv.namespaces.keys.list(namespaceId, {
443
+ account_id: this.accountId,
444
+ limit: pageSize,
445
+ prefix: options?.prefix,
446
+ ...cursor ? { cursor } : {}
447
+ });
448
+ keys.push(...page.result);
449
+ cursor = page.result_info?.cursor || void 0;
450
+ } while (cursor);
435
451
  }
452
+ return keys;
436
453
  } catch (error) {
437
454
  throw new MastraError({
438
455
  id: createStorageErrorId("CLOUDFLARE", "LIST_NAMESPACE_KEYS", "FAILED"),
@@ -467,149 +484,6 @@ var CloudflareKVDB = class extends MastraBase {
467
484
  }
468
485
  };
469
486
  //#endregion
470
- //#region src/kv/storage/domains/background-tasks/index.ts
471
- function toRecord(task) {
472
- return {
473
- id: task.id,
474
- tool_call_id: task.toolCallId,
475
- tool_name: task.toolName,
476
- agent_id: task.agentId,
477
- thread_id: task.threadId ?? null,
478
- resource_id: task.resourceId ?? null,
479
- run_id: task.runId,
480
- status: task.status,
481
- args: task.args,
482
- result: task.result ?? null,
483
- error: task.error ?? null,
484
- suspend_payload: task.suspendPayload ?? null,
485
- retry_count: task.retryCount,
486
- max_retries: task.maxRetries,
487
- timeout_ms: task.timeoutMs,
488
- createdAt: task.createdAt.toISOString(),
489
- startedAt: task.startedAt?.toISOString() ?? null,
490
- suspendedAt: task.suspendedAt?.toISOString() ?? null,
491
- completedAt: task.completedAt?.toISOString() ?? null
492
- };
493
- }
494
- function fromRecord(record) {
495
- return {
496
- id: record.id,
497
- status: record.status,
498
- toolName: record.tool_name,
499
- toolCallId: record.tool_call_id,
500
- args: record.args ?? {},
501
- agentId: record.agent_id,
502
- threadId: record.thread_id ?? void 0,
503
- resourceId: record.resource_id ?? void 0,
504
- runId: record.run_id ?? "",
505
- result: record.result ?? void 0,
506
- error: record.error ?? void 0,
507
- suspendPayload: record.suspend_payload ?? void 0,
508
- retryCount: Number(record.retry_count ?? 0),
509
- maxRetries: Number(record.max_retries ?? 0),
510
- timeoutMs: Number(record.timeout_ms ?? 3e5),
511
- createdAt: new Date(record.createdAt),
512
- startedAt: record.startedAt ? new Date(record.startedAt) : void 0,
513
- suspendedAt: record.suspendedAt ? new Date(record.suspendedAt) : void 0,
514
- completedAt: record.completedAt ? new Date(record.completedAt) : void 0
515
- };
516
- }
517
- var BackgroundTasksStorageCloudflare = class extends BackgroundTasksStorage {
518
- #db;
519
- constructor(config) {
520
- super();
521
- this.#db = new CloudflareKVDB(resolveCloudflareConfig(config));
522
- }
523
- async dangerouslyClearAll() {
524
- await this.#db.clearTable({ tableName: TABLE_BACKGROUND_TASKS });
525
- }
526
- async createTask(task) {
527
- await this.#db.putKV({
528
- tableName: TABLE_BACKGROUND_TASKS,
529
- key: task.id,
530
- value: toRecord(task)
531
- });
532
- }
533
- async updateTask(taskId, update) {
534
- const existing = await this.getTask(taskId);
535
- if (!existing) return;
536
- const merged = { ...existing };
537
- if ("status" in update) merged.status = update.status;
538
- if ("result" in update) merged.result = update.result;
539
- if ("error" in update) merged.error = update.error;
540
- if ("suspendPayload" in update) merged.suspendPayload = update.suspendPayload;
541
- if ("retryCount" in update) merged.retryCount = update.retryCount;
542
- if ("startedAt" in update) merged.startedAt = update.startedAt;
543
- if ("suspendedAt" in update) merged.suspendedAt = update.suspendedAt;
544
- if ("completedAt" in update) merged.completedAt = update.completedAt;
545
- await this.#db.putKV({
546
- tableName: TABLE_BACKGROUND_TASKS,
547
- key: taskId,
548
- value: toRecord(merged)
549
- });
550
- }
551
- async getTask(taskId) {
552
- const data = await this.#db.getKV(TABLE_BACKGROUND_TASKS, taskId);
553
- return data ? fromRecord(data) : null;
554
- }
555
- async listTasks(filter) {
556
- const keys = await this.#db.listKV(TABLE_BACKGROUND_TASKS);
557
- if (keys.length === 0) return {
558
- tasks: [],
559
- total: 0
560
- };
561
- let tasks = (await Promise.all(keys.map((k) => this.#db.getKV(TABLE_BACKGROUND_TASKS, k.name)))).filter(Boolean).map((r) => fromRecord(r));
562
- if (filter.status) {
563
- const s = Array.isArray(filter.status) ? filter.status : [filter.status];
564
- tasks = tasks.filter((t) => s.includes(t.status));
565
- }
566
- if (filter.agentId) tasks = tasks.filter((t) => t.agentId === filter.agentId);
567
- if (filter.threadId) tasks = tasks.filter((t) => t.threadId === filter.threadId);
568
- if (filter.toolName) tasks = tasks.filter((t) => t.toolName === filter.toolName);
569
- if (filter.toolCallId) tasks = tasks.filter((t) => t.toolCallId === filter.toolCallId);
570
- if (filter.runId) tasks = tasks.filter((t) => t.runId === filter.runId);
571
- const dateCol = filter.dateFilterBy ?? "createdAt";
572
- if (filter.fromDate) tasks = tasks.filter((t) => {
573
- const val = t[dateCol];
574
- return val != null && val >= filter.fromDate;
575
- });
576
- if (filter.toDate) tasks = tasks.filter((t) => {
577
- const val = t[dateCol];
578
- return val != null && val < filter.toDate;
579
- });
580
- const orderBy = filter.orderBy ?? "createdAt";
581
- const dir = filter.orderDirection === "desc" ? -1 : 1;
582
- tasks.sort((a, b) => ((a[orderBy]?.getTime() ?? 0) - (b[orderBy]?.getTime() ?? 0)) * dir);
583
- const total = tasks.length;
584
- if (filter.page != null && filter.perPage != null) {
585
- const start = filter.page * filter.perPage;
586
- tasks = tasks.slice(start, start + filter.perPage);
587
- } else if (filter.perPage != null) tasks = tasks.slice(0, filter.perPage);
588
- return {
589
- tasks,
590
- total
591
- };
592
- }
593
- async deleteTask(taskId) {
594
- await this.#db.deleteKV(TABLE_BACKGROUND_TASKS, taskId);
595
- }
596
- async deleteTasks(filter) {
597
- const { tasks } = await this.listTasks(filter);
598
- await Promise.all(tasks.map((t) => this.#db.deleteKV(TABLE_BACKGROUND_TASKS, t.id)));
599
- }
600
- async getRunningCount() {
601
- const { total } = await this.listTasks({ status: "running" });
602
- return total;
603
- }
604
- async getRunningCountByAgent(agentId) {
605
- const { total } = await this.listTasks({
606
- status: "running",
607
- agentId
608
- });
609
- return total;
610
- }
611
- };
612
- //#endregion
613
487
  //#region src/kv/storage/domains/memory/index.ts
614
488
  var MemoryStorageCloudflare = class extends MemoryStorage {
615
489
  supportsPartialThreadUpdate = true;
@@ -802,7 +676,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
802
676
  async deleteThread({ threadId }) {
803
677
  try {
804
678
  if (!await this.getThreadById({ threadId })) throw new Error(`Thread ${threadId} not found`);
805
- const threadMessageKeys = (await this.#db.listKV(TABLE_MESSAGES)).filter((key) => key.name.includes(`${TABLE_MESSAGES}:${threadId}:`));
679
+ const prefix = this.#db.namespacePrefix ? `${this.#db.namespacePrefix}:` : "";
680
+ const threadMessageKeys = (await this.#db.listKV(TABLE_MESSAGES, { prefix: `${prefix}${TABLE_MESSAGES}:${threadId}:` })).filter((key) => key.name.includes(`${TABLE_MESSAGES}:${threadId}:`));
806
681
  await Promise.all([
807
682
  this.#db.deleteKV(TABLE_MESSAGES, this.getThreadMessagesKey(threadId)),
808
683
  ...threadMessageKeys.map((key) => this.#db.deleteKV(TABLE_MESSAGES, key.name)),
@@ -2083,8 +1958,7 @@ var CloudflareKVStorage = class extends MastraCompositeStore {
2083
1958
  TABLE_THREADS,
2084
1959
  TABLE_MESSAGES,
2085
1960
  TABLE_WORKFLOW_SNAPSHOT,
2086
- TABLE_SCORERS,
2087
- TABLE_BACKGROUND_TASKS
1961
+ TABLE_SCORERS
2088
1962
  ];
2089
1963
  for (const table of requiredTables) if (!(table in config.bindings)) throw new Error(`Missing KV binding for table: ${table}`);
2090
1964
  }
@@ -2103,7 +1977,6 @@ var CloudflareKVStorage = class extends MastraCompositeStore {
2103
1977
  let workflows;
2104
1978
  let memory;
2105
1979
  let scores;
2106
- let backgroundTasks;
2107
1980
  if (isWorkersConfig(config)) {
2108
1981
  this.validateWorkersConfig(config);
2109
1982
  this.bindings = config.bindings;
@@ -2116,7 +1989,6 @@ var CloudflareKVStorage = class extends MastraCompositeStore {
2116
1989
  workflows = new WorkflowsStorageCloudflare(domainConfig);
2117
1990
  memory = new MemoryStorageCloudflare(domainConfig);
2118
1991
  scores = new ScoresStorageCloudflare(domainConfig);
2119
- backgroundTasks = new BackgroundTasksStorageCloudflare(domainConfig);
2120
1992
  } else {
2121
1993
  this.validateRestConfig(config);
2122
1994
  this.accountId = config.accountId.trim();
@@ -2131,13 +2003,11 @@ var CloudflareKVStorage = class extends MastraCompositeStore {
2131
2003
  workflows = new WorkflowsStorageCloudflare(domainConfig);
2132
2004
  memory = new MemoryStorageCloudflare(domainConfig);
2133
2005
  scores = new ScoresStorageCloudflare(domainConfig);
2134
- backgroundTasks = new BackgroundTasksStorageCloudflare(domainConfig);
2135
2006
  }
2136
2007
  this.stores = {
2137
2008
  workflows,
2138
2009
  memory,
2139
- scores,
2140
- backgroundTasks
2010
+ scores
2141
2011
  };
2142
2012
  } catch (error) {
2143
2013
  throw new MastraError({
@@ -2154,6 +2024,6 @@ var CloudflareKVStorage = class extends MastraCompositeStore {
2154
2024
  */
2155
2025
  const CloudflareStore = CloudflareKVStorage;
2156
2026
  //#endregion
2157
- export { MemoryStorageCloudflare as a, ScoresStorageCloudflare as i, CloudflareStore as n, BackgroundTasksStorageCloudflare as o, WorkflowsStorageCloudflare as r, CloudflareKVStorage as t };
2027
+ export { MemoryStorageCloudflare as a, ScoresStorageCloudflare as i, CloudflareStore as n, WorkflowsStorageCloudflare as r, CloudflareKVStorage as t };
2158
2028
 
2159
- //# sourceMappingURL=kv-DRnLtFWJ.js.map
2029
+ //# sourceMappingURL=kv-FPgTjsj1.js.map