@mastra/inngest 1.11.2-alpha.8 → 1.11.2

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.
@@ -65,11 +65,13 @@ function serializeRequestContext(requestContext) {
65
65
  }
66
66
  /**
67
67
  * Resume request-context rule: values persisted in the snapshot are the base,
68
- * and anything the caller supplies on this resume call overrides them.
68
+ * and anything the caller supplies on this resume call overrides them. The
69
+ * snapshot's bearer token and authenticated user, roles and permissions are
70
+ * dropped first, so they only ever come from the request doing the resuming.
69
71
  */
70
72
  function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
71
73
  return {
72
- ...snapshotRequestContext ?? {},
74
+ ...(0, _mastra_core_request_context.withoutLiveRequestKeys)(snapshotRequestContext),
73
75
  ...serializeRequestContext(requestContext)
74
76
  };
75
77
  }
@@ -162,6 +164,9 @@ function agentLoopTermination(...args) {
162
164
  function endRunSpansWithError(...args) {
163
165
  if (_mastra_core_features.coreFeatures.has("execution-outcomes")) _mastra_core_agent_durable.endRunSpansWithError?.(...args);
164
166
  }
167
+ function executionFailureTermination(...args) {
168
+ return _mastra_core_features.coreFeatures.has("execution-outcomes") ? _mastra_core_observability.executionFailureTermination?.(...args) ?? {} : {};
169
+ }
165
170
  /** Keep completed-request usage when a failed request makes the total incomplete. */
166
171
  function generationUsage(usage, steps) {
167
172
  const usageIncomplete = _mastra_core_features.coreFeatures.has("execution-outcomes") && _mastra_core_observability.isUsageIncomplete?.(usage);
@@ -2772,6 +2777,11 @@ function createAgenticLoopWorkflow(options) {
2772
2777
  if (nextCursor) state.responseMessagesCursor = nextCursor;
2773
2778
  }
2774
2779
  };
2780
+ if (state.deadlineTimeout || state.runAborted) {
2781
+ if (tracingRegistry) tracingRegistry.tracingStopCause = "model_finished";
2782
+ await emitStepFinish(false);
2783
+ return false;
2784
+ }
2775
2785
  const recordStopCause = (cause) => {
2776
2786
  state.tracingStopCause = cause;
2777
2787
  if (tracingRegistry) tracingRegistry.tracingStopCause = cause;
@@ -2817,9 +2827,18 @@ function createAgenticLoopWorkflow(options) {
2817
2827
  }).map(async (params) => {
2818
2828
  const { inputData, mastra, requestContext, tracingContext } = params;
2819
2829
  const state = inputData;
2820
- (0, _mastra_core_agent_durable.getRunRegistryEntry)(state.runId, mastra);
2830
+ const tracingRegistry = (0, _mastra_core_agent_durable.getRunRegistryEntry)(state.runId, mastra);
2821
2831
  const initData = params.getInitData();
2822
2832
  const pubsub = params[_mastra_core_workflows__constants.PUBSUB_SYMBOL];
2833
+ const resolveDeadlineError = () => {
2834
+ const abortReason = tracingRegistry?.abortSignal?.aborted ? tracingRegistry.abortSignal.reason : void 0;
2835
+ const carriedDeadline = (0, _mastra_core_agent_durable.readRunDeadline)(requestContext);
2836
+ return (0, _mastra_core_loop.isMastraTimeoutError)(abortReason) && abortReason.timeoutType === "total" ? abortReason : state.deadlineTimeout ? new _mastra_core_loop.MastraTimeoutError(state.deadlineTimeout) : !state.runAborted && carriedDeadline && Date.now() >= carriedDeadline.at ? new _mastra_core_loop.MastraTimeoutError({
2837
+ timeoutType: "total",
2838
+ timeoutMs: carriedDeadline.timeoutMs
2839
+ }) : void 0;
2840
+ };
2841
+ const sideEffectsDeadlineError = resolveDeadlineError();
2823
2842
  const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];
2824
2843
  let finalText = lastStep?.text;
2825
2844
  const finishResult = await (0, _mastra_core_agent_durable.runDurableFinishSideEffects)({
@@ -2834,7 +2853,7 @@ function createAgenticLoopWorkflow(options) {
2834
2853
  outputResult: {
2835
2854
  text: finalText ?? "",
2836
2855
  usage: state.accumulatedUsage,
2837
- finishReason: state.lastStepResult?.reason ?? "unknown",
2856
+ finishReason: sideEffectsDeadlineError ? "error" : state.runAborted ? "abort" : state.lastStepResult?.reason ?? "unknown",
2838
2857
  steps: state.accumulatedSteps
2839
2858
  }
2840
2859
  });
@@ -2866,6 +2885,7 @@ function createAgenticLoopWorkflow(options) {
2866
2885
  transient: true
2867
2886
  });
2868
2887
  }
2888
+ const deadlineError = sideEffectsDeadlineError ?? resolveDeadlineError();
2869
2889
  const finalOutput = {
2870
2890
  messageListState: finishResult.messageListState,
2871
2891
  messageId: state.messageId,
@@ -2873,6 +2893,14 @@ function createAgenticLoopWorkflow(options) {
2873
2893
  ...state.lastStepResult ?? { warnings: [] },
2874
2894
  reason: "tripwire",
2875
2895
  isContinued: false
2896
+ } : deadlineError ? {
2897
+ ...state.lastStepResult ?? { warnings: [] },
2898
+ reason: "error",
2899
+ isContinued: false
2900
+ } : state.runAborted ? {
2901
+ ...state.lastStepResult ?? { warnings: [] },
2902
+ reason: "abort",
2903
+ isContinued: false
2876
2904
  } : state.lastStepResult || {
2877
2905
  reason: "stop",
2878
2906
  warnings: [],
@@ -2887,6 +2915,7 @@ function createAgenticLoopWorkflow(options) {
2887
2915
  };
2888
2916
  const observability = mastra?.observability?.getSelectedInstance({});
2889
2917
  const registry = (0, _mastra_core_agent_durable.getRunRegistryEntry)(state.runId, mastra);
2918
+ const deadlineTermination = deadlineError && !tripwire ? executionFailureTermination(deadlineError) : void 0;
2890
2919
  const completionClock = registry?.resumeModelSpanData ? registry.resumeCompletionStartTime : state.completionStartTime;
2891
2920
  const timeToFirstTokenMs = registry?.resumeModelSpanData ? registry.resumeTimeToFirstTokenMs : state.timeToFirstTokenMs;
2892
2921
  const clocks = {
@@ -2897,7 +2926,7 @@ function createAgenticLoopWorkflow(options) {
2897
2926
  const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
2898
2927
  const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
2899
2928
  if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
2900
- const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
2929
+ const termination = deadlineTermination ? deadlineTermination : ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
2901
2930
  stopCause,
2902
2931
  delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
2903
2932
  finishReason,
@@ -2933,7 +2962,8 @@ function createAgenticLoopWorkflow(options) {
2933
2962
  output: { text: finalText },
2934
2963
  ...Object.keys(clocks).length ? { attributes: clocks } : {}
2935
2964
  });
2936
- if (pubsub) await (0, _mastra_core_agent_durable.emitFinishEvent)(pubsub, state.runId, {
2965
+ if (pubsub && deadlineError) await (0, _mastra_core_agent_durable.emitErrorEvent)(pubsub, state.runId, deadlineError);
2966
+ else if (pubsub) await (0, _mastra_core_agent_durable.emitFinishEvent)(pubsub, state.runId, {
2937
2967
  output: finalOutput.output,
2938
2968
  stepResult: finalOutput.stepResult,
2939
2969
  ...textRewritten && { textRewritten }
@@ -3242,9 +3272,12 @@ function createInngestAgent(options) {
3242
3272
  * one execution session (stream or resume) and compose it into the registry
3243
3273
  * entry's `abortSignal`, which co-located durable steps read. At the
3244
3274
  * deadline the run is reported failed: the stream gets one
3245
- * `MastraTimeoutError` and the snapshot rows are deleted. Mirrors core
3275
+ * `MastraTimeoutError` and the snapshot rows are deleted. A step on another
3276
+ * worker stops at the same deadline through the timer it arms from the
3277
+ * carried deadline. Mirrors core
3246
3278
  * `DurableAgent.#installAbortWithTotalTimeout` + `settleExecution`.
3247
- * Returns the timer teardown; a no-op when no budget is configured.
3279
+ * Returns the timer teardown (a no-op when no budget is configured) and the
3280
+ * segment's absolute deadline, which the segment's event carries to workers.
3248
3281
  */
3249
3282
  function armTotalTimeout(entry, abortController, runId, timeoutMs) {
3250
3283
  const totalTimeout = (0, _mastra_core_loop.createTimeoutAbortSignal)({
@@ -3254,12 +3287,31 @@ function createInngestAgent(options) {
3254
3287
  detachParentOnCleanup: false
3255
3288
  });
3256
3289
  entry.abortSignal = totalTimeout.signal;
3290
+ const deadline = timeoutMs !== void 0 && timeoutMs > 0 ? {
3291
+ at: Date.now() + timeoutMs,
3292
+ timeoutMs
3293
+ } : void 0;
3257
3294
  totalTimeout.timeoutPromise?.catch(async (error) => {
3258
- if (!(0, _mastra_core_loop.isMastraTimeoutError)(error) || totalTimeout.signal?.reason !== error) return;
3295
+ if (!(0, _mastra_core_loop.isMastraTimeoutError)(error) || !(0, _mastra_core_loop.isMastraTimeoutError)(totalTimeout.signal?.reason)) return;
3259
3296
  await emitError(runId, error);
3260
3297
  await deleteRunSnapshots(runId);
3261
3298
  });
3262
- return totalTimeout.cleanup;
3299
+ return {
3300
+ clear: () => totalTimeout.cleanup(),
3301
+ deadline
3302
+ };
3303
+ }
3304
+ /**
3305
+ * The request context a segment's event carries: the caller's, plus this segment's absolute
3306
+ * deadline (or none), so a worker that subscribes after the deadline's abort request went out
3307
+ * still stops at it.
3308
+ */
3309
+ function withSegmentDeadline(requestContext, deadline) {
3310
+ const { [_mastra_core_agent_durable.RUN_DEADLINE_KEY]: _stale, ...rest } = requestContext;
3311
+ return deadline ? {
3312
+ ...rest,
3313
+ [_mastra_core_agent_durable.RUN_DEADLINE_KEY]: deadline
3314
+ } : rest;
3263
3315
  }
3264
3316
  async function deleteRunSnapshots(runId) {
3265
3317
  try {
@@ -3450,7 +3502,7 @@ function createInngestAgent(options) {
3450
3502
  /**
3451
3503
  * Trigger the workflow via Inngest event
3452
3504
  */
3453
- async function triggerWorkflow(runId, workflowInput, tracingOptions, actor) {
3505
+ async function triggerWorkflow(runId, workflowInput, tracingOptions, actor, deadline) {
3454
3506
  const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
3455
3507
  await inngest$1.send({
3456
3508
  name: eventName,
@@ -3458,7 +3510,7 @@ function createInngestAgent(options) {
3458
3510
  inputData: workflowInput,
3459
3511
  runId,
3460
3512
  resourceId: workflowInput.state?.resourceId,
3461
- requestContext: workflowInput.requestContextEntries ?? {},
3513
+ requestContext: withSegmentDeadline(workflowInput.requestContextEntries ?? {}, deadline),
3462
3514
  tracingOptions,
3463
3515
  actor
3464
3516
  })
@@ -3582,7 +3634,7 @@ function createInngestAgent(options) {
3582
3634
  workflowInput.agentName = agentName;
3583
3635
  const { controller: abortController, detach: stopForwardingAbort } = (0, _mastra_core_agent_durable.createRunAbortController)(streamOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
3584
3636
  registryEntry.abortController = abortController;
3585
- const clearTotalTimeout = armTotalTimeout(registryEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs);
3637
+ const { clear: clearTotalTimeout, deadline: segmentDeadline } = armTotalTimeout(registryEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs);
3586
3638
  registryEntry.messageList = preparation.messageList;
3587
3639
  _mastra_core_agent_durable.globalRunRegistry.set(runId, registryEntry);
3588
3640
  workflowInput.stepIndex = 0;
@@ -3673,7 +3725,7 @@ function createInngestAgent(options) {
3673
3725
  return;
3674
3726
  }
3675
3727
  try {
3676
- await triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor);
3728
+ await triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor, segmentDeadline);
3677
3729
  } catch (error) {
3678
3730
  if (persistedRunning) await deleteRunSnapshots(runId);
3679
3731
  throw error;
@@ -3788,7 +3840,7 @@ function createInngestAgent(options) {
3788
3840
  };
3789
3841
  })();
3790
3842
  resumableSnapshot.catch(() => {});
3791
- const savedRequestContext = existingRegistryEntry?.requestContext?.entries() ?? Object.entries((await resumableSnapshot.catch(() => void 0))?.snapshot?.requestContext ?? {});
3843
+ const savedRequestContext = Object.entries((0, _mastra_core_request_context.withoutLiveRequestKeys)(existingRegistryEntry?.requestContext ? Object.fromEntries(existingRegistryEntry.requestContext.entries()) : (await resumableSnapshot.catch(() => void 0))?.snapshot?.requestContext));
3792
3844
  const callbackOptions = await withDefaultOptions(agent, {
3793
3845
  ...resumeOptions,
3794
3846
  requestContext: new _mastra_core_request_context.RequestContext([...savedRequestContext, ...resumeOptions?.requestContext?.entries() ?? []])
@@ -3842,7 +3894,7 @@ function createInngestAgent(options) {
3842
3894
  }
3843
3895
  existingEntry.abortController = abortController;
3844
3896
  existingEntry.requestContext = callbackOptions.requestContext;
3845
- const clearTotalTimeout = armTotalTimeout(existingEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs ?? existingRegistryEntry?.timeoutTotalMs ?? (await resumableSnapshot.catch(() => void 0))?.snapshot?.context?.input?.options?.modelSettings?.timeout?.totalMs);
3897
+ const { clear: clearTotalTimeout, deadline: segmentDeadline } = armTotalTimeout(existingEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs ?? existingRegistryEntry?.timeoutTotalMs ?? (await resumableSnapshot.catch(() => void 0))?.snapshot?.context?.input?.options?.modelSettings?.timeout?.totalMs);
3846
3898
  if (existingRegistryEntry && !existingRegistryEntry.isPlaceholder && (resumeOptions?.requestContext || resumeOptions?.hooks)) try {
3847
3899
  const snapshotMemoryInfo = (await resumableSnapshot.catch(() => void 0))?.snapshot?.context?.input?.messageListState?.memoryInfo;
3848
3900
  const resumeRequestContext = callbackOptions.requestContext;
@@ -3976,7 +4028,7 @@ function createInngestAgent(options) {
3976
4028
  inputData: resumeData,
3977
4029
  runId,
3978
4030
  resourceId: resumeOptions?.resourceId,
3979
- requestContext,
4031
+ requestContext: withSegmentDeadline(requestContext, segmentDeadline),
3980
4032
  tracingOptions,
3981
4033
  actor: resumeOptions?.actor,
3982
4034
  resume: {
@@ -5193,4 +5245,4 @@ Object.defineProperty(exports, "serve", {
5193
5245
  }
5194
5246
  });
5195
5247
 
5196
- //# sourceMappingURL=src-yF1Hyw1J.cjs.map
5248
+ //# sourceMappingURL=src-CSFwfJvk.cjs.map