@mastra/core 1.87.0-alpha.13 → 1.87.0-alpha.15

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.
Files changed (130) hide show
  1. package/dist/agent/durable/index.cjs +1 -1
  2. package/dist/agent/durable/index.js +1 -1
  3. package/dist/agent/index.cjs +2 -2
  4. package/dist/agent/index.js +2 -2
  5. package/dist/agent-builder/ee/index.cjs +1 -1
  6. package/dist/agent-builder/ee/index.js +1 -1
  7. package/dist/agent-controller/index.cjs +1 -1
  8. package/dist/agent-controller/index.js +1 -1
  9. package/dist/{agent-controller-DDxEG9Nd.cjs → agent-controller-DhDQXNoI.cjs} +5 -5
  10. package/dist/{agent-controller-DYwtbG2-.js → agent-controller-DihwxeVJ.js} +5 -5
  11. package/dist/background-tasks/index.cjs +1 -1
  12. package/dist/background-tasks/index.js +1 -1
  13. package/dist/{background-tasks-B8Lk1bt5.js → background-tasks-BoUX5G90.js} +1 -1
  14. package/dist/{background-tasks-LfQsDG6J.cjs → background-tasks-udYDvnlw.cjs} +1 -1
  15. package/dist/browser/index.cjs +1 -1
  16. package/dist/browser/index.js +1 -1
  17. package/dist/{builder-CPgUrTDP.cjs → builder-B2n-bUbl.cjs} +2 -2
  18. package/dist/{builder-DLaSPG2u.js → builder-Cn1lOWio.js} +2 -2
  19. package/dist/channels/index.cjs +2 -2
  20. package/dist/channels/index.js +2 -2
  21. package/dist/{channels-BPxJYR70.js → channels-DA3oMfhF.js} +1 -1
  22. package/dist/{channels-DH9fKqmy.cjs → channels-HRrlHnwF.cjs} +1 -1
  23. package/dist/coding-agent/index.cjs +2 -2
  24. package/dist/coding-agent/index.js +2 -2
  25. package/dist/{constants-Bou0hEgY.cjs → constants-CFO8w780.cjs} +8 -0
  26. package/dist/{constants-CFWgIaqA.js → constants-CUv0mU2y.js} +8 -0
  27. package/dist/datasets/index.cjs +2 -2
  28. package/dist/datasets/index.js +2 -2
  29. package/dist/docs/SKILL.md +1 -1
  30. package/dist/docs/assets/SOURCE_MAP.json +759 -749
  31. package/dist/docs/references/docs-harness-schedules.md +34 -0
  32. package/dist/docs/references/docs-signals-sending-signals.md +13 -0
  33. package/dist/docs/references/docs-signals-state-signals.md +1 -1
  34. package/dist/docs/references/reference-signals-time-signal-provider.md +35 -0
  35. package/dist/docs/references/reference-workspace-factory-sandbox.md +2 -0
  36. package/dist/evals/index.cjs +2 -2
  37. package/dist/evals/index.js +2 -2
  38. package/dist/evals/scoreTraces/index.cjs +2 -2
  39. package/dist/evals/scoreTraces/index.js +2 -2
  40. package/dist/harness/index.cjs +1 -1
  41. package/dist/harness/index.js +1 -1
  42. package/dist/index.cjs +1 -1
  43. package/dist/index.js +1 -1
  44. package/dist/knowledge/index.cjs +1 -1
  45. package/dist/knowledge/index.js +1 -1
  46. package/dist/llm/index.cjs +3 -3
  47. package/dist/llm/index.js +3 -3
  48. package/dist/{llm-DeOr7BXy.cjs → llm-Bljw7LII.cjs} +2 -2
  49. package/dist/{llm-DGa7alUy.js → llm-CxHzqEEI.js} +2 -2
  50. package/dist/loop/index.cjs +2 -2
  51. package/dist/loop/index.js +2 -2
  52. package/dist/{manager-BErWwr50.js → manager-BimN8ZdV.js} +3 -3
  53. package/dist/{manager-B-pQMauy.cjs → manager-DVYVB-3O.cjs} +3 -3
  54. package/dist/mastra/index.cjs +1 -1
  55. package/dist/mastra/index.js +1 -1
  56. package/dist/{mastra-B1BKkzX0.js → mastra-BpMvri3z.js} +17 -16
  57. package/dist/{mastra-CoWxmLQl.cjs → mastra-k8L1lFip.cjs} +17 -16
  58. package/dist/memory/index.cjs +2 -2
  59. package/dist/memory/index.js +2 -2
  60. package/dist/{model-CGH6nAvh.cjs → model-CrDuEDRq.cjs} +1 -1
  61. package/dist/{model-Bz3zffBv.js → model-sUJDcX2v.js} +1 -1
  62. package/dist/{netlify-CzbukKO2.js → netlify-BEJ96z-w.js} +1 -1
  63. package/dist/{netlify-D7oirBdu.cjs → netlify-Td-JUUkt.cjs} +1 -1
  64. package/dist/notifications/index.cjs +1 -1
  65. package/dist/notifications/index.js +1 -1
  66. package/dist/processor-provider/index.cjs +1 -1
  67. package/dist/processor-provider/index.js +1 -1
  68. package/dist/processors/index.cjs +2 -2
  69. package/dist/processors/index.js +2 -2
  70. package/dist/{provider-registry-DTaqnIYP.cjs → provider-registry-CCYXykIZ.cjs} +4 -4
  71. package/dist/{provider-registry-CdCkSE3h.js → provider-registry-DBG4hlGl.js} +4 -4
  72. package/dist/{registry-generator-CcgFsigf.cjs → registry-generator-BxiC9XcX.cjs} +1 -1
  73. package/dist/{registry-generator-Dbxm-MYh.js → registry-generator-D2lO3JJJ.js} +1 -1
  74. package/dist/{rehydrate-D7eaaJxI.cjs → rehydrate-BD0zOfc8.cjs} +2 -2
  75. package/dist/{rehydrate-BhmzzvtV.js → rehydrate-PRFAu8yl.js} +2 -2
  76. package/dist/relevance/index.cjs +2 -2
  77. package/dist/relevance/index.js +2 -2
  78. package/dist/{run-registry-59R9kE8Z.cjs → run-registry-BvMXuIb_.cjs} +530 -367
  79. package/dist/{run-registry-Du22tS_D.js → run-registry-Cqp-VFdv.js} +530 -367
  80. package/dist/{scheduler-B-VZUvv_.js → scheduler-0ShtMM1I.js} +71 -21
  81. package/dist/{scheduler-D00X03jQ.cjs → scheduler-CMjK0LoQ.cjs} +82 -20
  82. package/dist/signals/index.cjs +1 -1
  83. package/dist/signals/index.js +1 -1
  84. package/dist/signals/time-signal-provider.d.ts +8 -0
  85. package/dist/{signals-CIwzgkvN.cjs → signals-CbmgVwL-.cjs} +74 -7
  86. package/dist/{signals-BTfT-6DE.js → signals-Clupx3jz.js} +74 -7
  87. package/dist/storage/constants.cjs +1 -1
  88. package/dist/storage/constants.js +1 -1
  89. package/dist/storage/domains/knowledge/base.d.ts +33 -1
  90. package/dist/storage/domains/knowledge/inmemory.d.ts +2 -0
  91. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +20 -12
  92. package/dist/storage/domains/schedules/base.d.ts +31 -2
  93. package/dist/storage/domains/schedules/inmemory.d.ts +9 -2
  94. package/dist/storage/index.cjs +3 -3
  95. package/dist/storage/index.js +3 -3
  96. package/dist/stream/index.cjs +2 -2
  97. package/dist/stream/index.js +2 -2
  98. package/dist/{stream-mYc-fHPF.cjs → stream-BIbVD8V8.cjs} +1 -1
  99. package/dist/{stream-C_oNulbg.js → stream-D607FmAx.js} +1 -1
  100. package/dist/test-utils/llm-mock.cjs +1 -1
  101. package/dist/test-utils/llm-mock.js +1 -1
  102. package/dist/tool-loop-agent/index.cjs +1 -1
  103. package/dist/tool-loop-agent/index.js +1 -1
  104. package/dist/{tool-loop-agent-Bi09dOW5.cjs → tool-loop-agent-Cnf7vONA.cjs} +3 -3
  105. package/dist/{tool-loop-agent-Du1BJO8a.js → tool-loop-agent-eyoY_TEX.js} +3 -3
  106. package/dist/{utils-nyjsIsHZ.js → utils-CQkzZUcK.js} +1 -1
  107. package/dist/{utils-BGq3p2MX.cjs → utils-O1TXaFUl.cjs} +1 -1
  108. package/dist/utils.cjs +1 -1
  109. package/dist/utils.js +1 -1
  110. package/dist/{validate-CcE7gP2j.cjs → validate-CEgWy7P0.cjs} +1 -1
  111. package/dist/{validate-q0hhKzA4.js → validate-CTWjOlWp.js} +1 -1
  112. package/dist/vector/index.cjs +1 -1
  113. package/dist/vector/index.js +1 -1
  114. package/dist/worker/index.cjs +1 -1
  115. package/dist/worker/index.js +1 -1
  116. package/dist/{worker-DmJLbaGI.cjs → worker-CCDvbK3P.cjs} +2 -2
  117. package/dist/{worker-Dboi5I9k.js → worker-CCNb2aJe.js} +3 -3
  118. package/dist/{worker-Dzfx-9D0.cjs → worker-CI1joT3R.cjs} +3 -3
  119. package/dist/{worker-Wv2nS-Df.js → worker-D52cos24.js} +2 -2
  120. package/dist/{workflow-BPf1-mkb.cjs → workflow-BJL0qlPN.cjs} +3 -3
  121. package/dist/{workflow-CFfCkulP.js → workflow-DsmyWwxG.js} +3 -3
  122. package/dist/workflows/builder/index.cjs +1 -1
  123. package/dist/workflows/builder/index.js +1 -1
  124. package/dist/workflows/evented/index.cjs +1 -1
  125. package/dist/workflows/evented/index.js +1 -1
  126. package/dist/workflows/index.cjs +7 -5
  127. package/dist/workflows/index.js +6 -6
  128. package/dist/workflows/scheduler/claim.d.ts +51 -0
  129. package/dist/workflows/scheduler/index.d.ts +2 -0
  130. package/package.json +7 -7
