@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 @@ import { t as MastraBase } from "./base-CKLWBhDo.js";
4
4
  import { A as compactStopReasonContext, D as agentLoopTermination, O as executionFailureTermination, S as resolveObservabilityContext, b as wrapMastra, i as subtractReportedUsage, k as tripwireTermination, n as extractUsageMetrics, r as isUsageIncomplete, t as calculateObservedUsage, x as createObservabilityContext, y as unwrapMastraTracingProxy } from "./observability-D7RNOAPx.js";
5
5
  import { a as MastraNonRetryableError, i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
6
6
  import { a as classifyProviderError, l as describeProviderError, t as recordTerminalErrorMessage, u as readProviderErrorDetails } from "./error-BC9Au-22.js";
7
- import { $ as summarizeToolChoiceForSpan, $t as commitToolResult, A as isSignalChunkExcluded, An as raceAgainstAbort, At as getSnapshotMemoryInfo, B as removeTrailingAssistantGuardContinuations, Bt as stateColumnsWrite, C as stampChunkProducedAt, Cn as DEADLINE_SAVE_WAIT_MS, D as isStructuredOutputError, Dn as guardStreamUntilMatch, Dt as validateTemplate, E as escapeUnescapedControlCharsInJsonStrings, En as getAbortReason, Et as traverseMappingPath, F as endOutputStreamSpanOutsideStep, Fn as safeEnqueue, Ft as latestStepResults, G as FLUSH_HELD_PARTS_KEY, Gt as diffStateAsJson, Ht as unusedStateEntries, I as findOwnModelStepSpan, In as safeError, It as materializeState, J as withoutHeldContent, K as REPROCESS_PART_KEY, Kt as patchState, Ln as createRunScope, Lt as materializeWorkflowRun, M as ProcessorRunner, N as ProcessorState, Nn as MastraModelInput, Nt as applyStateColumnsWrite, O as asJsonSchema, On as guardStreamWithAbort, Ot as getStepResult, P as endOutputStreamSpanAtStepEnd, Pn as safeClose, Pt as isStateCheckpointDue, Q as summarizeProcessorToolsForSpan, R as isTrailingAssistantGuardContinuation, Rn as createRunScopeKey, Rt as pickStateKeys, S as getChunkProducedAt, Sn as DEADLINE_SAVE_CLAIM_HOLD_MS, St as stepRefId, T as createOutputHandler, Tn as createTimeoutAbortSignal, Tt as templateReadsState, Ut as applyStatePatch, V as ProviderHistoryCompat, Vt as summarizeStepResult, X as summarizeProcessorModelForSpan, Y as summarizeActiveToolsForSpan, Yt as isObservationalMemoryEnabled$1, Z as summarizeProcessorResultForSpan, Zt as parseMemoryRequestContext, _ as persistProcessorDataChunk, _t as stubStepResult, a as convertFullStreamChunkToMastra, an as snapshotToolResult, at as PROCESSOR_ABORT_SIGNAL, b as resolveOutputMessageSkippingCompletionChecks, bn as pendingQueueThreadId, bt as predicateReadsState, c as WorkflowRunOutput, cn as validationErrorModelOutput, ct as getHydratedStepResult, d as MastraModelOutput, dn as resolveSuspendedToolRunId, dt as lazyStepResults, en as computeModelOutputProviderMetadata, et as resolveProcessorSpanAttributes, f as clearStepPartIndexes, fn as resolveThreadIdFromArgs, ft as loadStepResults, g as isFeedbackContinuation, gn as applyStateSignal, gt as storageV2StepResultAccessors, h as findStepPartBoundaries, hn as tryStreamWithJsonFallback, ht as residentStepResultsLoader, in as resolveModelOutputAfterToolResultProcessors, it as createProcessorSendSignal, j as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, jn as settledOrElapsed, k as getResponseFormat, kn as isMastraTimeoutError, kt as getStepResultAsync, l as TripWire, ln as isProcessorWorkflow, lt as hydrateStepResults, m as findIterationOffsetInParts, mn as tryGenerateWithJsonFallback, mt as residentStepResults, nn as latestProcessedModelOutput, nt as toProcessorSpanPhase, on as withAgentWorkflowToolMarker, ot as RunJournal, p as createDestructurableOutput, pn as supportedLanguageModelSpecifications, pt as loadedStepResults, q as takeHeldParts, rn as readModelOutput, rt as PROCESSOR_LATE_SIGNAL_SINK, s as MastraAgentNetworkStream, sn as normalizeModelOutput, st as buildStepResultAccessors, tn as hasToolResultProcessor, tt as resolveProcessorSpanName, u as getModelOutputForTripwire, un as isSupportedLanguageModel, ut as isStepResultStub, v as reconcileBufferedStepTexts, vn as assertNotQueueThreadId, vt as collectMappingStepRefs, w as markChunkOutputProcessed, wn as MastraTimeoutError, wt as resolveTemplate, x as resolveProcessorWriterMessageId, xn as takenQueueThreadId, xt as resolveStepOutputs, y as resolveMessageText, yn as isQueueThreadId, yt as collectPredicateStepRefs, z as needsTrailingAssistantGuard, zt as stateBaseOf } from "./stream-C_oNulbg.js";
7
+ import { $ as summarizeToolChoiceForSpan, $t as commitToolResult, A as isSignalChunkExcluded, An as raceAgainstAbort, At as getSnapshotMemoryInfo, B as removeTrailingAssistantGuardContinuations, Bt as stateColumnsWrite, C as stampChunkProducedAt, Cn as DEADLINE_SAVE_WAIT_MS, D as isStructuredOutputError, Dn as guardStreamUntilMatch, Dt as validateTemplate, E as escapeUnescapedControlCharsInJsonStrings, En as getAbortReason, Et as traverseMappingPath, F as endOutputStreamSpanOutsideStep, Fn as safeEnqueue, Ft as latestStepResults, G as FLUSH_HELD_PARTS_KEY, Gt as diffStateAsJson, Ht as unusedStateEntries, I as findOwnModelStepSpan, In as safeError, It as materializeState, J as withoutHeldContent, K as REPROCESS_PART_KEY, Kt as patchState, Ln as createRunScope, Lt as materializeWorkflowRun, M as ProcessorRunner, N as ProcessorState, Nn as MastraModelInput, Nt as applyStateColumnsWrite, O as asJsonSchema, On as guardStreamWithAbort, Ot as getStepResult, P as endOutputStreamSpanAtStepEnd, Pn as safeClose, Pt as isStateCheckpointDue, Q as summarizeProcessorToolsForSpan, R as isTrailingAssistantGuardContinuation, Rn as createRunScopeKey, Rt as pickStateKeys, S as getChunkProducedAt, Sn as DEADLINE_SAVE_CLAIM_HOLD_MS, St as stepRefId, T as createOutputHandler, Tn as createTimeoutAbortSignal, Tt as templateReadsState, Ut as applyStatePatch, V as ProviderHistoryCompat, Vt as summarizeStepResult, X as summarizeProcessorModelForSpan, Y as summarizeActiveToolsForSpan, Yt as isObservationalMemoryEnabled$1, Z as summarizeProcessorResultForSpan, Zt as parseMemoryRequestContext, _ as persistProcessorDataChunk, _t as stubStepResult, a as convertFullStreamChunkToMastra, an as snapshotToolResult, at as PROCESSOR_ABORT_SIGNAL, b as resolveOutputMessageSkippingCompletionChecks, bn as pendingQueueThreadId, bt as predicateReadsState, c as WorkflowRunOutput, cn as validationErrorModelOutput, ct as getHydratedStepResult, d as MastraModelOutput, dn as resolveSuspendedToolRunId, dt as lazyStepResults, en as computeModelOutputProviderMetadata, et as resolveProcessorSpanAttributes, f as clearStepPartIndexes, fn as resolveThreadIdFromArgs, ft as loadStepResults, g as isFeedbackContinuation, gn as applyStateSignal, gt as storageV2StepResultAccessors, h as findStepPartBoundaries, hn as tryStreamWithJsonFallback, ht as residentStepResultsLoader, in as resolveModelOutputAfterToolResultProcessors, it as createProcessorSendSignal, j as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, jn as settledOrElapsed, k as getResponseFormat, kn as isMastraTimeoutError, kt as getStepResultAsync, l as TripWire, ln as isProcessorWorkflow, lt as hydrateStepResults, m as findIterationOffsetInParts, mn as tryGenerateWithJsonFallback, mt as residentStepResults, nn as latestProcessedModelOutput, nt as toProcessorSpanPhase, on as withAgentWorkflowToolMarker, ot as RunJournal, p as createDestructurableOutput, pn as supportedLanguageModelSpecifications, pt as loadedStepResults, q as takeHeldParts, rn as readModelOutput, rt as PROCESSOR_LATE_SIGNAL_SINK, s as MastraAgentNetworkStream, sn as normalizeModelOutput, st as buildStepResultAccessors, tn as hasToolResultProcessor, tt as resolveProcessorSpanName, u as getModelOutputForTripwire, un as isSupportedLanguageModel, ut as isStepResultStub, v as reconcileBufferedStepTexts, vn as assertNotQueueThreadId, vt as collectMappingStepRefs, w as markChunkOutputProcessed, wn as MastraTimeoutError, wt as resolveTemplate, x as resolveProcessorWriterMessageId, xn as takenQueueThreadId, xt as resolveStepOutputs, y as resolveMessageText, yn as isQueueThreadId, yt as collectPredicateStepRefs, z as needsTrailingAssistantGuard, zt as stateBaseOf } from "./stream-D607FmAx.js";
8
8
  import { c as MASTRA_THREAD_ID_KEY, d as isReservedRequestContextKey, f as mergeVersionOverrides$1, l as MASTRA_VERSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_RESOURCE_ID_KEY, p as withoutLiveRequestKeys, r as MASTRA_INHERITED_MEMORY_KEY, s as MASTRA_SCOPES_KEY, t as MASTRA_CONTINUATION_TOOL_CALL_IDS_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
9
9
  import { S as withAck, _ as serializeError$1, h as stripModelSnapshots, n as PublisherQueueLimitError, p as slimNestedAgentChunks, r as CachingPubSub, t as DefaultStepResult, u as isRunLocalTopic, v as EventEmitterPubSub, x as isLeaseProvider, y as NoopLeaseProvider } from "./output-helpers-CVzhy1Y0.js";
10
10
  import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-RgFlLrxG.js";
11
11
  import { Bt as listScoresArgsSchema, Ft as listLogsArgsSchema, Lt as listMetricsArgsSchema, Nt as listFeedbackArgsSchema, t as EntityType } from "./storage-Cc50aQAp.js";
12
12
  import { a as getOrCreateSpan, f as resolveCurrentSpan, l as getTimeToFirstChunkMs, n as executeWithContextSync, o as getResumeTracingContext, p as resolveExportedSpanId, s as getRootExportSpan, t as executeWithContext, u as getWorkflowResumeTracingContext } from "./utils-DU_pU5SK.js";
13
13
  import { i as setSpanErrorOrigin, n as getSpanErrorOrigin } from "./error-count-BH-rJW7q.js";
14
- import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-DGa7alUy.js";
14
+ import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-CxHzqEEI.js";
15
15
  import { a as withToolPayloadTransformMetadata, i as transformToolPayloadForTargets, n as hasTransformedToolPayload, o as withToolPayloadTransformProviderMetadata, r as normalizeToolPayloadTransformPolicy, t as getTransformedToolPayload } from "./payload-transform-Dj3HUeD4.js";
16
16
  import { boundedStringify, ensureSerializable, safeStringify } from "./utils/safe-stringify.js";
17
17
  import { d as signalSpanAttributes, h as signalToXmlMarkup, l as mastraDBMessageToSignal, n as createSignal, o as isMastraSignalMessage, s as isTransientSignalMessage, u as resolveDeliveryAttributes } from "./signals-CqR_iWkg.js";
@@ -24,13 +24,13 @@ import { _ as getRequestContextInputValues, a as getModelFacingValidationError,
24
24
  import { a as isApprovalExempt, c as isProviderDefinedTool, d as markAgentWorkflowTool, f as markApprovalExempt, l as isProviderTool, n as getNeedsApprovalFn, o as isBuiltBeforeApproval, r as getProviderToolName, s as isMastraTool, t as getBeforeApprovalFn } from "./toolchecks-DrsZdc3S.js";
25
25
  import { a as waitDelay, i as getRetryAfterMs, n as DEFAULT_MAX_RETRY_AFTER_MS, r as clampDelayMs } from "./fetchWithRetry-DFSvpYDT.js";
26
26
  import { i as hasFreeFormObject } from "./model-DS-b2R-R.js";
27
- import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-CdCkSE3h.js";
27
+ import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-DBG4hlGl.js";
28
28
  import { t as InMemoryServerCache } from "./inmemory-BK3zLwvM.js";
29
29
  import { n as resolveDynamicArgument, t as getRequestUser } from "./dynamic-argument-BzPK3qPN.js";
30
- import { t as MastraLLMV1 } from "./model-Bz3zffBv.js";
31
- import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-nyjsIsHZ.js";
30
+ import { t as MastraLLMV1 } from "./model-sUJDcX2v.js";
31
+ import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-CQkzZUcK.js";
32
32
  import { h as getWorkflowFGAResourceId, i as MastraFGAPermissions, y as requireFGA } from "./ee-iTj2bRDt-By_B9ngH.js";
33
- import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-B8Lk1bt5.js";
33
+ import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-BoUX5G90.js";
34
34
  import { t as ToolStream } from "./stream-D9JOykz7.js";
35
35
  import { MISSING, collectInvalidPredicatePaths, createPredicateEvaluator, derivePredicateLabel, normalizePredicatePath, walk } from "./predicate/index.js";
36
36
  import { Classifier } from "./classifier/index.js";
@@ -39,7 +39,7 @@ import { HAND_BACK_STATE_SYMBOL, PARENT_STATE_SYMBOL, PUBSUB_SYMBOL, STREAM_FORM
39
39
  import { i as executeHook } from "./hooks-Bth8Cjpj.js";
40
40
  import { o as assertValidScheduleDefinition, v as validateScheduleTiming } from "./schedules-DZfSx-7P.js";
41
41
  import { A as writeObjective, D as readObjective, O as resolveEffectiveGoalSettings, T as formatGoalBudgetPausedReason, _ as clearCachedGoalObjective, b as GOAL_SCORER_ID, g as cacheGoalObjective, k as resolveGoalStore, w as clearObjective, x as GOAL_SCORE_WAITING } from "./state-processor-B9kxpM53.js";
42
- import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-CFWgIaqA.js";
42
+ import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-CUv0mU2y.js";
43
43
  import { t as GoalSignalProvider } from "./signal-provider-BslnAjWG.js";
44
44
  import { t as slugify } from "./slugify-BUNmb-Ga.js";
45
45
  import { F as LocalSandbox, at as evaluateReadRecord, c as Workspace, dt as WORKSPACE_TOOLS, g as resolveToolConfig, gt as shellQuote, h as createWorkspaceTools, ht as sliceByTokens, l as createSkillTools, lt as CompositeFilesystem, mt as estimateTokenCount, ot as normalizeReadTrackerPath, pt as sliceByTokensSafe, st as LocalFilesystem } from "./workspace-Ct2kAiDv.js";
@@ -40932,6 +40932,12 @@ var InMemoryKnowledgePageStore = class {
40932
40932
  read: input.read
40933
40933
  })));
40934
40934
  }
