@mastra/core 1.87.0-alpha.14 → 1.87.0-alpha.16

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 (120) 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/session.d.ts +11 -0
  10. package/dist/{agent-controller-k4B293tu.cjs → agent-controller-j9NMWxj9.cjs} +39 -11
  11. package/dist/{agent-controller-FSjSZ_iD.js → agent-controller-kOpZ0XOG.js} +39 -11
  12. package/dist/background-tasks/index.cjs +1 -1
  13. package/dist/background-tasks/index.js +1 -1
  14. package/dist/{background-tasks-D40Y_iLc.cjs → background-tasks-CElXOIJy.cjs} +1 -1
  15. package/dist/{background-tasks-ClI6oF60.js → background-tasks-CwAL_gCW.js} +1 -1
  16. package/dist/browser/index.cjs +1 -1
  17. package/dist/browser/index.js +1 -1
  18. package/dist/{builder-C_I6l0US.cjs → builder-CxVVSmjB.cjs} +2 -2
  19. package/dist/{builder-D00XMm41.js → builder-DNZjud0V.js} +2 -2
  20. package/dist/channels/index.cjs +2 -2
  21. package/dist/channels/index.js +2 -2
  22. package/dist/{channels-BU5_kAUO.cjs → channels-BOAF0NeL.cjs} +1 -1
  23. package/dist/{channels-DMSae7xD.js → channels-CayUAfIz.js} +1 -1
  24. package/dist/coding-agent/index.cjs +2 -2
  25. package/dist/coding-agent/index.js +2 -2
  26. package/dist/datasets/index.cjs +2 -2
  27. package/dist/datasets/index.js +2 -2
  28. package/dist/docs/SKILL.md +1 -1
  29. package/dist/docs/assets/SOURCE_MAP.json +530 -530
  30. package/dist/docs/references/docs-signals-sending-signals.md +13 -0
  31. package/dist/docs/references/docs-signals-state-signals.md +1 -1
  32. package/dist/docs/references/reference-agent-controller-session.md +1 -1
  33. package/dist/docs/references/reference-signals-time-signal-provider.md +35 -0
  34. package/dist/evals/index.cjs +1 -1
  35. package/dist/evals/index.js +1 -1
  36. package/dist/evals/scoreTraces/index.cjs +1 -1
  37. package/dist/evals/scoreTraces/index.js +1 -1
  38. package/dist/harness/index.cjs +1 -1
  39. package/dist/harness/index.js +1 -1
  40. package/dist/index.cjs +1 -1
  41. package/dist/index.js +1 -1
  42. package/dist/knowledge/index.cjs +1 -1
  43. package/dist/knowledge/index.js +1 -1
  44. package/dist/llm/index.cjs +3 -3
  45. package/dist/llm/index.js +3 -3
  46. package/dist/{llm-C1aiWB6O.cjs → llm-DavIP030.cjs} +2 -2
  47. package/dist/{llm-D5rGQSnS.js → llm-Y6-66bjV.js} +2 -2
  48. package/dist/loop/index.cjs +2 -2
  49. package/dist/loop/index.js +2 -2
  50. package/dist/{manager-DxwPLhYJ.js → manager-BgRKeq71.js} +2 -2
  51. package/dist/{manager-B2z5f39G.cjs → manager-uP4hdwto.cjs} +2 -2
  52. package/dist/mastra/index.cjs +1 -1
  53. package/dist/mastra/index.js +1 -1
  54. package/dist/{mastra-WMuI7TZD.cjs → mastra-MQaZNO_5.cjs} +17 -16
  55. package/dist/{mastra-CHd7UnbI.js → mastra-YOYYfVqQ.js} +17 -16
  56. package/dist/memory/index.cjs +2 -2
  57. package/dist/memory/index.js +2 -2
  58. package/dist/{model-B8DlLHex.js → model-12DTcU8f.js} +1 -1
  59. package/dist/{model-C2CTzjMk.cjs → model-MVMgEFAM.cjs} +1 -1
  60. package/dist/{netlify-Dhs0UJul.cjs → netlify-BLF-KH2r.cjs} +1 -1
  61. package/dist/{netlify-xQFmVbr4.js → netlify-DgcmApEP.js} +1 -1
  62. package/dist/notifications/index.cjs +1 -1
  63. package/dist/notifications/index.js +1 -1
  64. package/dist/processor-provider/index.cjs +1 -1
  65. package/dist/processor-provider/index.js +1 -1
  66. package/dist/processors/index.cjs +2 -2
  67. package/dist/processors/index.js +2 -2
  68. package/dist/{provider-registry-FxVHWmht.js → provider-registry-C-NQBGL4.js} +4 -4
  69. package/dist/{provider-registry-CSQPAFzz.cjs → provider-registry-CUyaPS-4.cjs} +4 -4
  70. package/dist/{registry-generator-Dsh7xcz9.cjs → registry-generator-BZ5Pv4nI.cjs} +1 -1
  71. package/dist/{registry-generator-BzsrHxrr.js → registry-generator-EYJb9e6K.js} +1 -1
  72. package/dist/{rehydrate-8q7KX4rD.cjs → rehydrate-CeURpucJ.cjs} +2 -2
  73. package/dist/{rehydrate-DV1iO9eZ.js → rehydrate-DCOIeOdN.js} +2 -2
  74. package/dist/relevance/index.cjs +2 -2
  75. package/dist/relevance/index.js +2 -2
  76. package/dist/{run-registry-DOlZccsr.cjs → run-registry-DTSRWF58.cjs} +451 -345
  77. package/dist/{run-registry-sTm40Ecv.js → run-registry-rMtPezec.js} +451 -345
  78. package/dist/signals/index.cjs +1 -1
  79. package/dist/signals/index.js +1 -1
  80. package/dist/signals/time-signal-provider.d.ts +8 -0
  81. package/dist/{signals-CIwzgkvN.cjs → signals-CbmgVwL-.cjs} +74 -7
  82. package/dist/{signals-BTfT-6DE.js → signals-Clupx3jz.js} +74 -7
  83. package/dist/storage/domains/knowledge/base.d.ts +33 -1
  84. package/dist/storage/domains/knowledge/inmemory.d.ts +2 -0
  85. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +20 -12
  86. package/dist/storage/index.cjs +2 -2
  87. package/dist/storage/index.js +2 -2
  88. package/dist/stream/index.cjs +2 -2
  89. package/dist/stream/index.js +2 -2
  90. package/dist/{stream-k-Q1NLUs.js → stream-BesrxR1K.js} +1 -1
  91. package/dist/{stream-aGuW9AL8.cjs → stream-CrV6DfJ-.cjs} +1 -1
  92. package/dist/test-utils/llm-mock.cjs +1 -1
  93. package/dist/test-utils/llm-mock.js +1 -1
  94. package/dist/tool-loop-agent/index.cjs +1 -1
  95. package/dist/tool-loop-agent/index.js +1 -1
  96. package/dist/{tool-loop-agent-CJrysPOR.js → tool-loop-agent-BUVZs_1t.js} +3 -3
  97. package/dist/{tool-loop-agent-WcRtGJHn.cjs → tool-loop-agent-ikhSFXV9.cjs} +3 -3
  98. package/dist/{utils-DEzQLxWP.cjs → utils-CJvQVYFV.cjs} +1 -1
  99. package/dist/{utils-DamF4CfD.js → utils-D8ewiYXS.js} +1 -1
  100. package/dist/utils.cjs +1 -1
  101. package/dist/utils.js +1 -1
  102. package/dist/{validate-CDlONK0o.cjs → validate-BRq40Xoy.cjs} +1 -1
  103. package/dist/{validate-rum3NMFA.js → validate-BRuenG5x.js} +1 -1
  104. package/dist/vector/index.cjs +1 -1
  105. package/dist/vector/index.js +1 -1
  106. package/dist/worker/index.cjs +1 -1
  107. package/dist/worker/index.js +1 -1
  108. package/dist/{worker-BnXipQth.js → worker-BL1pA7s1.js} +2 -2
  109. package/dist/{worker-6MiKMAqB.cjs → worker-Bp2Om6B2.cjs} +2 -2
  110. package/dist/{worker-st16x0my.js → worker-CmAlDdZR.js} +2 -2
  111. package/dist/{worker-rwal1zI8.cjs → worker-DV_dWICJ.cjs} +2 -2
  112. package/dist/{workflow-D2-gn0U0.cjs → workflow-4rGnxGb1.cjs} +3 -3
  113. package/dist/{workflow-BzhYKgc_.js → workflow-8CPioJsX.js} +3 -3
  114. package/dist/workflows/builder/index.cjs +1 -1
  115. package/dist/workflows/builder/index.js +1 -1
  116. package/dist/workflows/evented/index.cjs +1 -1
  117. package/dist/workflows/evented/index.js +1 -1
  118. package/dist/workflows/index.cjs +4 -4
  119. package/dist/workflows/index.js +4 -4
  120. package/package.json +6 -6