@@ -4,14 +4,14 @@ const require_base = require("./base-BIzR1D3_.cjs");
4
4
  const require_observability = require("./observability-B0R_D1PZ.cjs");
5
5
  const require_error = require("./error-D90lJ6M7.cjs");
6
6
  const require_error$1 = require("./error-L1V4uUbd.cjs");
7
- const require_stream = require("./stream-mYc-fHPF.cjs");
7
+ const require_stream = require("./stream-BIbVD8V8.cjs");
8
8
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
9
9
  const require_output_helpers = require("./output-helpers-DgsH4aTb.cjs");
10
10
  const require_message_list = require("./message-list-C0F2sDNC.cjs");
11
11
  const require_storage = require("./storage-CfG0I2aF.cjs");
12
12
  const require_utils = require("./utils-D-eNsgDM.cjs");
13
13
  const require_error_count = require("./error-count-DeDpeWU2.cjs");
14
- const require_llm = require("./llm-DeOr7BXy.cjs");
14
+ const require_llm = require("./llm-Bljw7LII.cjs");
15
15
  const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
16
16
  const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
17
17
  const require_signals = require("./signals-CWxAMEmE.cjs");
@@ -23,13 +23,13 @@ const require_tool = require("./tool-CYlT2UA-.cjs");
23
23
  const require_toolchecks = require("./toolchecks-MFU48cit.cjs");
24
24
  const require_fetchWithRetry = require("./fetchWithRetry-f5k4p7_1.cjs");
25
25
  const require_model = require("./model-jBymoqGa.cjs");
26
- const require_provider_registry = require("./provider-registry-DTaqnIYP.cjs");
26
+ const require_provider_registry = require("./provider-registry-CCYXykIZ.cjs");
27
27
  const require_inmemory = require("./inmemory-Dc86VWGB.cjs");
28
28
  const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
29
- const require_model$1 = require("./model-CGH6nAvh.cjs");
30
- const require_utils$1 = require("./utils-BGq3p2MX.cjs");
29
+ const require_model$1 = require("./model-CrDuEDRq.cjs");
30
+ const require_utils$1 = require("./utils-O1TXaFUl.cjs");
31
31
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
32
- const require_background_tasks = require("./background-tasks-LfQsDG6J.cjs");
32
+ const require_background_tasks = require("./background-tasks-udYDvnlw.cjs");
33
33
  const require_stream$1 = require("./stream-BGbj9jAU.cjs");
34
34
  const require_predicate_index = require("./predicate/index.cjs");
35
35
  const require_classifier_index = require("./classifier/index.cjs");
@@ -38,7 +38,7 @@ const require_workflows_constants = require("./workflows/constants.cjs");
38
38
  const require_hooks = require("./hooks-D7VDBETj.cjs");
39
39
  const require_schedules = require("./schedules-BZS8McF7.cjs");
40
40
  const require_state_processor = require("./state-processor-kRNZ38Nf.cjs");
41
- const require_constants = require("./constants-Bou0hEgY.cjs");
41
+ const require_constants = require("./constants-CFO8w780.cjs");
42
42
  const require_signal_provider = require("./signal-provider-BFAvh_AJ.cjs");
43
43
  const require_slugify = require("./slugify-B_WzG9IY.cjs");
44
44
  const require_workspace = require("./workspace-CzzrnE6Q.cjs");
@@ -40938,6 +40938,12 @@ var InMemoryKnowledgePageStore = class {
40938
40938
  read: input.read
40939
40939
  })));
40940
40940
  }
40941
+ async getPagesAtPaths(input) {
40942
+ return Promise.all(input.lookups.map((lookup) => this.getPageByPath({
40943
+ ...lookup,
40944
+ read: input.read
40945
+ })));
40946
+ }
40941
40947
  async getLastChildPositions(input) {
40942
40948
  return Object.fromEntries([...new Set(input.parentIds)].map((id) => [id, this.#children(id).sort(byPosition).at(-1)?.position ?? null]));
40943
40949
  }
@@ -41479,9 +41485,37 @@ var InMemoryKnowledgePageStore = class {
41479
41485
  this.#pins.set(key, pin);
41480
41486
  return clone$1(pin);
41481
41487
  }
41488
+ async listPinsByTier(input) {
41489
+ const { tiers, count, limit, ...filters } = input;
41490
+ const rank = (pin) => tiers.findIndex((tier) => pin.audience.some((entry) => tier.includes(entry)));
41491
+ const pins = this.#matchingPins({
41492
+ ...filters,
41493
+ audience: tiers.flat()
41494
+ }).sort((a, b) => rank(a) - rank(b));
41495
+ return {
41496
+ pins: pins.slice(0, pageSize(limit)).map((pin) => this.#listed(pin)),
41497
+ ...count ? { total: pins.length } : {}
41498
+ };
41499
+ }
41482
41500
  async listPins(input) {
41501
+ const pins = this.#matchingPins(input);
41502
+ const { items, nextCursor } = paginate(pins, input.cursor, input.limit);
41503
+ return {
41504
+ pins: items.map((pin) => this.#listed(pin)),
41505
+ ...nextCursor ? { nextCursor } : {},
41506
+ ...input.count ? { total: pins.length } : {}
41507
+ };
41508
+ }
41509
+ #listed(pin) {
41510
+ return {
41511
+ ...clone$1(pin),
41512
+ pageName: this.#pages.get(pin.pageId).name
41513
+ };
41514
+ }
41515
+ /** The pins {@link listPins} lists, newest first, before paging. */
41516
+ #matchingPins(input) {
41483
41517
  const audience = input.audience === "all" ? null : new Set(input.audience);
41484
- const pins = [...this.#pins.values()].filter((pin) => {
41518
+ return [...this.#pins.values()].filter((pin) => {
41485
41519
  const page = this.#pages.get(pin.pageId);
41486
41520
  if (!page || page.deletedAt || !this.#pageReadable(page, input.read)) return false;
41487
41521
  if (input.kind && pin.kind !== input.kind) return false;
@@ -41490,15 +41524,6 @@ var InMemoryKnowledgePageStore = class {
41490
41524
  if (pin.kind === "page" && input.withBody && !/\S/.test(page.body ?? "")) return false;
41491
41525
  return !audience || pin.audience.some((entry) => audience.has(entry));
41492
41526
  }).sort(newestFirst);
41493
- const { items, nextCursor } = paginate(pins, input.cursor, input.limit);
41494
- return {
41495
- pins: items.map((pin) => ({
41496
- ...clone$1(pin),
41497
- pageName: this.#pages.get(pin.pageId).name
41498
- })),
41499
- ...nextCursor ? { nextCursor } : {},
41500
- ...input.count ? { total: pins.length } : {}
41501
- };
41502
41527
  }
41503
41528
  };
41504
41529
  // src/storage/domains/knowledge/inmemory.ts
@@ -41532,6 +41557,12 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
41532
41557
  getPagesByPaths(input) {
41533
41558
  return this.#pageStore.getPagesByPaths(input);
41534
41559
  }
41560
+ getPagesAtPaths(input) {
41561
+ return this.#pageStore.getPagesAtPaths(input);
41562
+ }
41563
+ listPinsByTier(input) {
41564
+ return this.#pageStore.listPinsByTier(input);
41565
+ }
41535
41566
  getLastChildPositions(input) {
41536
41567
  return this.#pageStore.getLastChildPositions(input);
41537
41568
  }
@@ -44168,6 +44199,20 @@ var SchedulesStorage = class extends require_filesystem_versioned.StorageDomain
44168
44199
  });