40935
+ async getPagesAtPaths(input) {
40936
+ return Promise.all(input.lookups.map((lookup) => this.getPageByPath({
40937
+ ...lookup,
40938
+ read: input.read
40939
+ })));
40940
+ }
40935
40941
  async getLastChildPositions(input) {
40936
40942
  return Object.fromEntries([...new Set(input.parentIds)].map((id) => [id, this.#children(id).sort(byPosition).at(-1)?.position ?? null]));
40937
40943
  }
@@ -41473,9 +41479,37 @@ var InMemoryKnowledgePageStore = class {
41473
41479
  this.#pins.set(key, pin);
41474
41480
  return clone$1(pin);
41475
41481
  }
41482
+ async listPinsByTier(input) {
41483
+ const { tiers, count, limit, ...filters } = input;
41484
+ const rank = (pin) => tiers.findIndex((tier) => pin.audience.some((entry) => tier.includes(entry)));
41485
+ const pins = this.#matchingPins({
41486
+ ...filters,
41487
+ audience: tiers.flat()
41488
+ }).sort((a, b) => rank(a) - rank(b));
41489
+ return {
41490
+ pins: pins.slice(0, pageSize(limit)).map((pin) => this.#listed(pin)),
41491
+ ...count ? { total: pins.length } : {}
41492
+ };
41493
+ }
41476
41494
  async listPins(input) {
41495
+ const pins = this.#matchingPins(input);
41496
+ const { items, nextCursor } = paginate(pins, input.cursor, input.limit);
41497
+ return {
41498
+ pins: items.map((pin) => this.#listed(pin)),
41499
+ ...nextCursor ? { nextCursor } : {},
41500
+ ...input.count ? { total: pins.length } : {}
41501
+ };
41502
+ }
41503
+ #listed(pin) {
41504
+ return {
41505
+ ...clone$1(pin),
41506
+ pageName: this.#pages.get(pin.pageId).name
41507
+ };
41508
+ }
41509
+ /** The pins {@link listPins} lists, newest first, before paging. */
41510
+ #matchingPins(input) {
41477
41511
  const audience = input.audience === "all" ? null : new Set(input.audience);
41478
- const pins = [...this.#pins.values()].filter((pin) => {
41512
+ return [...this.#pins.values()].filter((pin) => {
41479
41513
  const page = this.#pages.get(pin.pageId);
41480
41514
  if (!page || page.deletedAt || !this.#pageReadable(page, input.read)) return false;
41481
41515
  if (input.kind && pin.kind !== input.kind) return false;
@@ -41484,15 +41518,6 @@ var InMemoryKnowledgePageStore = class {
41484
41518
  if (pin.kind === "page" && input.withBody && !/\S/.test(page.body ?? "")) return false;
41485
41519
  return !audience || pin.audience.some((entry) => audience.has(entry));
41486
41520
  }).sort(newestFirst);
41487
- const { items, nextCursor } = paginate(pins, input.cursor, input.limit);
41488
- return {
41489
- pins: items.map((pin) => ({
41490
- ...clone$1(pin),
41491
- pageName: this.#pages.get(pin.pageId).name
41492
- })),
41493
- ...nextCursor ? { nextCursor } : {},
41494
- ...input.count ? { total: pins.length } : {}
41495
- };
41496
41521
  }
41497
41522
  };
41498
41523
  // src/storage/domains/knowledge/inmemory.ts
@@ -41526,6 +41551,12 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
41526
41551
  getPagesByPaths(input) {
41527
41552
  return this.#pageStore.getPagesByPaths(input);
41528
41553
  }
41554
+ getPagesAtPaths(input) {
41555
+ return this.#pageStore.getPagesAtPaths(input);
41556
+ }
41557
+ listPinsByTier(input) {
41558
+ return this.#pageStore.listPinsByTier(input);
41559
+ }
41529
41560
  getLastChildPositions(input) {
41530
41561
  return this.#pageStore.getLastChildPositions(input);
41531
41562
  }
@@ -44162,6 +44193,20 @@ var SchedulesStorage = class extends StorageDomain {
44162
44193
  });
44163
44194
  }