@@ -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-aGuW9AL8.cjs");
7
+ const require_stream = require("./stream-CrV6DfJ-.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-C1aiWB6O.cjs");
14
+ const require_llm = require("./llm-DavIP030.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-CSQPAFzz.cjs");
26
+ const require_provider_registry = require("./provider-registry-CUyaPS-4.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-C2CTzjMk.cjs");
30
- const require_utils$1 = require("./utils-DEzQLxWP.cjs");
29
+ const require_model$1 = require("./model-MVMgEFAM.cjs");
30
+ const require_utils$1 = require("./utils-CJvQVYFV.cjs");
31
31
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
32
- const require_background_tasks = require("./background-tasks-D40Y_iLc.cjs");
32
+ const require_background_tasks = require("./background-tasks-CElXOIJy.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");
@@ -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
  }
@@ -66540,16 +66571,28 @@ async function configPins(run, maxTokens) {
66540
66571
  listings: []
66541
66572
  };
66542
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;
66543
66590
  const pages = /* @__PURE__ */ new Map();
66544
66591
  const listings = /* @__PURE__ */ new Map();
66545
66592
  for (const pin of bound) {
66546
- const scope = scopes.find((candidate) => candidate.address === pin.address);
66593
+ const scope = scopeOf.get(pin.address);
66547
66594
  if (!scope) continue;
66548
- const page = pin.path.length === 0 ? knowledgeScopeReadable(scope, run.read) ? scope : null : await run.storage.getPageByPath({
66549
- scopeId: scope.id,
66550
- path: pin.path,
66551
- read: run.read
66552
- });
66595
+ const page = pin.path.length === 0 ? knowledgeScopeReadable(scope, run.read) ? scope : null : found[next++];
66553
66596
  if (!page || page.deletedAt) continue;
66554
66597
  if (pin.depth === void 0) pages.set(page.id, page);
66555
66598
  else if ((listings.get(page.id)?.depth ?? 0) < pin.depth) listings.set(page.id, await resolveListing(run, page, pin.depth, maxTokens));
@@ -66571,6 +66614,28 @@ async function rankedStoredPins(run, excludePageIds, want) {
66571
66614
  withBody: true,
66572
66615
  excludePageIds
66573
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
+ }
66574
66639
  const pins = [];
66575
66640
  const seen = /* @__PURE__ */ new Set();
66576
66641
  let total;
@@ -66594,7 +66659,7 @@ async function rankedStoredPins(run, excludePageIds, want) {
66594
66659
  } while (cursor && pins.length < want);
66595
66660
  if (pins.length >= want) break;
66596
66661
  }