44169
44200
  }
44170
44201
  async dangerouslyClearAll() {}
44202
+ /**
44203
+ * A view of this store holding one tenant's schedules. Ids are unique per
44204
+ * tenant, every read and write is limited to the tenant's rows, and created
44205
+ * rows carry its `tenantId`.
44206
+ *
44207
+ * The store this is called on keeps seeing only rows without a tenant,
44208
+ * except `listDueSchedules`, which spans every tenant so one tick can claim
44209
+ * what's due everywhere; claim a tenant's row through its `forTenant` view.
44210
+ *
44211
+ * Adapters that don't support tenants throw rather than ignore the tenant.
44212
+ */
44213
+ forTenant(_tenantId) {
44214
+ throw new Error(`${this.constructor.name} does not support tenant-scoped schedules`);
44215
+ }
44171
44216
  };
44172
44217
  // src/storage/domains/schedules/inmemory.ts
44173
44218
  function clone(value) {
@@ -44179,28 +44224,57 @@ function cloneRow(row) {
44179
44224
  copy.target = normalizeScheduleTarget(copy.target);
44180
44225
  return copy;
44181
44226
  }
44182
- var InMemorySchedulesStorage = class extends SchedulesStorage {
44227
+ var InMemorySchedulesStorage = class InMemorySchedulesStorage extends SchedulesStorage {
44183
44228
  db;
44184
- constructor({ db }) {
44229
+ #tenantId;
44230
+ constructor({ db, tenantId }) {
44185
44231
  super();
44186
44232
  this.db = db;
44233
+ this.#tenantId = tenantId;
44234
+ }
44235
+ forTenant(tenantId) {
44236
+ return new InMemorySchedulesStorage({
44237
+ db: this.db,
44238
+ tenantId
44239
+ });
44240
+ }
44241
+ /** Map key: root and tenant keys start differently, so neither can reach the other's rows. */
44242
+ #key(id) {
44243
+ return this.#tenantId === void 0 ? `root:${id}` : `tenant:${encodeURIComponent(this.#tenantId)}/${id}`;
44244
+ }
44245
+ #mine(row) {
44246
+ return row.tenantId === this.#tenantId;
44187
44247
  }
44248
+ /** The root store clears everything; a tenant's view clears only that tenant. */
44188
44249
  async dangerouslyClearAll() {
44189
- this.db.schedules.clear();
44190
- this.db.scheduleTriggers.length = 0;
44250
+ if (this.#tenantId === void 0) {
44251
+ this.db.schedules.clear();
44252
+ this.db.scheduleTriggers.length = 0;
44253
+ return;
44254
+ }
44255
+ for (const [key, row] of this.db.schedules) if (this.#mine(row)) this.db.schedules.delete(key);
44256
+ const triggers = this.db.scheduleTriggers;
44257
+ let kept = 0;
44258
+ for (const row of triggers) if (!this.#mine(row)) triggers[kept++] = row;
44259
+ triggers.length = kept;
44191
44260
  }
44192
44261
  async createSchedule(schedule) {
44193
- if (this.db.schedules.has(schedule.id)) throw new Error(`Schedule ${schedule.id} already exists`);
44194
- const stored = clone(schedule);
44195
- this.db.schedules.set(stored.id, stored);
44262
+ const key = this.#key(schedule.id);
44263
+ if (this.db.schedules.has(key)) throw new Error(`Schedule ${schedule.id} already exists`);
44264
+ const { tenantId: _ignored, ...rest } = schedule;
44265
+ const stored = clone(this.#tenantId === void 0 ? rest : {
44266
+ ...rest,
44267
+ tenantId: this.#tenantId
44268
+ });
44269
+ this.db.schedules.set(key, stored);
44196
44270
  return clone(stored);
44197
44271
  }
44198
44272
  async getSchedule(id) {
44199
- const found = this.db.schedules.get(id);
44273
+ const found = this.db.schedules.get(this.#key(id));
44200
44274
  return found ? cloneRow(found) : null;
44201
44275
  }
44202
44276
  async listSchedules(filter) {
44203
- let rows = Array.from(this.db.schedules.values());
44277
+ let rows = Array.from(this.db.schedules.values()).filter((r) => this.#mine(r));
44204
44278
  if (filter?.status) rows = rows.filter((r) => r.status === filter.status);
44205
44279
  if (filter?.workflowId) rows = rows.filter((r) => r.target.type === "workflow" && r.target.workflowId === filter.workflowId);
44206
44280
  if (filter?.ownerType !== void 0) rows = rows.filter((r) => (r.ownerType ?? null) === filter.ownerType);
@@ -44208,28 +44282,37 @@ var InMemorySchedulesStorage = class extends SchedulesStorage {
44208
44282
  rows.sort((a, b) => a.createdAt - b.createdAt);
44209
44283
  return rows.map(cloneRow);
44210
44284
  }
44211
- async listDueSchedules(now, limit) {
44285
+ async listDueSchedules(now, limit, options) {
44212
44286
  const due = [];
44213
- for (const row of this.db.schedules.values()) if (row.status === "active" && row.nextFireAt <= now) due.push(row);
44287
+ for (const row of this.db.schedules.values()) {
44288
+ if (this.#tenantId !== void 0) {
44289
+ if (!this.#mine(row)) continue;
44290
+ } else if (options?.unscoped && row.tenantId !== void 0) continue;
44291
+ else if (options?.tenants && row.tenantId === void 0) continue;
44292
+ if (row.status === "active" && row.nextFireAt <= now) due.push(row);
44293
+ }
44214
44294
  due.sort((a, b) => a.nextFireAt - b.nextFireAt);
44215
44295
  const cap = limit ?? due.length;
44216
44296
  return due.slice(0, cap).map(cloneRow);
44217
44297
  }
44218
44298
  async updateSchedule(id, patch) {
44219
- const existing = this.db.schedules.get(id);
44299
+ const existing = this.db.schedules.get(this.#key(id));
44220
44300
  if (!existing) throw new Error(`Schedule ${id} not found`);
44221
- const stored = clone({
44301
+ const updated = {
44222
44302
  ...existing,
44223
44303
  ...patch,
44224
44304
  target: patch.target !== void 0 ? patch.target : existing.target,
44225
44305
  metadata: patch.metadata !== void 0 ? patch.metadata : existing.metadata,
44226
44306
  updatedAt: Date.now()
44227
- });
44228
- this.db.schedules.set(id, stored);
44307
+ };
44308
+ if (existing.tenantId === void 0) delete updated.tenantId;
44309
+ else updated.tenantId = existing.tenantId;
44310
+ const stored = clone(updated);
44311
+ this.db.schedules.set(this.#key(id), stored);
44229
44312
  return cloneRow(stored);
44230
44313
  }
44231
44314
  async updateScheduleNextFire(id, expectedNextFireAt, newNextFireAt, lastFireAt, lastRunId, newStatus) {
44232
- const existing = this.db.schedules.get(id);
44315
+ const existing = this.db.schedules.get(this.#key(id));
44233
44316
  if (!existing) return false;
44234
44317
  if (existing.nextFireAt !== expectedNextFireAt) return false;
44235
44318
  if (existing.status !== "active") return false;
@@ -44241,23 +44324,28 @@ var InMemorySchedulesStorage = class extends SchedulesStorage {
44241
44324
  ...newStatus ? { status: newStatus } : {},
44242
44325
  updatedAt: Date.now()
44243
44326
  };
44244
- this.db.schedules.set(id, stored);
44327
+ this.db.schedules.set(this.#key(id), stored);
44245
44328
  return true;
44246
44329
  }
44247
44330
  async deleteSchedule(id) {
44248
- this.db.schedules.delete(id);
44249
- for (let i = this.db.scheduleTriggers.length - 1; i >= 0; i--) if (this.db.scheduleTriggers[i].scheduleId === id) this.db.scheduleTriggers.splice(i, 1);
44331
+ this.db.schedules.delete(this.#key(id));
44332
+ for (let i = this.db.scheduleTriggers.length - 1; i >= 0; i--) {
44333
+ const trigger = this.db.scheduleTriggers[i];
44334
+ if (trigger.scheduleId === id && this.#mine(trigger)) this.db.scheduleTriggers.splice(i, 1);
44335
+ }
44250
44336
  }
44251
44337
  async recordTrigger(trigger) {
44338
+ const { tenantId: _ignored, ...rest } = trigger;
44252
44339
  const stored = {
44253
- ...trigger,
44340
+ ...rest,
44341
+ ...this.#tenantId === void 0 ? {} : { tenantId: this.#tenantId },
44254
44342
  id: trigger.id ?? globalThis.crypto.randomUUID(),
44255
44343
  triggerKind: trigger.triggerKind ?? "schedule-fire"
44256
44344
  };
44257
44345
  this.db.scheduleTriggers.push(clone(stored));
44258
44346
  }
44259
44347
  async listTriggers(scheduleId, opts) {
44260
- let rows = this.db.scheduleTriggers.filter((f) => f.scheduleId === scheduleId);
44348
+ let rows = this.db.scheduleTriggers.filter((f) => f.scheduleId === scheduleId && this.#mine(f));
44261
44349
  if (opts?.fromActualFireAt != null) rows = rows.filter((f) => f.actualFireAt >= opts.fromActualFireAt);
44262
44350
  if (opts?.toActualFireAt != null) rows = rows.filter((f) => f.actualFireAt < opts.toActualFireAt);
44263
44351
  rows.sort((a, b) => b.actualFireAt - a.actualFireAt);
@@ -66483,16 +66571,28 @@ async function configPins(run, maxTokens) {
66483
66571
  listings: []
66484
66572
  };
66485
66573
  const scopes = await run.storage.getScopesByAddress([...new Set(bound.map((pin) => pin.address))]);
66574
+ const scopeOf = new Map(scopes.map((scope) => [scope.address, scope]));
66575
+ const lookups = bound.flatMap((pin) => {
66576
+ const scope = scopeOf.get(pin.address);
66577
+ return scope && pin.path.length > 0 ? [{
66578
+ scopeId: scope.id,
66579
+ path: pin.path
66580
+ }] : [];
66581
+ });
66582
+ const found = lookups.length === 0 ? [] : run.storage.getPagesAtPaths ? await run.storage.getPagesAtPaths({
66583
+ lookups,
66584
+ read: run.read
66585
+ }) : await Promise.all(lookups.map((lookup) => run.storage.getPageByPath({
66586
+ ...lookup,
66587
+ read: run.read
66588
+ })));
66589
+ let next = 0;
66486
66590
  const pages = /* @__PURE__ */ new Map();
66487
66591
  const listings = /* @__PURE__ */ new Map();
66488
66592
  for (const pin of bound) {
66489
- const scope = scopes.find((candidate) => candidate.address === pin.address);
66593
+ const scope = scopeOf.get(pin.address);
66490
66594
  if (!scope) continue;
66491
- const page = pin.path.length === 0 ? knowledgeScopeReadable(scope, run.read) ? scope : null : await run.storage.getPageByPath({
66492
- scopeId: scope.id,
66493
- path: pin.path,
66494
- read: run.read
66495
- });
66595
+ const page = pin.path.length === 0 ? knowledgeScopeReadable(scope, run.read) ? scope : null : found[next++];
66496
66596
  if (!page || page.deletedAt) continue;
66497
66597
  if (pin.depth === void 0) pages.set(page.id, page);
66498
66598
  else if ((listings.get(page.id)?.depth ?? 0) < pin.depth) listings.set(page.id, await resolveListing(run, page, pin.depth, maxTokens));
@@ -66514,6 +66614,28 @@ async function rankedStoredPins(run, excludePageIds, want) {
66514
66614
  withBody: true,
66515
66615
  excludePageIds
66516
66616
  };
66617
+ if (tiers.length === 0) return {
66618
+ pins: [],
66619
+ total: 0
66620
+ };
66621
+ if (run.storage.listPinsByTier && want <= 100) {
66622
+ const ranked = await run.storage.listPinsByTier({
66623
+ ...base,
66624
+ tiers,
66625
+ limit: want,
66626
+ count: true
66627
+ });
66628
+ const total = ranked.total ?? (await run.storage.listPins({
66629
+ ...base,
66630
+ audience: run.principals,
66631
+ limit: 1,
66632
+ count: true
66633
+ })).total ?? 0;
66634
+ return {
66635
+ pins: ranked.pins,
66636
+ total
66637
+ };
66638
+ }
66517
66639
  const pins = [];
66518
66640
  const seen = /* @__PURE__ */ new Set();
66519
66641
  let total;
@@ -66537,7 +66659,7 @@ async function rankedStoredPins(run, excludePageIds, want) {
66537
66659
  } while (cursor && pins.length < want);
66538
66660
  if (pins.length >= want) break;
66539
66661
  }
66540
- if (total === void 0) total = tiers.length === 0 ? 0 : (await run.storage.listPins({
66662
+ if (total === void 0) total = (await run.storage.listPins({
66541
66663
  ...base,
66542
66664
  audience: run.principals,
66543
66665
  limit: 1,
@@ -80149,22 +80271,29 @@ function createDurableLLMExecutionStep(_options) {
80149
80271
  }
80150
80272
  throwIfInterrupted();
80151
80273
  cleanupToolObservabilitySpans(true);
80152
- logger?.error?.("Error processing LLM stream", {
80153
- error,
80154
- runId
80155
- });
80156
80274
  const errorObj = error instanceof Error ? error : new Error(String(error));
80157
- if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80158
- error: errorObj,
80159
- endSpan: false
80160
- });
80161
- else if (modelSpan) modelSpan.error({
80162
- error: errorObj,
80163
- endSpan: false
80164
- });
80165
80275
  const innerTimeout = resolveTotalTimeoutAbort(executionAbortSignal, errorObj);
80276
+ const isAbort = !innerTimeout && (executionAbortSignal?.aborted === true || errorObj.name === "AbortError");
80277
+ if (!isAbort) {
80278
+ logger?.error?.("Error processing LLM stream", {
80279
+ error,
80280
+ runId
80281
+ });
80282
+ if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80283
+ error: errorObj,
80284
+ endSpan: false
80285
+ });
80286
+ else if (modelSpan) modelSpan.error({
80287
+ error: errorObj,
80288
+ endSpan: false
80289
+ });
80290
+ }
80166
80291
  if (innerTimeout) throw innerTimeout;
80167
- if (executionAbortSignal?.aborted === true || errorObj.name === "AbortError") {
80292
+ if (isAbort) {
80293
+ logger?.debug?.("LLM stream aborted", {
80294
+ error: errorObj,
80295
+ runId
80296
+ });
80168
80297
  materializeStreamedMessages();
80169
80298
  return {
80170
80299
  ...await storeStepTranscript(),
@@ -80229,21 +80358,28 @@ function createDurableLLMExecutionStep(_options) {
80229
80358
  const streamError = outputStream.error;
80230
80359
  if (streamError) {
80231
80360
  const streamErrorObj = streamError instanceof Error ? streamError : new Error(String(streamError));
80232
- logger?.error?.("Stream captured error", {
80233
- error: streamErrorObj,
80234
- runId
80235
- });
80236
- if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80237
- error: streamErrorObj,
80238
- endSpan: false
80239
- });
80240
- else if (modelSpan) modelSpan.error({
80241
- error: streamErrorObj,
80242
- endSpan: false
80243
- });
80244
80361
  const streamErrorTimeout = resolveTotalTimeoutAbort(executionAbortSignal, streamErrorObj);
80362
+ const isStreamErrorAbort = !streamErrorTimeout && (executionAbortSignal?.aborted === true || streamErrorObj.name === "AbortError");
80363
+ if (!isStreamErrorAbort) {
80364
+ logger?.error?.("Stream captured error", {
80365
+ error: streamErrorObj,
80366
+ runId
80367
+ });
80368
+ if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80369
+ error: streamErrorObj,
80370
+ endSpan: false
80371
+ });
80372
+ else if (modelSpan) modelSpan.error({
80373
+ error: streamErrorObj,
80374
+ endSpan: false
80375
+ });
80376
+ }
80245
80377
  if (streamErrorTimeout) throw streamErrorTimeout;
80246
- if (executionAbortSignal?.aborted === true || streamErrorObj.name === "AbortError") {
80378
+ if (isStreamErrorAbort) {
80379
+ logger?.debug?.("Captured LLM stream aborted", {
80380
+ error: streamErrorObj,
80381
+ runId
80382
+ });
80247
80383
  materializeStreamedMessages();
80248
80384
  return {
80249
80385
  ...await storeStepTranscript(),
@@ -86217,7 +86353,7 @@ async function prepareForDurableExecution(options) {
86217
86353
  });
86218
86354
  let tripwireData;
86219
86355
  if (inputProcessors.length > 0) try {
86220
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-mYc-fHPF.cjs")).then((n) => n.runner_exports);
86356
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-BIbVD8V8.cjs")).then((n) => n.runner_exports);
86221
86357
  await new ProcessorRunner({
86222
86358
  inputProcessors,
86223
86359
  outputProcessors,
@@ -96091,7 +96227,7 @@ var Agent = class Agent extends require_base.MastraBase {
96091
96227
  }
96092
96228
  }
96093
96229
  /** Rebuilds process-local recovery state from the persisted durable workflow input. */
96094
- async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
96230
+ async #rehydrateRecoveryState({ runId, workflowInput, abortController, onTerminalDeadline, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
96095
96231
  const requestContext = workflowInput.requestContextEntries ? new require_request_context.RequestContext(Object.entries(workflowInput.requestContextEntries)) : new require_request_context.RequestContext();
96096
96232
  restoreRunAgentScopes(requestContext);
96097
96233
  const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
@@ -96307,7 +96443,7 @@ var Agent = class Agent extends require_base.MastraBase {
96307
96443
  subscribePendingSignals: (listener) => wrapped.__getSubscribePendingSignals()(runId, listener),
96308
96444
  cleanup: () => {}
96309
96445
  };
96310
- this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
96446
+ this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence, onTerminalDeadline);
96311
96447
  this.#runInputs.set(executionFence, {
96312
96448
  ...workflowInput,
96313
96449
  messageListState: latestMessageListState ?? workflowInput.messageListState
@@ -96506,7 +96642,7 @@ var Agent = class Agent extends require_base.MastraBase {
96506
96642
  * each session gets a fresh timer. The timer is torn down via the entry's
96507
96643
  * `cleanup` slot, which every settle path invokes through the run registry.
96508
96644
  */
96509
- installAbortWithTotalTimeout(entry, abortController, executionFence) {
96645
+ installAbortWithTotalTimeout(entry, abortController, executionFence, onTerminalDeadline) {
96510
96646
  entry.abortController = abortController;
96511
96647
  entry.deadlineErrorRedelivered = false;
96512
96648
  const totalTimeout = require_stream.createTimeoutAbortSignal({
@@ -96518,10 +96654,14 @@ var Agent = class Agent extends require_base.MastraBase {
96518
96654
  entry.abortSignal = totalTimeout.signal;
96519
96655
  if (totalTimeout.timeoutPromise) totalTimeout.timeoutPromise.catch(async (error) => {
96520
96656
  if (!require_stream.isMastraTimeoutError(error) || error.timeoutType !== "total" || totalTimeout.signal?.reason !== error) return;
96521
- await this.settleExecution(executionFence.runId, executionFence, {
96522
- status: "failed",
96523
- error
96524
- });
96657
+ try {
96658
+ await this.settleExecution(executionFence.runId, executionFence, {
96659
+ status: "failed",
96660
+ error
96661
+ });
96662
+ } finally {
96663
+ onTerminalDeadline?.();
96664
+ }
96525
96665
  }).catch((error) => {
96526
96666
  this.logger.warn("Failed to settle durable agent at its total deadline", { error });
96527
96667
  });
@@ -96620,11 +96760,19 @@ var Agent = class Agent extends require_base.MastraBase {
96620
96760
  }
96621
96761
  this.executionEngine.assertRecoveryActive();
96622
96762
  const releaseLocalRecovery = this.executionEngine.claimLocalRecovery(this.id, this.name, runId);
96623
- const { controller: abortController } = createRunAbortController(options?.abortSignal);
96763
+ const { controller: abortController, detach: detachExternalAbort } = createRunAbortController(options?.abortSignal);
96764
+ let recoveryReleased = false;
96765
+ const releaseRecovery = () => {
96766
+ if (recoveryReleased) return;
96767
+ recoveryReleased = true;
96768
+ detachExternalAbort();
96769
+ releaseLocalRecovery();
96770
+ };
96624
96771
  let executionFence;
96625
96772
  let recoveryState;
96626
96773
  let finishPublishedBeforeCrash;
96627
96774
  let claimedSnapshot;
96775
+ let recoveryHandedOff = false;
96628
96776
  try {
96629
96777
  executionFence = await this.executionEngine.claimExecution(runId, options?.force ? "takeover" : "recover", this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, this.logger, this.#untrackedRunLiveness(runId, workflowInput));
96630
96778
  this.executionEngine.assertRecoveryActive();
@@ -96638,6 +96786,7 @@ var Agent = class Agent extends require_base.MastraBase {
96638
96786
  runId,
96639
96787
  workflowInput,
96640
96788
  abortController,
96789
+ onTerminalDeadline: detachExternalAbort,
96641
96790
  executionFence,
96642
96791
  originalSpansEnded: loaded.originalSpansEnded,
96643
96792
  openStepsOf: loaded.openStepsOf,
@@ -96647,146 +96796,154 @@ var Agent = class Agent extends require_base.MastraBase {
96647
96796
  this.#recoveredEntries.set(executionFence, recoveryState.registryEntry);
96648
96797
  this.executionEngine.assertRecoveryActive();
96649
96798
  } catch (error) {
96650
- const settlement = await executionFence?.settle(async () => {});
96651
- if (executionFence && settlement !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96652
- releaseLocalRecovery();
96653
- throw error;
96654
- }
96655
- const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } = recoveryState;
96656
- if (executionFence.generation !== void 0) {
96657
- const supersededFrom = await this.executionEngine.recoverySupersededFrom(workflowsStore, runId, claimedSnapshot, () => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, () => this.logger);
96658
- await emitOwnershipClaimedEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, executionFence.generation, supersededFrom).catch((error) => {
96659
- this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {
96660
- runId,
96661
- error
96662
- });
96663
- });
96664
- }
96665
- setExecutionClaim(requestContext, runId, executionFence.claim);
96666
- registryEntry.executionFence = executionFence;
96667
- let streamCleanup;
96668
- const cleanupOwnedRegistryState = () => {
96669
- if (registryEntry.executionFence !== executionFence) return;
96670
- if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
96671
- if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {
96672
- globalRunRegistry.delete(runId);
96673
- if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96674
- }
96675
- };
96676
- const runCleanup = createRunCleanup({
96677
- scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96678
- release: () => {
96679
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96680
- streamCleanup?.();
96681
- cleanupOwnedRegistryState();
96799
+ try {
96800
+ const settlement = await executionFence?.settle(async () => {});
96801
+ if (executionFence && settlement !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96802
+ } finally {
96803
+ releaseRecovery();
96682
96804
  }
96683
- });
96684
- const performCleanup = runCleanup.run;
96685
- const scheduleAutoCleanup = runCleanup.schedule;
96686
- let workflow;
96687
- try {
96688
- this.executionEngine.assertRecoveryActive();
96689
- workflow = this.getWorkflow();
96690
- } catch (error) {
96691
- if (await executionFence.settle(async () => {}) !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96692
- releaseLocalRecovery();
96693
96805
  throw error;
96694
96806
  }
96695
- const { stream, threadRegistration } = await this.#setupRecoveredStream({
96696
- runId,
96697
- workflowInput,
96698
- requestContext,
96699
- threadId,
96700
- resourceId,
96701
- messageList,
96702
- registryEntry,
96703
- options,
96704
- scheduleAutoCleanup,
96705
- executionFence
96706
- }).catch((error) => {
96707
- releaseLocalRecovery();
96708
- throw error;
96709
- });
96710
- const { output, cleanup: createdStreamCleanup, ready } = stream;
96711
- streamCleanup = createdStreamCleanup;
96712
- const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96713
- const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96714
- const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, require_observability.createObservabilityContext({ currentSpan: recoverAgentSpan }));
96715
- if (finishPublishedBeforeCrash && result?.status === "success") {
96716
- const { output: finalOutput, stepResult, tracingTermination, stopCause } = result.result;
96717
- recoverModelSpan?.end({ ...tracingTermination });
96718
- recoverAgentSpan?.end({
96719
- ...tracingTermination,
96720
- output: { text: finalOutput?.text }
96721
- });
96722
- await emitFinishEvent(recoveryPubsub, runId, {
96723
- output: finalOutput,
96724
- stepResult,
96725
- ...stopCause && { stopCause }
96807
+ try {
96808
+ const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } = recoveryState;
96809
+ if (executionFence.generation !== void 0) {
96810
+ const supersededFrom = await this.executionEngine.recoverySupersededFrom(workflowsStore, runId, claimedSnapshot, () => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, () => this.logger);
96811
+ await emitOwnershipClaimedEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, executionFence.generation, supersededFrom).catch((error) => {
96812
+ this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {
96813
+ runId,
96814
+ error
96815
+ });
96726
96816
  });
96727
96817
  }
96728
- if (result?.status === "suspended" && options?.closeOnSuspend) {
96729
- await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
96730
- await stream.waitForEventDelivery();
96731
- executionFence.throwIfLost();
96732
- stream.detach();
96818
+ setExecutionClaim(requestContext, runId, executionFence.claim);
96819
+ registryEntry.executionFence = executionFence;
96820
+ let streamCleanup;
96821
+ const cleanupOwnedRegistryState = () => {
96822
+ if (registryEntry.executionFence !== executionFence) return;
96823
+ if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
96824
+ if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {
96825
+ globalRunRegistry.delete(runId);
96826
+ if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96827
+ }
96828
+ };
96829
+ const runCleanup = createRunCleanup({
96830
+ scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96831
+ release: () => {
96832
+ agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96833
+ streamCleanup?.();
96834
+ cleanupOwnedRegistryState();
96835
+ }
96836
+ });
96837
+ const performCleanup = runCleanup.run;
96838
+ const scheduleAutoCleanup = runCleanup.schedule;
96839
+ let workflow;
96840
+ try {
96841
+ this.executionEngine.assertRecoveryActive();
96842
+ workflow = this.getWorkflow();
96843
+ } catch (error) {
96844
+ if (await executionFence.settle(async () => {}) !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96845
+ releaseRecovery();
96846
+ throw error;
96733
96847
  }
96734
- const finished = !!result?.status && result.status !== "suspended";
96735
- await executionFence.settle(async () => {
96736
- if (finished) await this.deleteRunSnapshots(runId);
96737
- if (finished) await releaseRemoteAbortListener(runId, this.#mastra);
96848
+ const { stream, threadRegistration } = await this.#setupRecoveredStream({
96849
+ runId,
96850
+ workflowInput,
96851
+ requestContext,
96852
+ threadId,
96853
+ resourceId,
96854
+ messageList,
96855
+ registryEntry,
96856
+ options,
96857
+ scheduleAutoCleanup,
96858
+ executionFence
96859
+ }).catch((error) => {
96860
+ releaseRecovery();
96861
+ throw error;
96738
96862
  });
96739
- if (result?.status === "failed") throw this.executionEngine.workflowFailureError(result.error, "Workflow recover failed");
96740
- }).catch(async (error) => {
96741
- if (error?.id === "DURABLE_AGENT_RECOVER_SHUTDOWN") await executionFence.abandon();
96742
- const executionError = this.executionEngine.workflowExecutionError(error, "Workflow recover failed");
96743
- if (await executionFence.settle(async () => {}) === "superseded") {
96744
- const output = {
96745
- status: "interrupted",
96746
- reason: "recovery superseded"
96747
- };
96748
- recoverModelSpan?.end({
96749
- output,
96750
- outcome: "interrupted",
96751
- stopReason: null,
96752
- stopReasonContext: null
96753
- });
96754
- recoverAgentSpan?.end({
96755
- output,
96756
- outcome: "interrupted",
96757
- stopReason: null,
96758
- stopReasonContext: null
96863
+ const { output, cleanup: createdStreamCleanup, ready } = stream;
96864
+ streamCleanup = createdStreamCleanup;
96865
+ const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96866
+ const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96867
+ const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, require_observability.createObservabilityContext({ currentSpan: recoverAgentSpan }));
96868
+ if (finishPublishedBeforeCrash && result?.status === "success") {
96869
+ const { output: finalOutput, stepResult, tracingTermination, stopCause } = result.result;
96870
+ recoverModelSpan?.end({ ...tracingTermination });
96871
+ recoverAgentSpan?.end({
96872
+ ...tracingTermination,
96873
+ output: { text: finalOutput?.text }
96874
+ });
96875
+ await emitFinishEvent(recoveryPubsub, runId, {
96876
+ output: finalOutput,
96877
+ stepResult,
96878
+ ...stopCause && { stopCause }
96879
+ });
96880
+ }
96881
+ if (result?.status === "suspended" && options?.closeOnSuspend) {
96882
+ await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
96883
+ await stream.waitForEventDelivery();
96884
+ executionFence.throwIfLost();
96885
+ stream.detach();
96886
+ }
96887
+ const finished = !!result?.status && result.status !== "suspended";
96888
+ await executionFence.settle(async () => {
96889
+ if (finished) await this.deleteRunSnapshots(runId);
96890
+ if (finished) await releaseRemoteAbortListener(runId, this.#mastra);
96759
96891
  });
96760
- await threadRegistration?.rollback({ releaseLease: false });
96761
- performCleanup();
96762
- } else if (!this.#timedOutExecutions.has(executionFence) && !await this.#reportRecoveryFailure(runId, executionError, executionFence.generation)) {
96763
- await threadRegistration?.rollback();
96764
- performCleanup();
96765
- }
96766
- throw executionError;
96767
- }).finally(releaseLocalRecovery));
96768
- const trackedRecoverEntry = getRunRegistryEntry(runId, this.#mastra);
96769
- if (trackedRecoverEntry) trackedRecoverEntry.workflowExecution = workflowExecution;
96770
- workflowExecution.catch(() => {});
96771
- const cleanup = performCleanup;
96772
- const abort = async (reason) => {
96773
- if (!abortController.signal.aborted) abortController.abort(reason);
96774
- await this.requestRemoteAbort(runId);
96775
- if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
96776
- };
96777
- return {
96778
- output,
96779
- get fullStream() {
96780
- return output.fullStream;
96781
- },
96782
- runId,
96783
- threadId,
96784
- resourceId,
96785
- traceId: output.traceId,
96786
- spanId: output.spanId,
96787
- cleanup,
96788
- abort
96789
- };
96892
+ if (result?.status === "failed") throw this.executionEngine.workflowFailureError(result.error, "Workflow recover failed");
96893
+ }).catch(async (error) => {
96894
+ if (error?.id === "DURABLE_AGENT_RECOVER_SHUTDOWN") await executionFence.abandon();
96895
+ const executionError = this.executionEngine.workflowExecutionError(error, "Workflow recover failed");
96896
+ if (await executionFence.settle(async () => {}) === "superseded") {
96897
+ const output = {
96898
+ status: "interrupted",
96899
+ reason: "recovery superseded"
96900
+ };
96901
+ recoverModelSpan?.end({
96902
+ output,
96903
+ outcome: "interrupted",
96904
+ stopReason: null,
96905
+ stopReasonContext: null
96906
+ });
96907
+ recoverAgentSpan?.end({
96908
+ output,
96909
+ outcome: "interrupted",
96910
+ stopReason: null,
96911
+ stopReasonContext: null
96912
+ });
96913
+ await threadRegistration?.rollback({ releaseLease: false });
96914
+ performCleanup();
96915
+ } else if (!this.#timedOutExecutions.has(executionFence) && !await this.#reportRecoveryFailure(runId, executionError, executionFence.generation)) {
96916
+ await threadRegistration?.rollback();
96917
+ performCleanup();
96918
+ }
96919
+ throw executionError;
96920
+ }).finally(releaseRecovery));
96921
+ recoveryHandedOff = true;
96922
+ const trackedRecoverEntry = getRunRegistryEntry(runId, this.#mastra);
96923
+ if (trackedRecoverEntry) trackedRecoverEntry.workflowExecution = workflowExecution;
96924
+ workflowExecution.catch(() => {});
96925
+ const cleanup = performCleanup;
96926
+ const abort = async (reason) => {
96927
+ if (!abortController.signal.aborted) abortController.abort(reason);
96928
+ await this.requestRemoteAbort(runId);
96929
+ if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
96930
+ };
96931
+ return {
96932
+ output,
96933
+ get fullStream() {
96934
+ return output.fullStream;
96935
+ },
96936
+ runId,
96937
+ threadId,
96938
+ resourceId,
96939
+ traceId: output.traceId,
96940
+ spanId: output.spanId,
96941
+ cleanup,
96942
+ abort
96943
+ };
96944
+ } finally {
96945
+ if (!recoveryHandedOff) releaseRecovery();
96946
+ }
96790
96947
  }
96791
96948
  /**
96792
96949
  * Clear retained pubsub state for a run's topics (cached history and, for
@@ -97190,166 +97347,172 @@ var Agent = class Agent extends require_base.MastraBase {
97190
97347
  setExecutionClaim(requestContext, runId, executionFence.claim);
97191
97348
  registryEntry.executionFence = executionFence;
97192
97349
  this.#runInputs.set(executionFence, workflowInput);
97193
- const { controller: abortController } = createRunAbortController(options?.abortSignal);
97194
- if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
97195
- this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
97196
- const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
97197
- registryEntry.agentId = this.id;
97198
- this.executionRunRegistry.registerWithMessageList(runId, registryEntry, messageList, {
97199
- threadId,
97200
- resourceId
97201
- });
97202
- const globalRegistryEntry = {
97203
- ...registryEntry,
97204
- messageList
97205
- };
97206
- globalRunRegistry.set(runId, globalRegistryEntry);
97207
- await this.attachStreamPublisher(runId, {
97208
- threadId,
97209
- resourceId
97210
- });
97211
- const segment = methodType === "stream" ? this.#beginSegment(runId) : void 0;
97212
- let streamCleanup;
97213
- const releaseRunState = () => {
97214
- if (segment !== void 0) {
97215
- if (!this.#releaseSegment(runId, segment, registryEntry)) return;
97216
- } else if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
97217
- if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
97218
- globalRunRegistry.delete(runId);
97219
- if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, globalRegistryEntry);
97220
- }
97221
- };
97222
- const runCleanup = createRunCleanup({
97223
- scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
97224
- release: () => {
97225
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
97226
- streamCleanup?.();
97227
- releaseRunState();
97228
- },
97229
- ...methodType === "generate" ? { releaseOnTimer: releaseRunState } : {}
97230
- });
97231
- const performCleanup = runCleanup.run;
97232
- const scheduleAutoCleanup = runCleanup.schedule;
97233
- const closeOnSuspend = methodType === "generate" || (options?.closeOnSuspend ?? false);
97234
- const closeOnPersistedSuspend = methodType === "stream" && closeOnSuspend && this.executionEngine.suspendPersistedOnReturn;
97235
- const { output, cleanup: createdStreamCleanup, detach: detachStream, waitForEventDelivery, ready } = createDurableAgentStream({
97236
- pubsub: this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub,
97237
- runId,
97238
- minGeneration: executionFence.generation,
97239
- onTerminalEvent: this.owningReaderTerminal(runId, executionFence),
97240
- readLocalRequest,
97241
- messageId,
97242
- model: {
97243
- modelId: workflowInput.modelConfig.modelId,
97244
- provider: workflowInput.modelConfig.provider,
97245
- version: "v3"
97246
- },
97247
- threadId,
97248
- resourceId,
97249
- onChunk: options?.onChunk,
97250
- experimentalTransform: options?.experimentalTransform,
97251
- onStepFinish: options?.onStepFinish,
97252
- onFinish: options?.onFinish,
97253
- onStreamFinished: scheduleAutoCleanup,
97254
- onError: async (error) => {
97255
- await options?.onError?.(error);
97256
- scheduleAutoCleanup();
97257
- },
97258
- onSuspended: options?.onSuspended,
97259
- onAbort: async (data) => {
97260
- try {
97261
- await (options?.onAbort)?.(data);
97262
- } finally {
97263
- scheduleAutoCleanup();
97264
- }
97265
- },
97266
- closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,
97267
- ...methodType === "stream" ? { hideSignals: options?.hideSignals } : {},
97268
- structuredOutput: registryEntry.structuredOutput,
97269
- outputProcessors: registryEntry.outputProcessors,
97270
- processorStates: registryEntry.processorStates,
97271
- agent: registryEntry.agent,
97272
- requestContext: registryEntry.requestContext,
97273
- returnScorerData: workflowInput.options.returnScorerData,
97274
- tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
97275
- messageList,
97276
- messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
97277
- });
97278
- streamCleanup = createdStreamCleanup;
97279
- const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
97280
- continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
97281
- generation: executionFence.generation,
97282
- ownershipLost: () => executionFence.isLost(),
97283
- stepOwner: () => getRunRegistryEntry(runId, this.#mastra),
97284
- signalsStore: registryEntry.pendingSignalsStore
97285
- });
97286
- const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
97287
- if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
97288
- await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
97289
- type: "start",
97290
- runId,
97291
- from: "AGENT",
97292
- payload: {
97293
- id: workflowInput.agentId,
97294
- messageId
97295
- }
97350
+ const { controller: abortController, detach: detachExternalAbort } = createRunAbortController(options?.abortSignal);
97351
+ let workflowExecutionOwnsDetach = false;
97352
+ try {
97353
+ if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
97354
+ this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence, detachExternalAbort);
97355
+ const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
97356
+ registryEntry.agentId = this.id;
97357
+ this.executionRunRegistry.registerWithMessageList(runId, registryEntry, messageList, {
97358
+ threadId,
97359
+ resourceId
97296
97360
  });
97297
- if (this.__getGoalConfig()) await beginGoalActivity({
97298
- mastra: this.#mastra,
97299
- agentId: workflowInput.agentId,
97361
+ const globalRegistryEntry = {
97362
+ ...registryEntry,
97363
+ messageList
97364
+ };
97365
+ globalRunRegistry.set(runId, globalRegistryEntry);
97366
+ await this.attachStreamPublisher(runId, {
97300
97367
  threadId,
97368
+ resourceId
97369
+ });
97370
+ const segment = methodType === "stream" ? this.#beginSegment(runId) : void 0;
97371
+ let streamCleanup;
97372
+ const releaseRunState = () => {
97373
+ if (segment !== void 0) {
97374
+ if (!this.#releaseSegment(runId, segment, registryEntry)) return;
97375
+ } else if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
97376
+ if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
97377
+ globalRunRegistry.delete(runId);
97378
+ if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, globalRegistryEntry);
97379
+ }
97380
+ };
97381
+ const runCleanup = createRunCleanup({
97382
+ scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
97383
+ release: () => {
97384
+ agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
97385
+ streamCleanup?.();
97386
+ releaseRunState();
97387
+ },
97388
+ ...methodType === "generate" ? { releaseOnTimer: releaseRunState } : {}
97389
+ });
97390
+ const performCleanup = runCleanup.run;
97391
+ const scheduleAutoCleanup = runCleanup.schedule;
97392
+ const closeOnSuspend = methodType === "generate" || (options?.closeOnSuspend ?? false);
97393
+ const closeOnPersistedSuspend = methodType === "stream" && closeOnSuspend && this.executionEngine.suspendPersistedOnReturn;
97394
+ const { output, cleanup: createdStreamCleanup, detach: detachStream, waitForEventDelivery, ready } = createDurableAgentStream({
97395
+ pubsub: this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub,
97301
97396
  runId,
97302
- requestContext: getRunRegistryEntry(runId, this.#mastra)?.requestContext
97397
+ minGeneration: executionFence.generation,
97398
+ onTerminalEvent: this.owningReaderTerminal(runId, executionFence),
97399
+ readLocalRequest,
97400
+ messageId,
97401
+ model: {
97402
+ modelId: workflowInput.modelConfig.modelId,
97403
+ provider: workflowInput.modelConfig.provider,
97404
+ version: "v3"
97405
+ },
97406
+ threadId,
97407
+ resourceId,
97408
+ onChunk: options?.onChunk,
97409
+ experimentalTransform: options?.experimentalTransform,
97410
+ onStepFinish: options?.onStepFinish,
97411
+ onFinish: options?.onFinish,
97412
+ onStreamFinished: scheduleAutoCleanup,
97413
+ onError: async (error) => {
97414
+ await options?.onError?.(error);
97415
+ scheduleAutoCleanup();
97416
+ },
97417
+ onSuspended: options?.onSuspended,
97418
+ onAbort: async (data) => {
97419
+ try {
97420
+ await (options?.onAbort)?.(data);
97421
+ } finally {
97422
+ scheduleAutoCleanup();
97423
+ }
97424
+ },
97425
+ closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,
97426
+ ...methodType === "stream" ? { hideSignals: options?.hideSignals } : {},
97427
+ structuredOutput: registryEntry.structuredOutput,
97428
+ outputProcessors: registryEntry.outputProcessors,
97429
+ processorStates: registryEntry.processorStates,
97430
+ agent: registryEntry.agent,
97431
+ requestContext: registryEntry.requestContext,
97432
+ returnScorerData: workflowInput.options.returnScorerData,
97433
+ tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
97434
+ messageList,
97435
+ messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
97303
97436
  });
97304
- let result;
97305
- try {
97306
- const signalsStore = registryEntry.pendingSignalsStore;
97307
- const moved = signalsStore ? agentThreadStreamRuntime.storedSignalWritesSettled(signalsStore, this.getPubSub()) : void 0;
97308
- if (moved) await moved;
97309
- await this.#persistInitialInput(runId, workflowInput);
97310
- result = await this.executeWorkflow(runId, workflowInput);
97311
- } catch (error) {
97312
- await this.#discardRestartableStart(runId, workflowInput.agentId);
97313
- throw error;
97314
- } finally {
97315
- this.#restartableStarts.delete(runId);
97316
- await stopGoalActivity({
97437
+ streamCleanup = createdStreamCleanup;
97438
+ const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
97439
+ continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
97440
+ generation: executionFence.generation,
97441
+ ownershipLost: () => executionFence.isLost(),
97442
+ stepOwner: () => getRunRegistryEntry(runId, this.#mastra),
97443
+ signalsStore: registryEntry.pendingSignalsStore
97444
+ });
97445
+ const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
97446
+ if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
97447
+ await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
97448
+ type: "start",
97449
+ runId,
97450
+ from: "AGENT",
97451
+ payload: {
97452
+ id: workflowInput.agentId,
97453
+ messageId
97454
+ }
97455
+ });
97456
+ if (this.__getGoalConfig()) await beginGoalActivity({
97457
+ mastra: this.#mastra,
97317
97458
  agentId: workflowInput.agentId,
97318
- runId
97459
+ threadId,
97460
+ runId,
97461
+ requestContext: getRunRegistryEntry(runId, this.#mastra)?.requestContext
97319
97462
  });
97320
- }
97321
- if (closeOnPersistedSuspend && result?.status === "suspended") {
97322
- await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
97323
- await waitForEventDelivery();
97324
- detachStream();
97325
- }
97326
- if (methodType === "generate") return result;
97327
- }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
97328
- const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
97329
- if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
97330
- await threadRegistration;
97331
- const cleanup = () => {
97332
- if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
97333
- Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
97334
- };
97335
- const abort = async (reason) => {
97336
- if (!abortController.signal.aborted) abortController.abort(reason);
97337
- await this.requestRemoteAbort(runId);
97338
- if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
97339
- };
97340
- return {
97341
- output,
97342
- get fullStream() {
97343
- return output.fullStream;
97344
- },
97345
- runId,
97346
- threadId,
97347
- resourceId,
97348
- traceId: output.traceId,
97349
- spanId: output.spanId,
97350
- cleanup,
97351
- abort
97352
- };
97463
+ let result;
97464
+ try {
97465
+ const signalsStore = registryEntry.pendingSignalsStore;
97466
+ const moved = signalsStore ? agentThreadStreamRuntime.storedSignalWritesSettled(signalsStore, this.getPubSub()) : void 0;
97467
+ if (moved) await moved;
97468
+ await this.#persistInitialInput(runId, workflowInput);
97469
+ result = await this.executeWorkflow(runId, workflowInput);
97470
+ } catch (error) {
97471
+ await this.#discardRestartableStart(runId, workflowInput.agentId);
97472
+ throw error;
97473
+ } finally {
97474
+ this.#restartableStarts.delete(runId);
97475
+ await stopGoalActivity({
97476
+ agentId: workflowInput.agentId,
97477
+ runId
97478
+ });
97479
+ }
97480
+ if (closeOnPersistedSuspend && result?.status === "suspended") {
97481
+ await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
97482
+ await waitForEventDelivery();
97483
+ detachStream();
97484
+ }
97485
+ if (methodType === "generate") return result;
97486
+ }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })).finally(detachExternalAbort));
97487
+ workflowExecutionOwnsDetach = true;
97488
+ const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
97489
+ if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
97490
+ await threadRegistration;
97491
+ const cleanup = () => {
97492
+ if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
97493
+ Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
97494
+ };
97495
+ const abort = async (reason) => {
97496
+ if (!abortController.signal.aborted) abortController.abort(reason);
97497
+ await this.requestRemoteAbort(runId);
97498
+ if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
97499
+ };
97500
+ return {
97501
+ output,
97502
+ get fullStream() {
97503
+ return output.fullStream;
97504
+ },
97505
+ runId,
97506
+ threadId,
97507
+ resourceId,
97508
+ traceId: output.traceId,
97509
+ spanId: output.spanId,
97510
+ cleanup,
97511
+ abort
97512
+ };
97513
+ } finally {
97514
+ if (!workflowExecutionOwnsDetach) detachExternalAbort();
97515
+ }
97353
97516
  }
97354
97517
  async #generateDurable(messages, options) {
97355
97518
  options = await this.#resolveDurableRunOptions(applyReservedMemoryContextKeys(options));
@@ -97754,7 +97917,7 @@ var Agent = class Agent extends require_base.MastraBase {
97754
97917
  const resumeTotalMs = resolvedOptions.modelSettings?.timeout?.totalMs;
97755
97918
  if (resumeTotalMs !== void 0) entry.timeoutTotalMs = resumeTotalMs;
97756
97919
  if (persistedInput) this.#runInputs.set(executionFence, persistedInput);
97757
- this.installAbortWithTotalTimeout(entry, abortController, executionFence);
97920
+ this.installAbortWithTotalTimeout(entry, abortController, executionFence, detachExternalAbort);
97758
97921
  const globalEntryForAbort = getRunRegistryEntry(runId, this.#mastra);
97759
97922
  if (globalEntryForAbort) {
97760
97923
  globalEntryForAbort.abortController = abortController;