44164
44195
  async dangerouslyClearAll() {}
44196
+ /**
44197
+ * A view of this store holding one tenant's schedules. Ids are unique per
44198
+ * tenant, every read and write is limited to the tenant's rows, and created
44199
+ * rows carry its `tenantId`.
44200
+ *
44201
+ * The store this is called on keeps seeing only rows without a tenant,
44202
+ * except `listDueSchedules`, which spans every tenant so one tick can claim
44203
+ * what's due everywhere; claim a tenant's row through its `forTenant` view.
44204
+ *
44205
+ * Adapters that don't support tenants throw rather than ignore the tenant.
44206
+ */
44207
+ forTenant(_tenantId) {
44208
+ throw new Error(`${this.constructor.name} does not support tenant-scoped schedules`);
44209
+ }
44165
44210
  };
44166
44211
  // src/storage/domains/schedules/inmemory.ts
44167
44212
  function clone(value) {
@@ -44173,28 +44218,57 @@ function cloneRow(row) {
44173
44218
  copy.target = normalizeScheduleTarget(copy.target);
44174
44219
  return copy;
44175
44220
  }
44176
- var InMemorySchedulesStorage = class extends SchedulesStorage {
44221
+ var InMemorySchedulesStorage = class InMemorySchedulesStorage extends SchedulesStorage {
44177
44222
  db;
44178
- constructor({ db }) {
44223
+ #tenantId;
44224
+ constructor({ db, tenantId }) {
44179
44225
  super();
44180
44226
  this.db = db;
44227
+ this.#tenantId = tenantId;
44228
+ }
44229
+ forTenant(tenantId) {
44230
+ return new InMemorySchedulesStorage({
44231
+ db: this.db,
44232
+ tenantId
44233
+ });
44234
+ }
44235
+ /** Map key: root and tenant keys start differently, so neither can reach the other's rows. */
44236
+ #key(id) {
44237
+ return this.#tenantId === void 0 ? `root:${id}` : `tenant:${encodeURIComponent(this.#tenantId)}/${id}`;
44238
+ }
44239
+ #mine(row) {
44240
+ return row.tenantId === this.#tenantId;
44181
44241
  }
44242
+ /** The root store clears everything; a tenant's view clears only that tenant. */
44182
44243
  async dangerouslyClearAll() {
44183
- this.db.schedules.clear();
44184
- this.db.scheduleTriggers.length = 0;
44244
+ if (this.#tenantId === void 0) {
44245
+ this.db.schedules.clear();
44246
+ this.db.scheduleTriggers.length = 0;
44247
+ return;
44248
+ }
44249
+ for (const [key, row] of this.db.schedules) if (this.#mine(row)) this.db.schedules.delete(key);
44250
+ const triggers = this.db.scheduleTriggers;
44251
+ let kept = 0;
44252
+ for (const row of triggers) if (!this.#mine(row)) triggers[kept++] = row;
44253
+ triggers.length = kept;
44185
44254
  }
44186
44255
  async createSchedule(schedule) {
44187
- if (this.db.schedules.has(schedule.id)) throw new Error(`Schedule ${schedule.id} already exists`);
44188
- const stored = clone(schedule);
44189
- this.db.schedules.set(stored.id, stored);
44256
+ const key = this.#key(schedule.id);
44257
+ if (this.db.schedules.has(key)) throw new Error(`Schedule ${schedule.id} already exists`);
44258
+ const { tenantId: _ignored, ...rest } = schedule;
44259
+ const stored = clone(this.#tenantId === void 0 ? rest : {
44260
+ ...rest,
44261
+ tenantId: this.#tenantId
44262
+ });
44263
+ this.db.schedules.set(key, stored);
44190
44264
  return clone(stored);
44191
44265
  }
44192
44266
  async getSchedule(id) {
44193
- const found = this.db.schedules.get(id);
44267
+ const found = this.db.schedules.get(this.#key(id));
44194
44268
  return found ? cloneRow(found) : null;
44195
44269
  }
44196
44270
  async listSchedules(filter) {
44197
- let rows = Array.from(this.db.schedules.values());
44271
+ let rows = Array.from(this.db.schedules.values()).filter((r) => this.#mine(r));
44198
44272
  if (filter?.status) rows = rows.filter((r) => r.status === filter.status);
44199
44273
  if (filter?.workflowId) rows = rows.filter((r) => r.target.type === "workflow" && r.target.workflowId === filter.workflowId);
44200
44274
  if (filter?.ownerType !== void 0) rows = rows.filter((r) => (r.ownerType ?? null) === filter.ownerType);
@@ -44202,28 +44276,37 @@ var InMemorySchedulesStorage = class extends SchedulesStorage {
44202
44276
  rows.sort((a, b) => a.createdAt - b.createdAt);
44203
44277
  return rows.map(cloneRow);
44204
44278
  }
44205
- async listDueSchedules(now, limit) {
44279
+ async listDueSchedules(now, limit, options) {
44206
44280
  const due = [];
44207
- for (const row of this.db.schedules.values()) if (row.status === "active" && row.nextFireAt <= now) due.push(row);
44281
+ for (const row of this.db.schedules.values()) {
44282
+ if (this.#tenantId !== void 0) {
44283
+ if (!this.#mine(row)) continue;
44284
+ } else if (options?.unscoped && row.tenantId !== void 0) continue;
44285
+ else if (options?.tenants && row.tenantId === void 0) continue;
44286
+ if (row.status === "active" && row.nextFireAt <= now) due.push(row);
44287
+ }
44208
44288
  due.sort((a, b) => a.nextFireAt - b.nextFireAt);
44209
44289
  const cap = limit ?? due.length;
44210
44290
  return due.slice(0, cap).map(cloneRow);
44211
44291
  }
44212
44292
  async updateSchedule(id, patch) {
44213
- const existing = this.db.schedules.get(id);
44293
+ const existing = this.db.schedules.get(this.#key(id));
44214
44294
  if (!existing) throw new Error(`Schedule ${id} not found`);
44215
- const stored = clone({
44295
+ const updated = {
44216
44296
  ...existing,
44217
44297
  ...patch,
44218
44298
  target: patch.target !== void 0 ? patch.target : existing.target,
44219
44299
  metadata: patch.metadata !== void 0 ? patch.metadata : existing.metadata,
44220
44300
  updatedAt: Date.now()
44221
- });
44222
- this.db.schedules.set(id, stored);
44301
+ };
44302
+ if (existing.tenantId === void 0) delete updated.tenantId;
44303
+ else updated.tenantId = existing.tenantId;
44304
+ const stored = clone(updated);
44305
+ this.db.schedules.set(this.#key(id), stored);
44223
44306
  return cloneRow(stored);
44224
44307
  }
44225
44308
  async updateScheduleNextFire(id, expectedNextFireAt, newNextFireAt, lastFireAt, lastRunId, newStatus) {
44226
- const existing = this.db.schedules.get(id);
44309
+ const existing = this.db.schedules.get(this.#key(id));
44227
44310
  if (!existing) return false;
44228
44311
  if (existing.nextFireAt !== expectedNextFireAt) return false;
44229
44312
  if (existing.status !== "active") return false;
@@ -44235,23 +44318,28 @@ var InMemorySchedulesStorage = class extends SchedulesStorage {
44235
44318
  ...newStatus ? { status: newStatus } : {},
44236
44319
  updatedAt: Date.now()
44237
44320
  };
44238
- this.db.schedules.set(id, stored);
44321
+ this.db.schedules.set(this.#key(id), stored);
44239
44322
  return true;
44240
44323
  }
44241
44324
  async deleteSchedule(id) {
44242
- this.db.schedules.delete(id);
44243
- for (let i = this.db.scheduleTriggers.length - 1; i >= 0; i--) if (this.db.scheduleTriggers[i].scheduleId === id) this.db.scheduleTriggers.splice(i, 1);
44325
+ this.db.schedules.delete(this.#key(id));
44326
+ for (let i = this.db.scheduleTriggers.length - 1; i >= 0; i--) {
44327
+ const trigger = this.db.scheduleTriggers[i];
44328
+ if (trigger.scheduleId === id && this.#mine(trigger)) this.db.scheduleTriggers.splice(i, 1);
44329
+ }
44244
44330
  }
44245
44331
  async recordTrigger(trigger) {
44332
+ const { tenantId: _ignored, ...rest } = trigger;
44246
44333
  const stored = {
44247
- ...trigger,
44334
+ ...rest,
44335
+ ...this.#tenantId === void 0 ? {} : { tenantId: this.#tenantId },
44248
44336
  id: trigger.id ?? globalThis.crypto.randomUUID(),
44249
44337
  triggerKind: trigger.triggerKind ?? "schedule-fire"
44250
44338
  };
44251
44339
  this.db.scheduleTriggers.push(clone(stored));
44252
44340
  }
44253
44341
  async listTriggers(scheduleId, opts) {
44254
- let rows = this.db.scheduleTriggers.filter((f) => f.scheduleId === scheduleId);
44342
+ let rows = this.db.scheduleTriggers.filter((f) => f.scheduleId === scheduleId && this.#mine(f));
44255
44343
  if (opts?.fromActualFireAt != null) rows = rows.filter((f) => f.actualFireAt >= opts.fromActualFireAt);
44256
44344
  if (opts?.toActualFireAt != null) rows = rows.filter((f) => f.actualFireAt < opts.toActualFireAt);
44257
44345
  rows.sort((a, b) => b.actualFireAt - a.actualFireAt);
@@ -66477,16 +66565,28 @@ async function configPins(run, maxTokens) {
66477
66565
  listings: []
66478
66566
  };
66479
66567
  const scopes = await run.storage.getScopesByAddress([...new Set(bound.map((pin) => pin.address))]);
66568
+ const scopeOf = new Map(scopes.map((scope) => [scope.address, scope]));
66569
+ const lookups = bound.flatMap((pin) => {
66570
+ const scope = scopeOf.get(pin.address);
66571
+ return scope && pin.path.length > 0 ? [{
66572
+ scopeId: scope.id,
66573
+ path: pin.path
66574
+ }] : [];
66575
+ });
66576
+ const found = lookups.length === 0 ? [] : run.storage.getPagesAtPaths ? await run.storage.getPagesAtPaths({
66577
+ lookups,
66578
+ read: run.read
66579
+ }) : await Promise.all(lookups.map((lookup) => run.storage.getPageByPath({
66580
+ ...lookup,
66581
+ read: run.read
66582
+ })));
66583
+ let next = 0;
66480
66584
  const pages = /* @__PURE__ */ new Map();
66481
66585
  const listings = /* @__PURE__ */ new Map();
66482
66586
  for (const pin of bound) {
66483
- const scope = scopes.find((candidate) => candidate.address === pin.address);
66587
+ const scope = scopeOf.get(pin.address);
66484
66588
  if (!scope) continue;
66485
- const page = pin.path.length === 0 ? knowledgeScopeReadable(scope, run.read) ? scope : null : await run.storage.getPageByPath({
66486
- scopeId: scope.id,
66487
- path: pin.path,
66488
- read: run.read
66489
- });
66589
+ const page = pin.path.length === 0 ? knowledgeScopeReadable(scope, run.read) ? scope : null : found[next++];
66490
66590
  if (!page || page.deletedAt) continue;
66491
66591
  if (pin.depth === void 0) pages.set(page.id, page);
66492
66592
  else if ((listings.get(page.id)?.depth ?? 0) < pin.depth) listings.set(page.id, await resolveListing(run, page, pin.depth, maxTokens));
@@ -66508,6 +66608,28 @@ async function rankedStoredPins(run, excludePageIds, want) {
66508
66608
  withBody: true,
66509
66609
  excludePageIds
66510
66610
  };
66611
+ if (tiers.length === 0) return {
66612
+ pins: [],
66613
+ total: 0
66614
+ };
66615
+ if (run.storage.listPinsByTier && want <= 100) {
66616
+ const ranked = await run.storage.listPinsByTier({
66617
+ ...base,
66618
+ tiers,
66619
+ limit: want,
66620
+ count: true
66621
+ });
66622
+ const total = ranked.total ?? (await run.storage.listPins({
66623
+ ...base,
66624
+ audience: run.principals,
66625
+ limit: 1,
66626
+ count: true
66627
+ })).total ?? 0;
66628
+ return {
66629
+ pins: ranked.pins,
66630
+ total
66631
+ };
66632
+ }
66511
66633
  const pins = [];
66512
66634
  const seen = /* @__PURE__ */ new Set();
66513
66635
  let total;
@@ -66531,7 +66653,7 @@ async function rankedStoredPins(run, excludePageIds, want) {
66531
66653
  } while (cursor && pins.length < want);
66532
66654
  if (pins.length >= want) break;
66533
66655
  }
66534
- if (total === void 0) total = tiers.length === 0 ? 0 : (await run.storage.listPins({
66656
+ if (total === void 0) total = (await run.storage.listPins({
66535
66657
  ...base,
66536
66658
  audience: run.principals,
66537
66659
  limit: 1,
@@ -80143,22 +80265,29 @@ function createDurableLLMExecutionStep(_options) {
80143
80265
  }
80144
80266
  throwIfInterrupted();
80145
80267
  cleanupToolObservabilitySpans(true);
80146
- logger?.error?.("Error processing LLM stream", {
80147
- error,
80148
- runId
80149
- });
80150
80268
  const errorObj = error instanceof Error ? error : new Error(String(error));
80151
- if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80152
- error: errorObj,
80153
- endSpan: false
80154
- });
80155
- else if (modelSpan) modelSpan.error({
80156
- error: errorObj,
80157
- endSpan: false
80158
- });
80159
80269
  const innerTimeout = resolveTotalTimeoutAbort(executionAbortSignal, errorObj);
80270
+ const isAbort = !innerTimeout && (executionAbortSignal?.aborted === true || errorObj.name === "AbortError");
80271
+ if (!isAbort) {
80272
+ logger?.error?.("Error processing LLM stream", {
80273
+ error,
80274
+ runId
80275
+ });
80276
+ if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80277
+ error: errorObj,
80278
+ endSpan: false
80279
+ });
80280
+ else if (modelSpan) modelSpan.error({
80281
+ error: errorObj,
80282
+ endSpan: false
80283
+ });
80284
+ }
80160
80285
  if (innerTimeout) throw innerTimeout;
80161
- if (executionAbortSignal?.aborted === true || errorObj.name === "AbortError") {
80286
+ if (isAbort) {
80287
+ logger?.debug?.("LLM stream aborted", {
80288
+ error: errorObj,
80289
+ runId
80290
+ });
80162
80291
  materializeStreamedMessages();
80163
80292
  return {
80164
80293
  ...await storeStepTranscript(),
@@ -80223,21 +80352,28 @@ function createDurableLLMExecutionStep(_options) {
80223
80352
  const streamError = outputStream.error;
80224
80353
  if (streamError) {
80225
80354
  const streamErrorObj = streamError instanceof Error ? streamError : new Error(String(streamError));
80226
- logger?.error?.("Stream captured error", {
80227
- error: streamErrorObj,
80228
- runId
80229
- });
80230
- if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80231
- error: streamErrorObj,
80232
- endSpan: false
80233
- });
80234
- else if (modelSpan) modelSpan.error({
80235
- error: streamErrorObj,
80236
- endSpan: false
80237
- });
80238
80355
  const streamErrorTimeout = resolveTotalTimeoutAbort(executionAbortSignal, streamErrorObj);
80356
+ const isStreamErrorAbort = !streamErrorTimeout && (executionAbortSignal?.aborted === true || streamErrorObj.name === "AbortError");
80357
+ if (!isStreamErrorAbort) {
80358
+ logger?.error?.("Stream captured error", {
80359
+ error: streamErrorObj,
80360
+ runId
80361
+ });
80362
+ if (modelSpanTracker) modelSpanTracker.reportGenerationError({
80363
+ error: streamErrorObj,
80364
+ endSpan: false
80365
+ });
80366
+ else if (modelSpan) modelSpan.error({
80367
+ error: streamErrorObj,
80368
+ endSpan: false
80369
+ });
80370
+ }
80239
80371
  if (streamErrorTimeout) throw streamErrorTimeout;
80240
- if (executionAbortSignal?.aborted === true || streamErrorObj.name === "AbortError") {
80372
+ if (isStreamErrorAbort) {
80373
+ logger?.debug?.("Captured LLM stream aborted", {
80374
+ error: streamErrorObj,
80375
+ runId
80376
+ });
80241
80377
  materializeStreamedMessages();
80242
80378
  return {
80243
80379
  ...await storeStepTranscript(),
@@ -86211,7 +86347,7 @@ async function prepareForDurableExecution(options) {
86211
86347
  });
86212
86348
  let tripwireData;
86213
86349
  if (inputProcessors.length > 0) try {
86214
- const { ProcessorRunner } = await import("./stream-C_oNulbg.js").then((n) => n.L);
86350
+ const { ProcessorRunner } = await import("./stream-D607FmAx.js").then((n) => n.L);
86215
86351
  await new ProcessorRunner({
86216
86352
  inputProcessors,
86217
86353
  outputProcessors,
@@ -96085,7 +96221,7 @@ var Agent = class Agent extends MastraBase {
96085
96221
  }
96086
96222
  }
96087
96223
  /** Rebuilds process-local recovery state from the persisted durable workflow input. */
96088
- async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
96224
+ async #rehydrateRecoveryState({ runId, workflowInput, abortController, onTerminalDeadline, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
96089
96225
  const requestContext = workflowInput.requestContextEntries ? new RequestContext(Object.entries(workflowInput.requestContextEntries)) : new RequestContext();
96090
96226
  restoreRunAgentScopes(requestContext);
96091
96227
  const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
@@ -96301,7 +96437,7 @@ var Agent = class Agent extends MastraBase {
96301
96437
  subscribePendingSignals: (listener) => wrapped.__getSubscribePendingSignals()(runId, listener),
96302
96438
  cleanup: () => {}
96303
96439
  };
96304
- this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
96440
+ this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence, onTerminalDeadline);
96305
96441
  this.#runInputs.set(executionFence, {
96306
96442
  ...workflowInput,
96307
96443
  messageListState: latestMessageListState ?? workflowInput.messageListState
@@ -96500,7 +96636,7 @@ var Agent = class Agent extends MastraBase {
96500
96636
  * each session gets a fresh timer. The timer is torn down via the entry's
96501
96637
  * `cleanup` slot, which every settle path invokes through the run registry.
96502
96638
  */
96503
- installAbortWithTotalTimeout(entry, abortController, executionFence) {
96639
+ installAbortWithTotalTimeout(entry, abortController, executionFence, onTerminalDeadline) {
96504
96640
  entry.abortController = abortController;
96505
96641
  entry.deadlineErrorRedelivered = false;
96506
96642
  const totalTimeout = createTimeoutAbortSignal({
@@ -96512,10 +96648,14 @@ var Agent = class Agent extends MastraBase {
96512
96648
  entry.abortSignal = totalTimeout.signal;
96513
96649
  if (totalTimeout.timeoutPromise) totalTimeout.timeoutPromise.catch(async (error) => {
96514
96650
  if (!isMastraTimeoutError(error) || error.timeoutType !== "total" || totalTimeout.signal?.reason !== error) return;
96515
- await this.settleExecution(executionFence.runId, executionFence, {
96516
- status: "failed",
96517
- error
96518
- });
96651
+ try {
96652
+ await this.settleExecution(executionFence.runId, executionFence, {
96653
+ status: "failed",
96654
+ error
96655
+ });
96656
+ } finally {
96657
+ onTerminalDeadline?.();
96658
+ }
96519
96659
  }).catch((error) => {
96520
96660
  this.logger.warn("Failed to settle durable agent at its total deadline", { error });
96521
96661
  });
@@ -96614,11 +96754,19 @@ var Agent = class Agent extends MastraBase {
96614
96754
  }
96615
96755
  this.executionEngine.assertRecoveryActive();
96616
96756
  const releaseLocalRecovery = this.executionEngine.claimLocalRecovery(this.id, this.name, runId);
96617
- const { controller: abortController } = createRunAbortController(options?.abortSignal);
96757
+ const { controller: abortController, detach: detachExternalAbort } = createRunAbortController(options?.abortSignal);
96758
+ let recoveryReleased = false;
96759
+ const releaseRecovery = () => {
96760
+ if (recoveryReleased) return;
96761
+ recoveryReleased = true;
96762
+ detachExternalAbort();
96763
+ releaseLocalRecovery();
96764
+ };
96618
96765
  let executionFence;
96619
96766
  let recoveryState;
96620
96767
  let finishPublishedBeforeCrash;
96621
96768
  let claimedSnapshot;
96769
+ let recoveryHandedOff = false;
96622
96770
  try {
96623
96771
  executionFence = await this.executionEngine.claimExecution(runId, options?.force ? "takeover" : "recover", this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, this.logger, this.#untrackedRunLiveness(runId, workflowInput));
96624
96772
  this.executionEngine.assertRecoveryActive();
@@ -96632,6 +96780,7 @@ var Agent = class Agent extends MastraBase {
96632
96780
  runId,
96633
96781
  workflowInput,
96634
96782
  abortController,
96783
+ onTerminalDeadline: detachExternalAbort,
96635
96784
  executionFence,
96636
96785
  originalSpansEnded: loaded.originalSpansEnded,
96637
96786
  openStepsOf: loaded.openStepsOf,
@@ -96641,146 +96790,154 @@ var Agent = class Agent extends MastraBase {
96641
96790
  this.#recoveredEntries.set(executionFence, recoveryState.registryEntry);
96642
96791
  this.executionEngine.assertRecoveryActive();
96643
96792
  } catch (error) {
96644
- const settlement = await executionFence?.settle(async () => {});
96645
- if (executionFence && settlement !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96646
- releaseLocalRecovery();
96647
- throw error;
96648
- }
96649
- const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } = recoveryState;
96650
- if (executionFence.generation !== void 0) {
96651
- const supersededFrom = await this.executionEngine.recoverySupersededFrom(workflowsStore, runId, claimedSnapshot, () => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, () => this.logger);
96652
- await emitOwnershipClaimedEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, executionFence.generation, supersededFrom).catch((error) => {
96653
- this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {
96654
- runId,
96655
- error
96656
- });
96657
- });
96658
- }
96659
- setExecutionClaim(requestContext, runId, executionFence.claim);
96660
- registryEntry.executionFence = executionFence;
96661
- let streamCleanup;
96662
- const cleanupOwnedRegistryState = () => {
96663
- if (registryEntry.executionFence !== executionFence) return;
96664
- if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
96665
- if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {
96666
- globalRunRegistry.delete(runId);
96667
- if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96668
- }
96669
- };
96670
- const runCleanup = createRunCleanup({
96671
- scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96672
- release: () => {
96673
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96674
- streamCleanup?.();
96675
- cleanupOwnedRegistryState();
96793
+ try {
96794
+ const settlement = await executionFence?.settle(async () => {});
96795
+ if (executionFence && settlement !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96796
+ } finally {
96797
+ releaseRecovery();
96676
96798
  }
96677
- });
96678
- const performCleanup = runCleanup.run;
96679
- const scheduleAutoCleanup = runCleanup.schedule;
96680
- let workflow;
96681
- try {
96682
- this.executionEngine.assertRecoveryActive();
96683
- workflow = this.getWorkflow();
96684
- } catch (error) {
96685
- if (await executionFence.settle(async () => {}) !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96686
- releaseLocalRecovery();
96687
96799
  throw error;
96688
96800
  }
96689
- const { stream, threadRegistration } = await this.#setupRecoveredStream({
96690
- runId,
96691
- workflowInput,
96692
- requestContext,
96693
- threadId,
96694
- resourceId,
96695
- messageList,
96696
- registryEntry,
96697
- options,
96698
- scheduleAutoCleanup,
96699
- executionFence
96700
- }).catch((error) => {
96701
- releaseLocalRecovery();
96702
- throw error;
96703
- });
96704
- const { output, cleanup: createdStreamCleanup, ready } = stream;
96705
- streamCleanup = createdStreamCleanup;
96706
- const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96707
- const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96708
- const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, createObservabilityContext({ currentSpan: recoverAgentSpan }));
96709
- if (finishPublishedBeforeCrash && result?.status === "success") {
96710
- const { output: finalOutput, stepResult, tracingTermination, stopCause } = result.result;
96711
- recoverModelSpan?.end({ ...tracingTermination });
96712
- recoverAgentSpan?.end({
96713
- ...tracingTermination,
96714
- output: { text: finalOutput?.text }
96715
- });
96716
- await emitFinishEvent(recoveryPubsub, runId, {
96717
- output: finalOutput,
96718
- stepResult,
96719
- ...stopCause && { stopCause }
96801
+ try {
96802
+ const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } = recoveryState;
96803
+ if (executionFence.generation !== void 0) {
96804
+ const supersededFrom = await this.executionEngine.recoverySupersededFrom(workflowsStore, runId, claimedSnapshot, () => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, () => this.logger);
96805
+ await emitOwnershipClaimedEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, executionFence.generation, supersededFrom).catch((error) => {
96806
+ this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {
96807
+ runId,
96808
+ error
96809
+ });
96720
96810
  });
96721
96811
  }
96722
- if (result?.status === "suspended" && options?.closeOnSuspend) {
96723
- await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
96724
- await stream.waitForEventDelivery();
96725
- executionFence.throwIfLost();
96726
- stream.detach();
96812
+ setExecutionClaim(requestContext, runId, executionFence.claim);
96813
+ registryEntry.executionFence = executionFence;
96814
+ let streamCleanup;
96815
+ const cleanupOwnedRegistryState = () => {
96816
+ if (registryEntry.executionFence !== executionFence) return;
96817
+ if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
96818
+ if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {
96819
+ globalRunRegistry.delete(runId);
96820
+ if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96821
+ }
96822
+ };
96823
+ const runCleanup = createRunCleanup({
96824
+ scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96825
+ release: () => {
96826
+ agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96827
+ streamCleanup?.();
96828
+ cleanupOwnedRegistryState();
96829
+ }
96830
+ });
96831
+ const performCleanup = runCleanup.run;
96832
+ const scheduleAutoCleanup = runCleanup.schedule;
96833
+ let workflow;
96834
+ try {
96835
+ this.executionEngine.assertRecoveryActive();
96836
+ workflow = this.getWorkflow();
96837
+ } catch (error) {
96838
+ if (await executionFence.settle(async () => {}) !== "superseded" && this.executionEngine.shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
96839
+ releaseRecovery();
96840
+ throw error;
96727
96841
  }
96728
- const finished = !!result?.status && result.status !== "suspended";
96729
- await executionFence.settle(async () => {
96730
- if (finished) await this.deleteRunSnapshots(runId);
96731
- if (finished) await releaseRemoteAbortListener(runId, this.#mastra);
96842
+ const { stream, threadRegistration } = await this.#setupRecoveredStream({
96843
+ runId,
96844
+ workflowInput,
96845
+ requestContext,
96846
+ threadId,
96847
+ resourceId,
96848
+ messageList,
96849
+ registryEntry,
96850
+ options,
96851
+ scheduleAutoCleanup,
96852
+ executionFence
96853
+ }).catch((error) => {
96854
+ releaseRecovery();
96855
+ throw error;
96732
96856
  });
96733
- if (result?.status === "failed") throw this.executionEngine.workflowFailureError(result.error, "Workflow recover failed");
96734
- }).catch(async (error) => {
96735
- if (error?.id === "DURABLE_AGENT_RECOVER_SHUTDOWN") await executionFence.abandon();
96736
- const executionError = this.executionEngine.workflowExecutionError(error, "Workflow recover failed");
96737
- if (await executionFence.settle(async () => {}) === "superseded") {
96738
- const output = {
96739
- status: "interrupted",
96740
- reason: "recovery superseded"
96741
- };
96742
- recoverModelSpan?.end({
96743
- output,
96744
- outcome: "interrupted",
96745
- stopReason: null,
96746
- stopReasonContext: null
96747
- });
96748
- recoverAgentSpan?.end({
96749
- output,
96750
- outcome: "interrupted",
96751
- stopReason: null,
96752
- stopReasonContext: null
96857
+ const { output, cleanup: createdStreamCleanup, ready } = stream;
96858
+ streamCleanup = createdStreamCleanup;
96859
+ const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96860
+ const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96861
+ const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, createObservabilityContext({ currentSpan: recoverAgentSpan }));
96862
+ if (finishPublishedBeforeCrash && result?.status === "success") {
96863
+ const { output: finalOutput, stepResult, tracingTermination, stopCause } = result.result;
96864
+ recoverModelSpan?.end({ ...tracingTermination });
96865
+ recoverAgentSpan?.end({
96866
+ ...tracingTermination,
96867
+ output: { text: finalOutput?.text }
96868
+ });
96869
+ await emitFinishEvent(recoveryPubsub, runId, {
96870
+ output: finalOutput,
96871
+ stepResult,
96872
+ ...stopCause && { stopCause }
96873
+ });
96874
+ }
96875
+ if (result?.status === "suspended" && options?.closeOnSuspend) {
96876
+ await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
96877
+ await stream.waitForEventDelivery();
96878
+ executionFence.throwIfLost();
96879
+ stream.detach();
96880
+ }
96881
+ const finished = !!result?.status && result.status !== "suspended";
96882
+ await executionFence.settle(async () => {
96883
+ if (finished) await this.deleteRunSnapshots(runId);
96884
+ if (finished) await releaseRemoteAbortListener(runId, this.#mastra);
96753
96885
  });
96754
- await threadRegistration?.rollback({ releaseLease: false });
96755
- performCleanup();
96756
- } else if (!this.#timedOutExecutions.has(executionFence) && !await this.#reportRecoveryFailure(runId, executionError, executionFence.generation)) {
96757
- await threadRegistration?.rollback();
96758
- performCleanup();
96759
- }
96760
- throw executionError;
96761
- }).finally(releaseLocalRecovery));
96762
- const trackedRecoverEntry = getRunRegistryEntry(runId, this.#mastra);
96763
- if (trackedRecoverEntry) trackedRecoverEntry.workflowExecution = workflowExecution;
96764
- workflowExecution.catch(() => {});
96765
- const cleanup = performCleanup;
96766
- const abort = async (reason) => {
96767
- if (!abortController.signal.aborted) abortController.abort(reason);
96768
- await this.requestRemoteAbort(runId);
96769
- if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
96770
- };
96771
- return {
96772
- output,
96773
- get fullStream() {
96774
- return output.fullStream;
96775
- },
96776
- runId,
96777
- threadId,
96778
- resourceId,
96779
- traceId: output.traceId,
96780
- spanId: output.spanId,
96781
- cleanup,
96782
- abort
96783
- };
96886
+ if (result?.status === "failed") throw this.executionEngine.workflowFailureError(result.error, "Workflow recover failed");
96887
+ }).catch(async (error) => {
96888
+ if (error?.id === "DURABLE_AGENT_RECOVER_SHUTDOWN") await executionFence.abandon();
96889
+ const executionError = this.executionEngine.workflowExecutionError(error, "Workflow recover failed");
96890
+ if (await executionFence.settle(async () => {}) === "superseded") {
96891
+ const output = {
96892
+ status: "interrupted",
96893
+ reason: "recovery superseded"
96894
+ };
96895
+ recoverModelSpan?.end({
96896
+ output,
96897
+ outcome: "interrupted",
96898
+ stopReason: null,
96899
+ stopReasonContext: null
96900
+ });
96901
+ recoverAgentSpan?.end({
96902
+ output,
96903
+ outcome: "interrupted",
96904
+ stopReason: null,
96905
+ stopReasonContext: null
96906
+ });
96907
+ await threadRegistration?.rollback({ releaseLease: false });
96908
+ performCleanup();
96909
+ } else if (!this.#timedOutExecutions.has(executionFence) && !await this.#reportRecoveryFailure(runId, executionError, executionFence.generation)) {
96910
+ await threadRegistration?.rollback();
96911
+ performCleanup();
96912
+ }
96913
+ throw executionError;
96914
+ }).finally(releaseRecovery));
96915
+ recoveryHandedOff = true;
96916
+ const trackedRecoverEntry = getRunRegistryEntry(runId, this.#mastra);
96917
+ if (trackedRecoverEntry) trackedRecoverEntry.workflowExecution = workflowExecution;
96918
+ workflowExecution.catch(() => {});
96919
+ const cleanup = performCleanup;
96920
+ const abort = async (reason) => {
96921
+ if (!abortController.signal.aborted) abortController.abort(reason);
96922
+ await this.requestRemoteAbort(runId);
96923
+ if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
96924
+ };
96925
+ return {
96926
+ output,
96927
+ get fullStream() {
96928
+ return output.fullStream;
96929
+ },
96930
+ runId,
96931
+ threadId,
96932
+ resourceId,
96933
+ traceId: output.traceId,
96934
+ spanId: output.spanId,
96935
+ cleanup,
96936
+ abort
96937
+ };
96938
+ } finally {
96939
+ if (!recoveryHandedOff) releaseRecovery();
96940
+ }
96784
96941
  }
96785
96942
  /**
96786
96943
  * Clear retained pubsub state for a run's topics (cached history and, for
@@ -97184,166 +97341,172 @@ var Agent = class Agent extends MastraBase {
97184
97341
  setExecutionClaim(requestContext, runId, executionFence.claim);
97185
97342
  registryEntry.executionFence = executionFence;
97186
97343
  this.#runInputs.set(executionFence, workflowInput);
97187
- const { controller: abortController } = createRunAbortController(options?.abortSignal);
97188
- if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
97189
- this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
97190
- const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
97191
- registryEntry.agentId = this.id;
97192
- this.executionRunRegistry.registerWithMessageList(runId, registryEntry, messageList, {
97193
- threadId,
97194
- resourceId
97195
- });
97196
- const globalRegistryEntry = {
97197
- ...registryEntry,
97198
- messageList
97199
- };
97200
- globalRunRegistry.set(runId, globalRegistryEntry);
97201
- await this.attachStreamPublisher(runId, {
97202
- threadId,
97203
- resourceId
97204
- });
97205
- const segment = methodType === "stream" ? this.#beginSegment(runId) : void 0;
97206
- let streamCleanup;
97207
- const releaseRunState = () => {
97208
- if (segment !== void 0) {
97209
- if (!this.#releaseSegment(runId, segment, registryEntry)) return;
97210
- } else if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
97211
- if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
97212
- globalRunRegistry.delete(runId);
97213
- if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, globalRegistryEntry);
97214
- }
97215
- };
97216
- const runCleanup = createRunCleanup({
97217
- scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
97218
- release: () => {
97219
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
97220
- streamCleanup?.();
97221
- releaseRunState();
97222
- },
97223
- ...methodType === "generate" ? { releaseOnTimer: releaseRunState } : {}
97224
- });
97225
- const performCleanup = runCleanup.run;
97226
- const scheduleAutoCleanup = runCleanup.schedule;
97227
- const closeOnSuspend = methodType === "generate" || (options?.closeOnSuspend ?? false);
97228
- const closeOnPersistedSuspend = methodType === "stream" && closeOnSuspend && this.executionEngine.suspendPersistedOnReturn;
97229
- const { output, cleanup: createdStreamCleanup, detach: detachStream, waitForEventDelivery, ready } = createDurableAgentStream({
97230
- pubsub: this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub,
97231
- runId,
97232
- minGeneration: executionFence.generation,
97233
- onTerminalEvent: this.owningReaderTerminal(runId, executionFence),
97234
- readLocalRequest,
97235
- messageId,
97236
- model: {
97237
- modelId: workflowInput.modelConfig.modelId,
97238
- provider: workflowInput.modelConfig.provider,
97239
- version: "v3"
97240
- },
97241
- threadId,
97242
- resourceId,
97243
- onChunk: options?.onChunk,
97244
- experimentalTransform: options?.experimentalTransform,
97245
- onStepFinish: options?.onStepFinish,
97246
- onFinish: options?.onFinish,
97247
- onStreamFinished: scheduleAutoCleanup,
97248
- onError: async (error) => {
97249
- await options?.onError?.(error);
97250
- scheduleAutoCleanup();
97251
- },
97252
- onSuspended: options?.onSuspended,
97253
- onAbort: async (data) => {
97254
- try {
97255
- await (options?.onAbort)?.(data);
97256
- } finally {
97257
- scheduleAutoCleanup();
97258
- }
97259
- },
97260
- closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,
97261
- ...methodType === "stream" ? { hideSignals: options?.hideSignals } : {},
97262
- structuredOutput: registryEntry.structuredOutput,
97263
- outputProcessors: registryEntry.outputProcessors,
97264
- processorStates: registryEntry.processorStates,
97265
- agent: registryEntry.agent,
97266
- requestContext: registryEntry.requestContext,
97267
- returnScorerData: workflowInput.options.returnScorerData,
97268
- tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
97269
- messageList,
97270
- messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
97271
- });
97272
- streamCleanup = createdStreamCleanup;
97273
- const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
97274
- continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
97275
- generation: executionFence.generation,
97276
- ownershipLost: () => executionFence.isLost(),
97277
- stepOwner: () => getRunRegistryEntry(runId, this.#mastra),
97278
- signalsStore: registryEntry.pendingSignalsStore
97279
- });
97280
- const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
97281
- if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
97282
- await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
97283
- type: "start",
97284
- runId,
97285
- from: "AGENT",
97286
- payload: {
97287
- id: workflowInput.agentId,
97288
- messageId
97289
- }
97344
+ const { controller: abortController, detach: detachExternalAbort } = createRunAbortController(options?.abortSignal);
97345
+ let workflowExecutionOwnsDetach = false;
97346
+ try {
97347
+ if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
97348
+ this.installAbortWithTotalTimeout(registryEntry, abortController, executionFence, detachExternalAbort);
97349
+ const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
97350
+ registryEntry.agentId = this.id;
97351
+ this.executionRunRegistry.registerWithMessageList(runId, registryEntry, messageList, {
97352
+ threadId,
97353
+ resourceId
97290
97354
  });
97291
- if (this.__getGoalConfig()) await beginGoalActivity({
97292
- mastra: this.#mastra,
97293
- agentId: workflowInput.agentId,
97355
+ const globalRegistryEntry = {
97356
+ ...registryEntry,
97357
+ messageList
97358
+ };
97359
+ globalRunRegistry.set(runId, globalRegistryEntry);
97360
+ await this.attachStreamPublisher(runId, {
97294
97361
  threadId,
97362
+ resourceId
97363
+ });
97364
+ const segment = methodType === "stream" ? this.#beginSegment(runId) : void 0;
97365
+ let streamCleanup;
97366
+ const releaseRunState = () => {
97367
+ if (segment !== void 0) {
97368
+ if (!this.#releaseSegment(runId, segment, registryEntry)) return;
97369
+ } else if (this.executionRunRegistry.get(runId) === registryEntry) this.executionRunRegistry.cleanup(runId);
97370
+ if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
97371
+ globalRunRegistry.delete(runId);
97372
+ if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, globalRegistryEntry);
97373
+ }
97374
+ };
97375
+ const runCleanup = createRunCleanup({
97376
+ scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
97377
+ release: () => {
97378
+ agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
97379
+ streamCleanup?.();
97380
+ releaseRunState();
97381
+ },
97382
+ ...methodType === "generate" ? { releaseOnTimer: releaseRunState } : {}
97383
+ });
97384
+ const performCleanup = runCleanup.run;
97385
+ const scheduleAutoCleanup = runCleanup.schedule;
97386
+ const closeOnSuspend = methodType === "generate" || (options?.closeOnSuspend ?? false);
97387
+ const closeOnPersistedSuspend = methodType === "stream" && closeOnSuspend && this.executionEngine.suspendPersistedOnReturn;
97388
+ const { output, cleanup: createdStreamCleanup, detach: detachStream, waitForEventDelivery, ready } = createDurableAgentStream({
97389
+ pubsub: this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub,
97295
97390
  runId,
97296
- requestContext: getRunRegistryEntry(runId, this.#mastra)?.requestContext
97391
+ minGeneration: executionFence.generation,
97392
+ onTerminalEvent: this.owningReaderTerminal(runId, executionFence),
97393
+ readLocalRequest,
97394
+ messageId,
97395
+ model: {
97396
+ modelId: workflowInput.modelConfig.modelId,
97397
+ provider: workflowInput.modelConfig.provider,
97398
+ version: "v3"
97399
+ },
97400
+ threadId,
97401
+ resourceId,
97402
+ onChunk: options?.onChunk,
97403
+ experimentalTransform: options?.experimentalTransform,
97404
+ onStepFinish: options?.onStepFinish,
97405
+ onFinish: options?.onFinish,
97406
+ onStreamFinished: scheduleAutoCleanup,
97407
+ onError: async (error) => {
97408
+ await options?.onError?.(error);
97409
+ scheduleAutoCleanup();
97410
+ },
97411
+ onSuspended: options?.onSuspended,
97412
+ onAbort: async (data) => {
97413
+ try {
97414
+ await (options?.onAbort)?.(data);
97415
+ } finally {
97416
+ scheduleAutoCleanup();
97417
+ }
97418
+ },
97419
+ closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,
97420
+ ...methodType === "stream" ? { hideSignals: options?.hideSignals } : {},
97421
+ structuredOutput: registryEntry.structuredOutput,
97422
+ outputProcessors: registryEntry.outputProcessors,
97423
+ processorStates: registryEntry.processorStates,
97424
+ agent: registryEntry.agent,
97425
+ requestContext: registryEntry.requestContext,
97426
+ returnScorerData: workflowInput.options.returnScorerData,
97427
+ tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
97428
+ messageList,
97429
+ messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
97297
97430
  });
97298
- let result;
97299
- try {
97300
- const signalsStore = registryEntry.pendingSignalsStore;
97301
- const moved = signalsStore ? agentThreadStreamRuntime.storedSignalWritesSettled(signalsStore, this.getPubSub()) : void 0;
97302
- if (moved) await moved;
97303
- await this.#persistInitialInput(runId, workflowInput);
97304
- result = await this.executeWorkflow(runId, workflowInput);
97305
- } catch (error) {
97306
- await this.#discardRestartableStart(runId, workflowInput.agentId);
97307
- throw error;
97308
- } finally {
97309
- this.#restartableStarts.delete(runId);
97310
- await stopGoalActivity({
97431
+ streamCleanup = createdStreamCleanup;
97432
+ const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
97433
+ continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
97434
+ generation: executionFence.generation,
97435
+ ownershipLost: () => executionFence.isLost(),
97436
+ stepOwner: () => getRunRegistryEntry(runId, this.#mastra),
97437
+ signalsStore: registryEntry.pendingSignalsStore
97438
+ });
97439
+ const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
97440
+ if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
97441
+ await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
97442
+ type: "start",
97443
+ runId,
97444
+ from: "AGENT",
97445
+ payload: {
97446
+ id: workflowInput.agentId,
97447
+ messageId
97448
+ }
97449
+ });
97450
+ if (this.__getGoalConfig()) await beginGoalActivity({
97451
+ mastra: this.#mastra,
97311
97452
  agentId: workflowInput.agentId,
97312
- runId
97453
+ threadId,
97454
+ runId,
97455
+ requestContext: getRunRegistryEntry(runId, this.#mastra)?.requestContext
97313
97456
  });
97314
- }
97315
- if (closeOnPersistedSuspend && result?.status === "suspended") {
97316
- await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
97317
- await waitForEventDelivery();
97318
- detachStream();
97319
- }
97320
- if (methodType === "generate") return result;
97321
- }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
97322
- const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
97323
- if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
97324
- await threadRegistration;
97325
- const cleanup = () => {
97326
- if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
97327
- Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
97328
- };
97329
- const abort = async (reason) => {
97330
- if (!abortController.signal.aborted) abortController.abort(reason);
97331
- await this.requestRemoteAbort(runId);
97332
- if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
97333
- };
97334
- return {
97335
- output,
97336
- get fullStream() {
97337
- return output.fullStream;
97338
- },
97339
- runId,
97340
- threadId,
97341
- resourceId,
97342
- traceId: output.traceId,
97343
- spanId: output.spanId,
97344
- cleanup,
97345
- abort
97346
- };
97457
+ let result;
97458
+ try {
97459
+ const signalsStore = registryEntry.pendingSignalsStore;
97460
+ const moved = signalsStore ? agentThreadStreamRuntime.storedSignalWritesSettled(signalsStore, this.getPubSub()) : void 0;
97461
+ if (moved) await moved;
97462
+ await this.#persistInitialInput(runId, workflowInput);
97463
+ result = await this.executeWorkflow(runId, workflowInput);
97464
+ } catch (error) {
97465
+ await this.#discardRestartableStart(runId, workflowInput.agentId);
97466
+ throw error;
97467
+ } finally {
97468
+ this.#restartableStarts.delete(runId);
97469
+ await stopGoalActivity({
97470
+ agentId: workflowInput.agentId,
97471
+ runId
97472
+ });
97473
+ }
97474
+ if (closeOnPersistedSuspend && result?.status === "suspended") {
97475
+ await this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush();
97476
+ await waitForEventDelivery();
97477
+ detachStream();
97478
+ }
97479
+ if (methodType === "generate") return result;
97480
+ }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })).finally(detachExternalAbort));
97481
+ workflowExecutionOwnsDetach = true;
97482
+ const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
97483
+ if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
97484
+ await threadRegistration;
97485
+ const cleanup = () => {
97486
+ if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
97487
+ Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
97488
+ };
97489
+ const abort = async (reason) => {
97490
+ if (!abortController.signal.aborted) abortController.abort(reason);
97491
+ await this.requestRemoteAbort(runId);
97492
+ if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) this.abortRunStream(runId);
97493
+ };
97494
+ return {
97495
+ output,
97496
+ get fullStream() {
97497
+ return output.fullStream;
97498
+ },
97499
+ runId,
97500
+ threadId,
97501
+ resourceId,
97502
+ traceId: output.traceId,
97503
+ spanId: output.spanId,
97504
+ cleanup,
97505
+ abort
97506
+ };
97507
+ } finally {
97508
+ if (!workflowExecutionOwnsDetach) detachExternalAbort();
97509
+ }
97347
97510
  }
97348
97511
  async #generateDurable(messages, options) {
97349
97512
  options = await this.#resolveDurableRunOptions(applyReservedMemoryContextKeys(options));
@@ -97748,7 +97911,7 @@ var Agent = class Agent extends MastraBase {
97748
97911
  const resumeTotalMs = resolvedOptions.modelSettings?.timeout?.totalMs;
97749
97912
  if (resumeTotalMs !== void 0) entry.timeoutTotalMs = resumeTotalMs;
97750
97913
  if (persistedInput) this.#runInputs.set(executionFence, persistedInput);
97751
- this.installAbortWithTotalTimeout(entry, abortController, executionFence);
97914
+ this.installAbortWithTotalTimeout(entry, abortController, executionFence, detachExternalAbort);
97752
97915
  const globalEntryForAbort = getRunRegistryEntry(runId, this.#mastra);
97753
97916
  if (globalEntryForAbort) {
97754
97917
  globalEntryForAbort.abortController = abortController;