66597
- if (total === void 0) total = tiers.length === 0 ? 0 : (await run.storage.listPins({
66662
+ if (total === void 0) total = (await run.storage.listPins({
66598
66663
  ...base,
66599
66664
  audience: run.principals,
66600
66665
  limit: 1,
@@ -80206,22 +80271,29 @@ function createDurableLLMExecutionStep(_options) {
80206
80271
  }
80207
80272
  throwIfInterrupted();
80208
80273
  cleanupToolObservabilitySpans(true);
80209
- logger?.error?.("Error processing LLM stream", {
80210
- error,
80211
- runId
80212
- });
80213
80274
  const errorObj = error instanceof Error ? error : new Error(String(error));
80214
- if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80215
- error: errorObj,
80216
- endSpan: false
80217
- });
80218
- else if (modelSpan) modelSpan.error({
80219
- error: errorObj,
80220
- endSpan: false
80221
- });
80222
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
+ }
80223
80291
  if (innerTimeout) throw innerTimeout;
80224
- if (executionAbortSignal?.aborted === true || errorObj.name === "AbortError") {
80292
+ if (isAbort) {
80293
+ logger?.debug?.("LLM stream aborted", {
80294
+ error: errorObj,
80295
+ runId
80296
+ });
80225
80297
  materializeStreamedMessages();
80226
80298
  return {
80227
80299
  ...await storeStepTranscript(),
@@ -80286,21 +80358,28 @@ function createDurableLLMExecutionStep(_options) {
80286
80358
  const streamError = outputStream.error;
80287
80359
  if (streamError) {
80288
80360
  const streamErrorObj = streamError instanceof Error ? streamError : new Error(String(streamError));
80289
- logger?.error?.("Stream captured error", {
80290
- error: streamErrorObj,
80291
- runId
80292
- });
80293
- if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80294
- error: streamErrorObj,
80295
- endSpan: false
80296
- });
80297
- else if (modelSpan) modelSpan.error({
80298
- error: streamErrorObj,
80299
- endSpan: false
80300
- });
80301
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
+ }
80302
80377
  if (streamErrorTimeout) throw streamErrorTimeout;
80303
- if (executionAbortSignal?.aborted === true || streamErrorObj.name === "AbortError") {
80378
+ if (isStreamErrorAbort) {
80379
+ logger?.debug?.("Captured LLM stream aborted", {
80380
+ error: streamErrorObj,
80381
+ runId
80382
+ });
80304
80383
  materializeStreamedMessages();
80305
80384
  return {
80306
80385
  ...await storeStepTranscript(),
@@ -86274,7 +86353,7 @@ async function prepareForDurableExecution(options) {
86274
86353
  });
86275
86354
  let tripwireData;
86276
86355
  if (inputProcessors.length > 0) try {
86277
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-aGuW9AL8.cjs")).then((n) => n.runner_exports);
86356
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-CrV6DfJ-.cjs")).then((n) => n.runner_exports);
86278
86357
  await new ProcessorRunner({
86279
86358
  inputProcessors,
86280
86359
  outputProcessors,
@@ -96148,7 +96227,7 @@ var Agent = class Agent extends require_base.MastraBase {
96148
96227
  }
96149
96228
  }
96150
96229
  /** Rebuilds process-local recovery state from the persisted durable workflow input. */
96151
- async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
96230
+ async #rehydrateRecoveryState({ runId, workflowInput, abortController, onTerminalDeadline, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
96152
96231
  const requestContext = workflowInput.requestContextEntries ? new require_request_context.RequestContext(Object.entries(workflowInput.requestContextEntries)) : new require_request_context.RequestContext();
96153
96232
  restoreRunAgentScopes(requestContext);
96154
96233
  const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
@@ -96364,7 +96443,7 @@ var Agent = class Agent extends require_base.MastraBase {
96364
96443
  subscribePendingSignals: (listener) => wrapped.__getSubscribePendingSignals()(runId, listener),
96365
96444
  cleanup: () => {}
96366
96445
  };
96367
- this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
96446
+ this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence, onTerminalDeadline);
96368
96447
  this.#runInputs.set(executionFence, {
96369
96448
  ...workflowInput,
96370
96449
  messageListState: latestMessageListState ?? workflowInput.messageListState
@@ -96563,7 +96642,7 @@ var Agent = class Agent extends require_base.MastraBase {
96563
96642
  * each session gets a fresh timer. The timer is torn down via the entry's
96564
96643
  * `cleanup` slot, which every settle path invokes through the run registry.
96565
96644
  */
96566
- installAbortWithTotalTimeout(entry, abortController, executionFence) {
96645
+ installAbortWithTotalTimeout(entry, abortController, executionFence, onTerminalDeadline) {
96567
96646
  entry.abortController = abortController;
96568
96647
  entry.deadlineErrorRedelivered = false;
96569
96648
  const totalTimeout = require_stream.createTimeoutAbortSignal({
@@ -96575,10 +96654,14 @@ var Agent = class Agent extends require_base.MastraBase {
96575
96654
  entry.abortSignal = totalTimeout.signal;
96576
96655
  if (totalTimeout.timeoutPromise) totalTimeout.timeoutPromise.catch(async (error) => {
96577
96656
  if (!require_stream.isMastraTimeoutError(error) || error.timeoutType !== "total" || totalTimeout.signal?.reason !== error) return;
96578
- await this.settleExecution(executionFence.runId, executionFence, {
96579
- status: "failed",
96580
- error
96581
- });
96657
+ try {
96658
+ await this.settleExecution(executionFence.runId, executionFence, {
96659
+ status: "failed",
96660
+ error
96661
+ });
96662
+ } finally {
96663
+ onTerminalDeadline?.();
96664
+ }
96582
96665
  }).catch((error) => {
96583
96666
  this.logger.warn("Failed to settle durable agent at its total deadline", { error });
96584
96667
  });
@@ -96677,11 +96760,19 @@ var Agent = class Agent extends require_base.MastraBase {
96677
96760
  }
96678
96761
  this.executionEngine.assertRecoveryActive();
96679
96762
  const releaseLocalRecovery = this.executionEngine.claimLocalRecovery(this.id, this.name, runId);
96680
- 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
+ };
96681
96771
  let executionFence;
96682
96772
  let recoveryState;
96683
96773
  let finishPublishedBeforeCrash;
96684
96774
  let claimedSnapshot;
96775
+ let recoveryHandedOff = false;
96685
96776
  try {
96686
96777
  executionFence = await this.executionEngine.claimExecution(runId, options?.force ? "takeover" : "recover", this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, this.logger, this.#untrackedRunLiveness(runId, workflowInput));
96687
96778
  this.executionEngine.assertRecoveryActive();
@@ -96695,6 +96786,7 @@ var Agent = class Agent extends require_base.MastraBase {
96695
96786
  runId,
96696
96787
  workflowInput,
96697
96788
  abortController,
96789
+ onTerminalDeadline: detachExternalAbort,
96698
96790
  executionFence,
96699
96791
  originalSpansEnded: loaded.originalSpansEnded,
96700
96792
  openStepsOf: loaded.openStepsOf,
@@ -96704,146 +96796,154 @@ var Agent = class Agent extends require_base.MastraBase {
96704
96796
  this.#recoveredEntries.set(executionFence, recoveryState.registryEntry);
96705
96797
  this.executionEngine.assertRecoveryActive();
96706
96798
  } catch (error) {
96707
- const settlement = await executionFence?.settle(async () => {});
96708
- if (executionFence && settlement !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96709
- releaseLocalRecovery();
96710
- throw error;
96711
- }
96712
- const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } = recoveryState;
96713
- if (executionFence.generation !== void 0) {
96714
- const supersededFrom = await this.executionEngine.recoverySupersededFrom(workflowsStore, runId, claimedSnapshot, () => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, () => this.logger);
96715
- await emitOwnershipClaimedEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, executionFence.generation, supersededFrom).catch((error) => {
96716
- this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {
96717
- runId,
96718
- error
96719
- });
96720
- });
96721
- }
96722
- setExecutionClaim(requestContext, runId, executionFence.claim);
96723
- registryEntry.executionFence = executionFence;
96724
- let streamCleanup;
96725
- const cleanupOwnedRegistryState = () => {
96726
- if (registryEntry.executionFence !== executionFence) return;
96727
- if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
96728
- if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {
96729
- globalRunRegistry.delete(runId);
96730
- if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96731
- }
96732
- };
96733
- const runCleanup = createRunCleanup({
96734
- scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96735
- release: () => {
96736
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96737
- streamCleanup?.();
96738
- 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();
96739
96804
  }
96740
- });
96741
- const performCleanup = runCleanup.run;
96742
- const scheduleAutoCleanup = runCleanup.schedule;
96743
- let workflow;
96744
- try {
96745
- this.executionEngine.assertRecoveryActive();
96746
- workflow = this.getWorkflow();
96747
- } catch (error) {
96748
- if (await executionFence.settle(async () => {}) !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96749
- releaseLocalRecovery();
96750
96805
  throw error;
96751
96806
  }
96752
- const { stream, threadRegistration } = await this.#setupRecoveredStream({
96753
- runId,
96754
- workflowInput,
96755
- requestContext,
96756
- threadId,
96757
- resourceId,
96758
- messageList,
96759
- registryEntry,
96760
- options,
96761
- scheduleAutoCleanup,
96762
- executionFence
96763
- }).catch((error) => {
96764
- releaseLocalRecovery();
96765
- throw error;
96766
- });
96767
- const { output, cleanup: createdStreamCleanup, ready } = stream;
96768
- streamCleanup = createdStreamCleanup;
96769
- const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96770
- const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96771
- const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, require_observability.createObservabilityContext({ currentSpan: recoverAgentSpan }));
96772
- if (finishPublishedBeforeCrash && result?.status === "success") {
96773
- const { output: finalOutput, stepResult, tracingTermination, stopCause } = result.result;
96774
- recoverModelSpan?.end({ ...tracingTermination });
96775
- recoverAgentSpan?.end({
96776
- ...tracingTermination,
96777
- output: { text: finalOutput?.text }
96778
- });
96779
- await emitFinishEvent(recoveryPubsub, runId, {
96780
- output: finalOutput,
96781
- stepResult,
96782
- ...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
+ });
96783
96816
  });
96784
96817
  }
96785
- if (result?.status === "suspended" && options?.closeOnSuspend) {
96786
- await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
96787
- await stream.waitForEventDelivery();
96788
- executionFence.throwIfLost();
96789
- 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;
96790
96847
  }
96791
- const finished = !!result?.status && result.status !== "suspended";
96792
- await executionFence.settle(async () => {
96793
- if (finished) await this.deleteRunSnapshots(runId);
96794
- 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;
96795
96862
  });
96796
- if (result?.status === "failed") throw this.executionEngine.workflowFailureError(result.error, "Workflow recover failed");
96797
- }).catch(async (error) => {
96798
- if (error?.id === "DURABLE_AGENT_RECOVER_SHUTDOWN") await executionFence.abandon();
96799
- const executionError = this.executionEngine.workflowExecutionError(error, "Workflow recover failed");
96800
- if (await executionFence.settle(async () => {}) === "superseded") {
96801
- const output = {
96802
- status: "interrupted",
96803
- reason: "recovery superseded"
96804
- };
96805
- recoverModelSpan?.end({
96806
- output,
96807
- outcome: "interrupted",
96808
- stopReason: null,
96809
- stopReasonContext: null
96810
- });
96811
- recoverAgentSpan?.end({
96812
- output,
96813
- outcome: "interrupted",
96814
- stopReason: null,
96815
- 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);
96816
96891
  });
96817
- await threadRegistration?.rollback({ releaseLease: false });
96818
- performCleanup();
96819
- } else if (!this.#timedOutExecutions.has(executionFence) && !await this.#reportRecoveryFailure(runId, executionError, executionFence.generation)) {
96820
- await threadRegistration?.rollback();
96821
- performCleanup();
96822
- }
96823
- throw executionError;
96824
- }).finally(releaseLocalRecovery));
96825
- const trackedRecoverEntry = getRunRegistryEntry(runId, this.#mastra);
96826
- if (trackedRecoverEntry) trackedRecoverEntry.workflowExecution = workflowExecution;
96827
- workflowExecution.catch(() => {});
96828
- const cleanup = performCleanup;
96829
- const abort = async (reason) => {
96830
- if (!abortController.signal.aborted) abortController.abort(reason);
96831
- await this.requestRemoteAbort(runId);
96832
- if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
96833
- };
96834
- return {
96835
- output,
96836
- get fullStream() {
96837
- return output.fullStream;
96838
- },
96839
- runId,
96840
- threadId,
96841
- resourceId,
96842
- traceId: output.traceId,
96843
- spanId: output.spanId,
96844
- cleanup,
96845
- abort
96846
- };
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
+ }
96847
96947
  }
96848
96948
  /**
96849
96949
  * Clear retained pubsub state for a run's topics (cached history and, for
@@ -97247,166 +97347,172 @@ var Agent = class Agent extends require_base.MastraBase {
97247
97347
  setExecutionClaim(requestContext, runId, executionFence.claim);
97248
97348
  registryEntry.executionFence = executionFence;
97249
97349
  this.#runInputs.set(executionFence, workflowInput);
97250
- const { controller: abortController } = createRunAbortController(options?.abortSignal);
97251
- if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
97252
- this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
97253
- const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
97254
- registryEntry.agentId = this.id;
97255
- this.executionRunRegistry.registerWithMessageList(runId, registryEntry, messageList, {
97256
- threadId,
97257
- resourceId
97258
- });
97259
- const globalRegistryEntry = {
97260
- ...registryEntry,
97261
- messageList
97262
- };
97263
- globalRunRegistry.set(runId, globalRegistryEntry);
97264
- await this.attachStreamPublisher(runId, {
97265
- threadId,
97266
- resourceId
97267
- });
97268
- const segment = methodType === "stream" ? this.#beginSegment(runId) : void 0;
97269
- let streamCleanup;
97270
- const releaseRunState = () => {
97271
- if (segment !== void 0) {
97272
- if (!this.#releaseSegment(runId, segment, registryEntry)) return;
97273
- } else if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
97274
- if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
97275
- globalRunRegistry.delete(runId);
97276
- if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, globalRegistryEntry);
97277
- }
97278
- };
97279
- const runCleanup = createRunCleanup({
97280
- scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
97281
- release: () => {
97282
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
97283
- streamCleanup?.();
97284
- releaseRunState();
97285
- },
97286
- ...methodType === "generate" ? { releaseOnTimer: releaseRunState } : {}
97287
- });
97288
- const performCleanup = runCleanup.run;
97289
- const scheduleAutoCleanup = runCleanup.schedule;
97290
- const closeOnSuspend = methodType === "generate" || (options?.closeOnSuspend ?? false);
97291
- const closeOnPersistedSuspend = methodType === "stream" && closeOnSuspend && this.executionEngine.suspendPersistedOnReturn;
97292
- const { output, cleanup: createdStreamCleanup, detach: detachStream, waitForEventDelivery, ready } = createDurableAgentStream({
97293
- pubsub: this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub,
97294
- runId,
97295
- minGeneration: executionFence.generation,
97296
- onTerminalEvent: this.owningReaderTerminal(runId, executionFence),
97297
- readLocalRequest,
97298
- messageId,
97299
- model: {
97300
- modelId: workflowInput.modelConfig.modelId,
97301
- provider: workflowInput.modelConfig.provider,
97302
- version: "v3"
97303
- },
97304
- threadId,
97305
- resourceId,
97306
- onChunk: options?.onChunk,
97307
- experimentalTransform: options?.experimentalTransform,
97308
- onStepFinish: options?.onStepFinish,
97309
- onFinish: options?.onFinish,
97310
- onStreamFinished: scheduleAutoCleanup,
97311
- onError: async (error) => {
97312
- await options?.onError?.(error);
97313
- scheduleAutoCleanup();
97314
- },
97315
- onSuspended: options?.onSuspended,
97316
- onAbort: async (data) => {
97317
- try {
97318
- await (options?.onAbort)?.(data);
97319
- } finally {
97320
- scheduleAutoCleanup();
97321
- }
97322
- },
97323
- closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,
97324
- ...methodType === "stream" ? { hideSignals: options?.hideSignals } : {},
97325
- structuredOutput: registryEntry.structuredOutput,
97326
- outputProcessors: registryEntry.outputProcessors,
97327
- processorStates: registryEntry.processorStates,
97328
- agent: registryEntry.agent,
97329
- requestContext: registryEntry.requestContext,
97330
- returnScorerData: workflowInput.options.returnScorerData,
97331
- tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
97332
- messageList,
97333
- messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
97334
- });
97335
- streamCleanup = createdStreamCleanup;
97336
- const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
97337
- continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
97338
- generation: executionFence.generation,
97339
- ownershipLost: () => executionFence.isLost(),
97340
- stepOwner: () => getRunRegistryEntry(runId, this.#mastra),
97341
- signalsStore: registryEntry.pendingSignalsStore
97342
- });
97343
- const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
97344
- if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
97345
- await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
97346
- type: "start",
97347
- runId,
97348
- from: "AGENT",
97349
- payload: {
97350
- id: workflowInput.agentId,
97351
- messageId
97352
- }
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
97353
97360
  });
97354
- if (this.__getGoalConfig()) await beginGoalActivity({
97355
- mastra: this.#mastra,
97356
- agentId: workflowInput.agentId,
97361
+ const globalRegistryEntry = {
97362
+ ...registryEntry,
97363
+ messageList
97364
+ };
97365
+ globalRunRegistry.set(runId, globalRegistryEntry);
97366
+ await this.attachStreamPublisher(runId, {
97357
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,
97358
97396
  runId,
97359
- 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
97360
97436
  });
97361
- let result;
97362
- try {
97363
- const signalsStore = registryEntry.pendingSignalsStore;
97364
- const moved = signalsStore ? agentThreadStreamRuntime.storedSignalWritesSettled(signalsStore, this.getPubSub()) : void 0;
97365
- if (moved) await moved;
97366
- await this.#persistInitialInput(runId, workflowInput);
97367
- result = await this.executeWorkflow(runId, workflowInput);
97368
- } catch (error) {
97369
- await this.#discardRestartableStart(runId, workflowInput.agentId);
97370
- throw error;
97371
- } finally {
97372
- this.#restartableStarts.delete(runId);
97373
- 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,
97374
97458
  agentId: workflowInput.agentId,
97375
- runId
97459
+ threadId,
97460
+ runId,
97461
+ requestContext: getRunRegistryEntry(runId, this.#mastra)?.requestContext
97376
97462
  });
97377
- }
97378
- if (closeOnPersistedSuspend && result?.status === "suspended") {
97379
- await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
97380
- await waitForEventDelivery();
97381
- detachStream();
97382
- }
97383
- if (methodType === "generate") return result;
97384
- }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
97385
- const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
97386
- if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
97387
- await threadRegistration;
97388
- const cleanup = () => {
97389
- if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
97390
- Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
97391
- };
97392
- const abort = async (reason) => {
97393
- if (!abortController.signal.aborted) abortController.abort(reason);
97394
- await this.requestRemoteAbort(runId);
97395
- if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
97396
- };
97397
- return {
97398
- output,
97399
- get fullStream() {
97400
- return output.fullStream;
97401
- },
97402
- runId,
97403
- threadId,
97404
- resourceId,
97405
- traceId: output.traceId,
97406
- spanId: output.spanId,
97407
- cleanup,
97408
- abort
97409
- };
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
+ }
97410
97516
  }
97411
97517
  async #generateDurable(messages, options) {
97412
97518
  options = await this.#resolveDurableRunOptions(applyReservedMemoryContextKeys(options));
@@ -97811,7 +97917,7 @@ var Agent = class Agent extends require_base.MastraBase {
97811
97917
  const resumeTotalMs = resolvedOptions.modelSettings?.timeout?.totalMs;
97812
97918
  if (resumeTotalMs !== void 0) entry.timeoutTotalMs = resumeTotalMs;
97813
97919
  if (persistedInput) this.#runInputs.set(executionFence, persistedInput);
97814
- this.installAbortWithTotalTimeout(entry, abortController, executionFence);
97920
+ this.installAbortWithTotalTimeout(entry, abortController, executionFence, detachExternalAbort);
97815
97921
  const globalEntryForAbort = getRunRegistryEntry(runId, this.#mastra);
97816
97922
  if (globalEntryForAbort) {
97817
97923
  globalEntryForAbort.abortController = abortController;