@mastra/inngest 1.11.1 → 1.11.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,22 +29,74 @@ let _mastra_core_tools = require("@mastra/core/tools");
29
29
  let _mastra_core_workflows = require("@mastra/core/workflows");
30
30
  _mastra_core_workflows = __toESM(_mastra_core_workflows, 1);
31
31
  let _mastra_core_agent_durable = require("@mastra/core/agent/durable");
32
+ _mastra_core_agent_durable = __toESM(_mastra_core_agent_durable, 1);
32
33
  let _mastra_core_di = require("@mastra/core/di");
33
34
  let _mastra_core_events = require("@mastra/core/events");
34
35
  let inngest = require("inngest");
36
+ let _mastra_core_request_context = require("@mastra/core/request-context");
35
37
  let async_hooks = require("async_hooks");
36
38
  let _mastra_core_features = require("@mastra/core/features");
37
39
  let inngest_realtime = require("inngest/realtime");
38
40
  let stream_web = require("stream/web");
39
41
  let _mastra_core_stream = require("@mastra/core/stream");
40
- let _mastra_core_request_context = require("@mastra/core/request-context");
41
42
  let inngest_hono = require("inngest/hono");
42
43
  let _mastra_core_cache = require("@mastra/core/cache");
43
44
  let _mastra_core_loop = require("@mastra/core/loop");
45
+ let _mastra_core_storage = require("@mastra/core/storage");
44
46
  let _mastra_core_utils = require("@mastra/core/utils");
45
47
  let _mastra_core_agent_message_list = require("@mastra/core/agent/message-list");
46
48
  let _mastra_core_workflows__constants = require("@mastra/core/workflows/_constants");
47
49
  let zod = require("zod");
50
+ // src/durable-event-payload.ts
51
+ /**
52
+ * Lease on an InngestAgent resume claim until its event starts. A claim whose event never started
53
+ * (its resume died before sending, or the send failed) lapses, and a later resume takes it over.
54
+ */
55
+ const RESUME_CLAIM_DISPATCH_LEASE_MS = 6e4;
56
+ /**
57
+ * Flatten a `RequestContext` into the plain JSON object the event carries.
58
+ * Absent context serializes to `{}`, never `undefined`.
59
+ */
60
+ function serializeRequestContext(requestContext) {
61
+ const obj = requestContext ? requestContext.toJSON() : {};
62
+ delete obj[_mastra_core_request_context.MASTRA_AUTH_TOKEN_KEY];
63
+ return obj;
64
+ }
65
+ /**
66
+ * Resume request-context rule: values persisted in the snapshot are the base,
67
+ * and anything the caller supplies on this resume call overrides them.
68
+ */
69
+ function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
70
+ return {
71
+ ...snapshotRequestContext ?? {},
72
+ ...serializeRequestContext(requestContext)
73
+ };
74
+ }
75
+ function buildDurableTriggerEventData(args) {
76
+ const { requestContext, ...rest } = args;
77
+ return {
78
+ ...rest,
79
+ requestContext: toRequestContextEntries(requestContext)
80
+ };
81
+ }
82
+ function buildDurableResumeEventData(args) {
83
+ const { requestContext, ...rest } = args;
84
+ return {
85
+ ...rest,
86
+ requestContext: toRequestContextEntries(requestContext)
87
+ };
88
+ }
89
+ function buildDurableTimeTravelEventData(args) {
90
+ const { requestContext, ...rest } = args;
91
+ return {
92
+ ...rest,
93
+ requestContext: toRequestContextEntries(requestContext)
94
+ };
95
+ }
96
+ function toRequestContextEntries(requestContext) {
97
+ if (!requestContext) return {};
98
+ return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
99
+ }
48
100
  // src/nested-workflow-output.ts
49
101
  const NESTED_WORKFLOW_OUTPUT_MODE = {
50
102
  DEFAULT: "default",
@@ -105,6 +157,10 @@ function workflowTermination(...args) {
105
157
  function agentLoopTermination(...args) {
106
158
  return _mastra_core_features.coreFeatures.has("execution-outcomes") ? _mastra_core_observability.agentLoopTermination?.(...args) ?? {} : {};
107
159
  }
160
+ /** End the caller's live root spans with `error`; a no-op on cores without the helper. */
161
+ function endRunSpansWithError(...args) {
162
+ if (_mastra_core_features.coreFeatures.has("execution-outcomes")) _mastra_core_agent_durable.endRunSpansWithError?.(...args);
163
+ }
108
164
  /** Keep completed-request usage when a failed request makes the total incomplete. */
109
165
  function generationUsage(usage, steps) {
110
166
  const usageIncomplete = _mastra_core_features.coreFeatures.has("execution-outcomes") && _mastra_core_observability.isUsageIncomplete?.(usage);
@@ -464,7 +520,9 @@ var InngestExecutionEngine = class extends _mastra_core_workflows.DefaultExecuti
464
520
  runId,
465
521
  steps: nestedResumeSteps,
466
522
  resumePayload: resume.resumePayload,
467
- resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0
523
+ resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0,
524
+ label: resume.label,
525
+ forEachIndex: resume.label ? snapshot?.resumeLabels?.[resume.label]?.foreachIndex : void 0
468
526
  } },
469
527
  outputOptions: {
470
528
  includeState: true,
@@ -582,6 +640,26 @@ var InngestExecutionEngine = class extends _mastra_core_workflows.DefaultExecuti
582
640
  const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
583
641
  return stepResult?.status === "suspended";
584
642
  });
643
+ const agentInput = stepResults.input;
644
+ const resumedCallFinished = isResume && !!resume?.label && !result.resumeLabels?.[resume.label];
645
+ const parked = (suspendedSteps[0]?.[1])?.suspendPayload;
646
+ const approval = parked?.requireToolApproval;
647
+ const parkedToolCallId = parked?.toolCallId ?? approval?.toolCallId;
648
+ let parkedBefore = false;
649
+ if (resumedCallFinished && agentInput?.__workflowKind === "durable-agent" && parkedToolCallId) parkedBefore = !!(await (await this.mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
650
+ workflowName: executionContext.workflowId,
651
+ runId: executionContext.runId
652
+ }))?.resumeLabels?.[parkedToolCallId];
653
+ if (parkedBefore && agentInput?.runId) {
654
+ const meta = parked?.__workflow_meta;
655
+ await (0, _mastra_core_agent_durable.emitSuspendedEvent)(pubsub, agentInput.runId, {
656
+ toolCallId: parkedToolCallId,
657
+ toolName: approval?.toolName ?? parked?.toolName,
658
+ args: approval?.args ?? parked?.args ?? meta?.foreachOutput?.[meta.foreachIndex]?.payload?.args,
659
+ suspendPayload: parked?.toolCallSuspended,
660
+ type: parked?.type === "approval" ? "approval" : "suspension"
661
+ });
662
+ }
585
663
  for (const [stepName, stepResult] of suspendedSteps) {
586
664
  const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
587
665
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
@@ -1073,51 +1151,6 @@ var InngestPubSub = class extends _mastra_core_events.PubSub {
1073
1151
  this.subscriptions.clear();
1074
1152
  }
1075
1153
  };
1076
- // src/durable-event-payload.ts
1077
- /**
1078
- * Flatten a `RequestContext` into the plain JSON object the event carries.
1079
- * Absent context serializes to `{}`, never `undefined`.
1080
- */
1081
- function serializeRequestContext(requestContext) {
1082
- const obj = requestContext ? requestContext.toJSON() : {};
1083
- delete obj[_mastra_core_request_context.MASTRA_AUTH_TOKEN_KEY];
1084
- return obj;
1085
- }
1086
- /**
1087
- * Resume request-context rule: values persisted in the snapshot are the base,
1088
- * and anything the caller supplies on this resume call overrides them.
1089
- */
1090
- function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
1091
- return {
1092
- ...snapshotRequestContext ?? {},
1093
- ...serializeRequestContext(requestContext)
1094
- };
1095
- }
1096
- function buildDurableTriggerEventData(args) {
1097
- const { requestContext, ...rest } = args;
1098
- return {
1099
- ...rest,
1100
- requestContext: toRequestContextEntries(requestContext)
1101
- };
1102
- }
1103
- function buildDurableResumeEventData(args) {
1104
- const { requestContext, ...rest } = args;
1105
- return {
1106
- ...rest,
1107
- requestContext: toRequestContextEntries(requestContext)
1108
- };
1109
- }
1110
- function buildDurableTimeTravelEventData(args) {
1111
- const { requestContext, ...rest } = args;
1112
- return {
1113
- ...rest,
1114
- requestContext: toRequestContextEntries(requestContext)
1115
- };
1116
- }
1117
- function toRequestContextEntries(requestContext) {
1118
- if (!requestContext) return {};
1119
- return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
1120
- }
1121
1154
  // src/run.ts
1122
1155
  var InngestRun = class extends _mastra_core_workflows.Run {
1123
1156
  inngest;
@@ -1838,6 +1871,8 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
1838
1871
  */
1839
1872
  #pubsubFactory;
1840
1873
  #emitWorkflowEvents = true;
1874
+ /** Functions a host (e.g. the durable agent loop) serves alongside this workflow's own. */
1875
+ #hostFunctions = [];
1841
1876
  constructor(params, inngest) {
1842
1877
  const { concurrency, rateLimit, throttle, debounce, priority, retries, cron, inputData, initialState, ...workflowParams } = params;
1843
1878
  super(workflowParams);
@@ -1902,6 +1937,9 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
1902
1937
  this.__setEmitWorkflowEvents(this.#emitWorkflowEvents);
1903
1938
  return committed;
1904
1939
  }
1940
+ __addHostFunctions(functions) {
1941
+ this.#hostFunctions.push(...functions);
1942
+ }
1905
1943
  __setEmitWorkflowEvents(enabled) {
1906
1944
  this.#emitWorkflowEvents = enabled;
1907
1945
  const updateNested = (step) => {
@@ -2033,6 +2071,18 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
2033
2071
  });
2034
2072
  this.logger.warn?.(`Workflow "${this.id}" was triggered without a runId, so run "${runId}" cannot be cancelled by id. Send \`data.runId\` on the trigger event (or start the run with createRun()) to make it cancellable.`);
2035
2073
  }
2074
+ const resumeClaim = resume?.claim;
2075
+ if (resumeClaim) {
2076
+ if (!await step.run(`workflow.${this.id}.resume-claim`, async () => {
2077
+ return (await (await this.#mastra?.getStorage()?.getStore("workflows"))?.renewRunOwnership({
2078
+ ...resumeClaim,
2079
+ leaseMs: 864e5
2080
+ }))?.renewed ?? true;
2081
+ })) return {
2082
+ result: void 0,
2083
+ runId
2084
+ };
2085
+ }
2036
2086
  if (resume && (initialState === void 0 || resume.stepResults === void 0)) {
2037
2087
  const snapshot = await (await this.#mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
2038
2088
  workflowName: this.id,
@@ -2211,6 +2261,7 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
2211
2261
  });
2212
2262
  }
2213
2263
  }
2264
+ if (resumeClaim) await (await mastra?.getStorage()?.getStore("workflows"))?.releaseRunOwnership(resumeClaim);
2214
2265
  try {
2215
2266
  await pubsub.publish(`workflow.events.v2.${runId}`, {
2216
2267
  type: "watch",
@@ -2266,7 +2317,8 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
2266
2317
  return [
2267
2318
  this.getFunction(),
2268
2319
  ...this.cronConfig?.cron ? [this.createCronFunction()] : [],
2269
- ...this.getNestedFunctions(this.executionGraph.steps)
2320
+ ...this.getNestedFunctions(this.executionGraph.steps),
2321
+ ...this.#hostFunctions
2270
2322
  ];
2271
2323
  }
2272
2324
  };
@@ -2396,6 +2448,7 @@ const durableAgenticInputSchema = zod.z.object({
2396
2448
  * Iteration state schema - extends base with observability fields.
2397
2449
  */
2398
2450
  const iterationStateSchema = _mastra_core_agent_durable.baseIterationStateSchema.extend({
2451
+ accumulatedSteps: zod.z.array(zod.z.any()),
2399
2452
  modelList: zod.z.array(_mastra_core_agent_durable.modelListEntrySchema).optional(),
2400
2453
  agentSpanData: zod.z.any().optional(),
2401
2454
  modelSpanData: zod.z.any().optional(),
@@ -2425,7 +2478,77 @@ const InngestDurableStepIds = {
2425
2478
  AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${_mastra_core_agent_durable.DurableStepIds.AGENTIC_EXECUTION}`,
2426
2479
  AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${_mastra_core_agent_durable.DurableStepIds.AGENTIC_LOOP}`
2427
2480
  };
2481
+ /** Run ownership key of the claim an InngestAgent resume holds on the loop run. */
2482
+ const resumeClaimKey = (runId) => `${InngestDurableStepIds.AGENTIC_LOOP}:resume-claim:${runId}`;
2483
+ /**
2484
+ * The store a resume claim lives in. A claim needs an atomic status change and a lease, so a
2485
+ * claim whose resume died can be taken over; without both, resumes are not claimed at all.
2486
+ */
2487
+ async function resumeClaimStore(mastra) {
2488
+ const store = await mastra?.getStorage()?.getStore("workflows");
2489
+ if (!store?.supportsConcurrentUpdates?.()) return void 0;
2490
+ return await Promise.resolve().then(() => store.supportsRunFencing()).catch(() => false) ? store : void 0;
2491
+ }
2492
+ const setLoopStatus = (store, runId, status, expectedStatus) => store.updateWorkflowState({
2493
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP,
2494
+ runId,
2495
+ opts: {
2496
+ status,
2497
+ expectedStatus
2498
+ }
2499
+ });
2500
+ /**
2501
+ * Ends a resumed segment Inngest failed or cancelled, which never reaches the finalize step that
2502
+ * would: marks the run failed or canceled, ends its stream and releases its claim. The run is not
2503
+ * parked again, since a nested segment Inngest did not cancel can still be running its tools.
2504
+ */
2505
+ function createResumeClaimReleaseFunction(inngest, workflow) {
2506
+ const loopEvent = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
2507
+ return inngest.createFunction({
2508
+ id: `${loopEvent}.resume-claim-release`,
2509
+ triggers: [{
2510
+ event: "inngest/function.failed",
2511
+ if: `event.data.event.name == '${loopEvent}'`
2512
+ }, {
2513
+ event: "inngest/function.cancelled",
2514
+ if: `event.data.event.name == '${loopEvent}'`
2515
+ }]
2516
+ }, async ({ event }) => {
2517
+ const original = event.data.event?.data;
2518
+ const claim = original?.resume?.claim;
2519
+ const mastra = workflow.mastra;
2520
+ const store = await resumeClaimStore(mastra);
2521
+ if (!original?.runId || !claim || !store) return;
2522
+ if (!(await store.renewRunOwnership({
2523
+ ...claim,
2524
+ leaseMs: 6e4
2525
+ })).renewed) return;
2526
+ const cancelled = event.name === "inngest/function.cancelled";
2527
+ await setLoopStatus(store, original.runId, cancelled ? "canceled" : "failed", "running");
2528
+ const defaultPubsub = new InngestPubSub(inngest, workflow.id, mastra?.getLogger?.());
2529
+ const pubsub = workflow.__getPubsubFactory()?.(defaultPubsub) ?? defaultPubsub;
2530
+ try {
2531
+ if (cancelled) await (0, _mastra_core_agent_durable.emitAbortEvent)(pubsub, original.runId, {
2532
+ steps: [],
2533
+ text: ""
2534
+ });
2535
+ else {
2536
+ const message = event.data.error?.message;
2537
+ await (0, _mastra_core_agent_durable.emitErrorEvent)(pubsub, original.runId, new Error(message ?? "The resumed agent run failed."));
2538
+ }
2539
+ } catch (error) {
2540
+ mastra?.getLogger?.()?.warn?.(`[InngestAgent] run ${original.runId} failed to publish its end`, error);
2541
+ }
2542
+ await store.releaseRunOwnership(claim);
2543
+ });
2544
+ }
2428
2545
  function createInngestDurableAgenticWorkflow(options) {
2546
+ const workflow = createAgenticLoopWorkflow(options);
2547
+ const inngestWorkflow = workflow;
2548
+ inngestWorkflow.__addHostFunctions([createResumeClaimReleaseFunction(options.inngest, inngestWorkflow)]);
2549
+ return workflow;
2550
+ }
2551
+ function createAgenticLoopWorkflow(options) {
2429
2552
  const { inngest, maxSteps = _mastra_core_agent_durable.DurableAgentDefaults.MAX_STEPS, retries } = options;
2430
2553
  const { createWorkflow } = init(inngest);
2431
2554
  const llmExecutionStep = (0, _mastra_core_agent_durable.createDurableLLMExecutionStep)();
@@ -2567,8 +2690,12 @@ function createInngestDurableAgenticWorkflow(options) {
2567
2690
  });
2568
2691
  }
2569
2692
  };
2693
+ const recordStopCause = (cause) => {
2694
+ state.tracingStopCause = cause;
2695
+ if (tracingRegistry) tracingRegistry.tracingStopCause = cause;
2696
+ };
2570
2697
  if (state.delegationBailed) {
2571
- if (tracingRegistry) tracingRegistry.tracingStopCause = state.lastStepResult?.isContinued ? "delegation" : "model_finished";
2698
+ recordStopCause(state.lastStepResult?.isContinued ? "delegation" : "model_finished");
2572
2699
  await emitStepFinish(false);
2573
2700
  return false;
2574
2701
  }
@@ -2576,7 +2703,7 @@ function createInngestDurableAgenticWorkflow(options) {
2576
2703
  const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
2577
2704
  const underMaxSteps = state.iterationCount < effectiveMaxSteps;
2578
2705
  if (!shouldContinue || !underMaxSteps) {
2579
- if (tracingRegistry) tracingRegistry.tracingStopCause = shouldContinue ? "max_steps" : "model_finished";
2706
+ recordStopCause(shouldContinue ? "max_steps" : "model_finished");
2580
2707
  await emitStepFinish(false);
2581
2708
  return false;
2582
2709
  }
@@ -2602,7 +2729,7 @@ function createInngestDurableAgenticWorkflow(options) {
2602
2729
  }
2603
2730
  }))).some(Boolean);
2604
2731
  });
2605
- if (stopped && tracingRegistry) tracingRegistry.tracingStopCause = "stop_condition";
2732
+ if (stopped) recordStopCause("stop_condition");
2606
2733
  await emitStepFinish(!stopped);
2607
2734
  return !stopped;
2608
2735
  }).map(async (params) => {
@@ -2621,6 +2748,7 @@ function createInngestDurableAgenticWorkflow(options) {
2621
2748
  requestContext,
2622
2749
  tracingContext,
2623
2750
  logger: mastra?.getLogger?.(),
2751
+ messageId: state.messageId,
2624
2752
  outputResult: {
2625
2753
  text: finalText ?? "",
2626
2754
  usage: state.accumulatedUsage,
@@ -2633,16 +2761,17 @@ function createInngestDurableAgenticWorkflow(options) {
2633
2761
  finalText = finishResult.outputText;
2634
2762
  }
2635
2763
  const tripwire = finishResult.tripwire;
2764
+ if (pubsub && !tripwire) for (const chunk of finishResult.structuredOutputChunks ?? []) await (0, _mastra_core_agent_durable.emitChunkEvent)(pubsub, state.runId, {
2765
+ ...chunk,
2766
+ runId: state.runId
2767
+ });
2768
+ if (pubsub) for (const chunk of finishResult.outputResultChunks ?? []) await (0, _mastra_core_agent_durable.emitChunkEvent)(pubsub, state.runId, chunk, true);
2636
2769
  if (tripwire && pubsub) await (0, _mastra_core_agent_durable.emitChunkEvent)(pubsub, state.runId, {
2637
2770
  type: "tripwire",
2638
2771
  runId: state.runId,
2639
2772
  from: _mastra_core_stream.ChunkFrom.AGENT,
2640
2773
  payload: tripwire
2641
2774
  });
2642
- if (pubsub && !tripwire) for (const chunk of finishResult.structuredOutputChunks ?? []) await (0, _mastra_core_agent_durable.emitChunkEvent)(pubsub, state.runId, {
2643
- ...chunk,
2644
- runId: state.runId
2645
- });
2646
2775
  if (pubsub && !tripwire && finishResult.titleForStream) {
2647
2776
  const title = await finishResult.titleForStream;
2648
2777
  if (title && initData.state?.threadId) await (0, _mastra_core_agent_durable.emitChunkEvent)(pubsub, state.runId, {
@@ -2681,6 +2810,17 @@ function createInngestDurableAgenticWorkflow(options) {
2681
2810
  ...completionClock ? { completionStartTime: new Date(completionClock) } : {},
2682
2811
  ...timeToFirstTokenMs !== void 0 ? { timeToFirstTokenMs } : {}
2683
2812
  };
2813
+ const finishReason = finalOutput.stepResult?.reason;
2814
+ const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
2815
+ const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
2816
+ if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
2817
+ const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
2818
+ stopCause,
2819
+ delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
2820
+ finishReason,
2821
+ tripwire: tripwire ?? state.lastStepResult?.tripwire,
2822
+ maxSteps: state.options?.maxSteps ?? maxSteps
2823
+ });
2684
2824
  if (state.modelSpanData) {
2685
2825
  const modelSpan = registry?.resumeModelSpan ?? registry?.modelSpan ?? observability?.rebuildSpan(state.modelSpanData);
2686
2826
  const toolCalls = state.accumulatedSteps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
@@ -2690,13 +2830,7 @@ function createInngestDurableAgenticWorkflow(options) {
2690
2830
  })));
2691
2831
  const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps);
2692
2832
  modelSpan?.createTracker()?.endGeneration({
2693
- ...["tripwire", "error"].includes(finalOutput.stepResult?.reason ?? "") && registry?.tracingTermination ? registry.tracingTermination : agentLoopTermination({
2694
- stopCause: registry?.tracingStopCause,
2695
- delegationFailure: registry?.tracingDelegationFailure,
2696
- finishReason: finalOutput.stepResult?.reason,
2697
- tripwire,
2698
- maxSteps: state.options?.maxSteps ?? maxSteps
2699
- }),
2833
+ ...termination,
2700
2834
  output: {
2701
2835
  text: finalText,
2702
2836
  ...toolCalls.length ? { toolCalls } : {}
@@ -2712,13 +2846,7 @@ function createInngestDurableAgenticWorkflow(options) {
2712
2846
  });
2713
2847
  }
2714
2848
  if (state.agentSpanData) (registry?.resumeAgentSpan ?? registry?.agentSpan ?? observability?.rebuildSpan(state.agentSpanData))?.end({
2715
- ...["tripwire", "error"].includes(finalOutput.stepResult?.reason ?? "") && registry?.tracingTermination ? registry.tracingTermination : agentLoopTermination({
2716
- stopCause: registry?.tracingStopCause,
2717
- delegationFailure: registry?.tracingDelegationFailure,
2718
- finishReason: finalOutput.stepResult?.reason,
2719
- tripwire,
2720
- maxSteps: state.options?.maxSteps ?? maxSteps
2721
- }),
2849
+ ...termination,
2722
2850
  output: { text: finalText },
2723
2851
  ...Object.keys(clocks).length ? { attributes: clocks } : {}
2724
2852
  });
@@ -2833,6 +2961,43 @@ var InngestAgentPubSubRouter = class extends _mastra_core_events.PubSub {
2833
2961
  const STREAM_CLEANUP = Symbol("mastra.durable.inngest.streamCleanup");
2834
2962
  const RESUME_SNAPSHOT_WAIT_MS = 1e4;
2835
2963
  const RESUME_SNAPSHOT_POLL_MS = 100;
2964
+ /** runId -> toolCallId -> token of the resume of that tool call in flight in this process. */
2965
+ const inFlightToolCallResumes = /* @__PURE__ */ new Map();
2966
+ /** Names this process in resume claim owner ids, to recognize its own claims. */
2967
+ const RESUME_CLAIM_PROCESS_ID = crypto.randomUUID();
2968
+ /**
2969
+ * Marks a resume of `toolCallId` as in flight. Returns `undefined` when another resume already
2970
+ * holds the mark. The returned release only clears its own mark.
2971
+ */
2972
+ function markToolCallResume(runId, toolCallId) {
2973
+ const token = Symbol(toolCallId);
2974
+ const marks = inFlightToolCallResumes.get(runId) ?? /* @__PURE__ */ new Map();
2975
+ if (marks.has(toolCallId)) return void 0;
2976
+ marks.set(toolCallId, token);
2977
+ inFlightToolCallResumes.set(runId, marks);
2978
+ return () => {
2979
+ if (marks.get(toolCallId) !== token) return;
2980
+ marks.delete(toolCallId);
2981
+ if (marks.size === 0) inFlightToolCallResumes.delete(runId);
2982
+ };
2983
+ }
2984
+ function resumeAlreadyClaimedError(agentName, runId, toolCallId) {
2985
+ return new _mastra_core_error.MastraError({
2986
+ id: "AGENT_RESUME_ALREADY_CLAIMED",
2987
+ domain: _mastra_core_error.ErrorDomain.AGENT,
2988
+ category: _mastra_core_error.ErrorCategory.USER,
2989
+ text: `InngestAgent "${agentName}" resume(${runId}) cannot resume the run because another resume of it is already running.`,
2990
+ details: {
2991
+ agentName,
2992
+ runId,
2993
+ ...toolCallId ? { toolCallId } : {}
2994
+ }
2995
+ });
2996
+ }
2997
+ /** A second approval of a tool call this process is already resuming fails right away (#27485). */
2998
+ function assertToolCallResumeNotInFlight(agentName, runId, toolCallId) {
2999
+ if (toolCallId && inFlightToolCallResumes.get(runId)?.has(toolCallId)) throw resumeAlreadyClaimedError(agentName, runId, toolCallId);
3000
+ }
2836
3001
  /**
2837
3002
  * Merges the wrapped agent's `defaultOptions` under the call options, matching
2838
3003
  * core `DurableAgent`, so lifecycle callbacks configured as defaults fire unless
@@ -2944,18 +3109,30 @@ function createInngestAgent(options) {
2944
3109
  async function deleteFencedSuspendedRun(runId) {
2945
3110
  try {
2946
3111
  const workflowsStore = await mastra?.getStorage()?.getStore("workflows");
2947
- if ((await workflowsStore?.loadWorkflowSnapshot({
2948
- runId,
2949
- workflowName: InngestDurableStepIds.AGENTIC_LOOP
2950
- }))?.status !== "suspended") return;
2951
- await workflowsStore?.deleteWorkflowRunById({
3112
+ const snapshot = await workflowsStore?.loadWorkflowSnapshot({
2952
3113
  runId,
2953
3114
  workflowName: InngestDurableStepIds.AGENTIC_LOOP
2954
3115
  });
2955
- await workflowsStore?.deleteWorkflowRunById({
2956
- runId,
2957
- workflowName: InngestDurableStepIds.AGENTIC_EXECUTION
2958
- });
3116
+ const store = await resumeClaimStore(mastra);
3117
+ const owner = await store?.getRunOwnership({ runId: resumeClaimKey(runId) });
3118
+ const parked = !owner?.live && (snapshot?.status === "suspended" || snapshot?.status === "running" && Object.keys(snapshot.suspendedPaths ?? {}).length > 0);
3119
+ const fence = parked && store ? await store.claimRunOwnership({
3120
+ runId: resumeClaimKey(runId),
3121
+ ownerId: `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/`,
3122
+ leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
3123
+ expectedGeneration: owner?.generation ?? 0
3124
+ }) : void 0;
3125
+ if (fence?.acquired) await store?.releaseRunOwnership(fence.record);
3126
+ if (parked && (!store || fence?.acquired)) {
3127
+ await workflowsStore?.deleteWorkflowRunById({
3128
+ runId,
3129
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP
3130
+ });
3131
+ await workflowsStore?.deleteWorkflowRunById({
3132
+ runId,
3133
+ workflowName: InngestDurableStepIds.AGENTIC_EXECUTION
3134
+ });
3135
+ }
2959
3136
  await (0, _mastra_core_agent_durable.emitAbortEvent)(getPubsub(), runId, {
2960
3137
  steps: [],
2961
3138
  text: ""
@@ -3066,6 +3243,62 @@ function createInngestAgent(options) {
3066
3243
  return false;
3067
3244
  }
3068
3245
  }
3246
+ /** The live lease of the resume holding the run's claim, if any. */
3247
+ async function liveResumeClaim(runId) {
3248
+ const owner = await (await resumeClaimStore(mastra))?.getRunOwnership({ runId: resumeClaimKey(runId) });
3249
+ return owner?.live ? owner : void 0;
3250
+ }
3251
+ /**
3252
+ * Claims a suspension read by `resume()` (`suspended` -> `running`) so no other resume, in this
3253
+ * process or another, dispatches it again (#27485, #27925). The lease is taken first and is the
3254
+ * mutex: a `running` snapshot without a live lease is a claim whose event never started, which
3255
+ * this resume takes over. Returns `undefined` when another resume got there first.
3256
+ */
3257
+ async function claimSuspension(runId, snapshot, toolCallId) {
3258
+ const store = await resumeClaimStore(mastra);
3259
+ if (!store || !snapshot.status) return { release: async () => {} };
3260
+ const key = resumeClaimKey(runId);
3261
+ const owner = await store.getRunOwnership({ runId: key });
3262
+ if (owner?.live) return void 0;
3263
+ const ownerId = `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/${toolCallId ?? ""}`;
3264
+ const lease = await store.claimRunOwnership({
3265
+ runId: key,
3266
+ ownerId,
3267
+ leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
3268
+ expectedGeneration: owner?.generation ?? 0
3269
+ });
3270
+ if (!lease.acquired) return void 0;
3271
+ const fence = {
3272
+ runId: key,
3273
+ generation: lease.record.generation,
3274
+ ownerId
3275
+ };
3276
+ const claimed = await setLoopStatus(store, runId, "running", snapshot.status);
3277
+ if (claimed?.timestamp !== snapshot.timestamp) {
3278
+ if (claimed && snapshot.status !== "running") await setLoopStatus(store, runId, "suspended", "running");
3279
+ await store.releaseRunOwnership(fence);
3280
+ return;
3281
+ }
3282
+ return {
3283
+ fence,
3284
+ release: async () => {
3285
+ if (!(0, _mastra_core_storage.matchesRunFence)(await store.getRunOwnership({ runId: key }), fence)) return;
3286
+ await setLoopStatus(store, runId, "suspended", "running");
3287
+ await store.releaseRunOwnership(fence);
3288
+ }
3289
+ };
3290
+ }
3291
+ /**
3292
+ * Throws unless this resume may wait for the live one holding the run: one resuming a different
3293
+ * call, or any resume once the holder's segment parked again in this process. Any other resume is a
3294
+ * duplicate, and waiting would hand its resume data to whatever the run suspends on next.
3295
+ */
3296
+ function assertMayWaitFor(owner, runId, toolCallId) {
3297
+ const [ownerProcess, , ...label] = owner.ownerId.split("/");
3298
+ const ownerToolCallId = label.join("/");
3299
+ if (ownerProcess === RESUME_CLAIM_PROCESS_ID && !inFlightToolCallResumes.get(runId)?.has(ownerToolCallId) || toolCallId && ownerToolCallId !== toolCallId) return;
3300
+ throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
3301
+ }
3069
3302
  /**
3070
3303
  * Tool calls and text from before the suspension, seeded into the resumed stream
3071
3304
  * so its `toolCalls` and `text` include them without replaying their chunks.
@@ -3364,6 +3597,7 @@ function createInngestAgent(options) {
3364
3597
  throw error;
3365
3598
  }
3366
3599
  }).catch(async (error) => {
3600
+ endRunSpansWithError(runId, error);
3367
3601
  await emitError(runId, error);
3368
3602
  await failStream(error);
3369
3603
  });
@@ -3416,6 +3650,11 @@ function createInngestAgent(options) {
3416
3650
  bgManager: mastra?.backgroundTaskManager
3417
3651
  });
3418
3652
  }
3653
+ const markedToolCallId = resumeOptions?.toolCallId ?? "";
3654
+ if (inFlightToolCallResumes.get(runId)?.has(markedToolCallId)) {
3655
+ if (!await resumeClaimStore(mastra) || await liveResumeClaim(runId)) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
3656
+ inFlightToolCallResumes.get(runId)?.delete(markedToolCallId);
3657
+ }
3419
3658
  const existingRegistryEntry = (0, _mastra_core_agent_durable.getRunRegistryEntry)(runId, mastra);
3420
3659
  await (existingRegistryEntry?.workflowExecution)?.catch(() => {});
3421
3660
  const resumableSnapshot = (async () => {
@@ -3427,9 +3666,21 @@ function createInngestAgent(options) {
3427
3666
  });
3428
3667
  const toolCallId = resumeOptions?.toolCallId;
3429
3668
  let nestedSnapshot;
3669
+ let held = false;
3430
3670
  const isReady = async (s) => {
3431
3671
  nestedSnapshot = void 0;
3432
- if (s?.status !== "suspended" || toolCallId && !s.resumeLabels?.[toolCallId]) return false;
3672
+ held = false;
3673
+ const claimed = s?.status === "running" && Object.keys(s.suspendedPaths ?? {}).length > 0;
3674
+ if (s?.status !== "suspended" && !claimed) return false;
3675
+ const owner = await liveResumeClaim(runId);
3676
+ if (owner) {
3677
+ held = true;
3678
+ if (s.status !== "suspended") assertMayWaitFor(owner, runId, toolCallId);
3679
+ return false;
3680
+ }
3681
+ if (claimed && !await resumeClaimStore(mastra)) return false;
3682
+ if (toolCallId && !s.resumeLabels?.[toolCallId]) return false;
3683
+ if (s.activePaths?.length) return false;
3433
3684
  const labelIds = Object.keys(s.resumeLabels ?? {});
3434
3685
  if (labelIds.length === 0) return true;
3435
3686
  nestedSnapshot = await workflowsStore.loadWorkflowSnapshot({
@@ -3440,14 +3691,18 @@ function createInngestAgent(options) {
3440
3691
  };
3441
3692
  let snapshot = await loadSnapshot();
3442
3693
  const deadline = Date.now() + RESUME_SNAPSHOT_WAIT_MS;
3443
- while (!await isReady(snapshot) && Date.now() < deadline) {
3694
+ let ready;
3695
+ while (!(ready = await isReady(snapshot)) && Date.now() < deadline) {
3696
+ assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
3444
3697
  await new Promise((resolve) => setTimeout(resolve, RESUME_SNAPSHOT_POLL_MS));
3445
3698
  snapshot = await loadSnapshot();
3446
3699
  }
3447
3700
  return {
3448
3701
  hasStore: true,
3449
3702
  snapshot,
3450
- nestedSnapshot
3703
+ nestedSnapshot,
3704
+ ready,
3705
+ held
3451
3706
  };
3452
3707
  })();
3453
3708
  resumableSnapshot.catch(() => {});
@@ -3457,8 +3712,10 @@ function createInngestAgent(options) {
3457
3712
  requestContext: new _mastra_core_request_context.RequestContext([...savedRequestContext, ...resumeOptions?.requestContext?.entries() ?? []])
3458
3713
  });
3459
3714
  (0, _mastra_core_agent_durable.validateModelTimeoutSettings)(callbackOptions.modelSettings?.timeout);
3460
- const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot } = await resumableSnapshot;
3461
- if (hasStore && suspendedSnapshot?.status !== "suspended") throw new inngest.NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (suspendedSnapshot?.status ? ` (status: ${suspendedSnapshot.status}).` : " (no snapshot found)."));
3715
+ const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot, ready: snapshotReady, held } = await resumableSnapshot;
3716
+ const takeover = snapshotReady && suspendedSnapshot?.status === "running";
3717
+ if (held || !takeover && suspendedSnapshot?.status === "running" && Object.keys(suspendedSnapshot.suspendedPaths ?? {}).length) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
3718
+ if (hasStore && !takeover && suspendedSnapshot?.status !== "suspended") throw new inngest.NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (suspendedSnapshot?.status ? ` (status: ${suspendedSnapshot.status}).` : " (no snapshot found)."));
3462
3719
  const suspendedStepIds = suspendedSnapshot?.suspendedPaths ? Object.keys(suspendedSnapshot.suspendedPaths) : [];
3463
3720
  const resumeLabels = suspendedSnapshot?.resumeLabels ?? {};
3464
3721
  const expandToLeafPath = (stepId) => {
@@ -3469,7 +3726,7 @@ function createInngestAgent(options) {
3469
3726
  let steps;
3470
3727
  if (toolCallId) {
3471
3728
  const targetStepId = resumeLabels[toolCallId]?.stepId;
3472
- if (!targetStepId) {
3729
+ if (!targetStepId || nestedSnapshot && !nestedSnapshot.resumeLabels?.[toolCallId]) {
3473
3730
  const available = Object.keys(resumeLabels);
3474
3731
  throw new inngest.NonRetriableError(`Cannot resume run ${runId}: no suspended tool call with id "${toolCallId}". ` + (available.length > 0 ? `Suspended tool call ids: ${available.join(", ")}.` : `No tool calls are currently suspended.`));
3475
3732
  }
@@ -3481,6 +3738,15 @@ function createInngestAgent(options) {
3481
3738
  }
3482
3739
  const resumeOffset = await getPubsubOffset(runId);
3483
3740
  const { toolCalls: initialToolCalls, resumedText } = await loadSuspendedIteration(runId, suspendedSnapshot, nestedSnapshot);
3741
+ const markKey = toolCallId ?? (await resumeClaimStore(mastra) ? "" : void 0);
3742
+ const releaseToolCallMarker = markKey === void 0 ? () => {} : markToolCallResume(runId, markKey);
3743
+ if (!releaseToolCallMarker) throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
3744
+ const claim = await claimSuspension(runId, suspendedSnapshot ?? {}, toolCallId);
3745
+ if (!claim) {
3746
+ releaseToolCallMarker();
3747
+ assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
3748
+ return proxyRef.resume(runId, resumeData, resumeOptions);
3749
+ }
3484
3750
  const abortController = new AbortController();
3485
3751
  const stopForwardingAbort = resumeOptions?.abortSignal ? forwardExternalAbort(resumeOptions.abortSignal, abortController, runId) : void 0;
3486
3752
  let existingEntry = existingRegistryEntry;
@@ -3534,6 +3800,7 @@ function createInngestAgent(options) {
3534
3800
  let resumeCleanedUp = false;
3535
3801
  const finalizeResumeRegistry = () => {
3536
3802
  clearTotalTimeout();
3803
+ releaseToolCallMarker();
3537
3804
  if (resumeCleanedUp) return;
3538
3805
  resumeCleanedUp = true;
3539
3806
  stopForwardingAbort?.();
@@ -3562,7 +3829,10 @@ function createInngestAgent(options) {
3562
3829
  requestContext: callbackOptions.requestContext,
3563
3830
  onChunk: (chunk) => {
3564
3831
  resumedChunkSeen = true;
3565
- if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") stopForwardingAbort?.();
3832
+ if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
3833
+ stopForwardingAbort?.();
3834
+ if (!toolCallId || chunk.payload.toolCallId === toolCallId) releaseToolCallMarker();
3835
+ }
3566
3836
  return callbackOptions.onChunk?.(chunk);
3567
3837
  },
3568
3838
  onStepFinish: callbackOptions.onStepFinish,
@@ -3583,6 +3853,7 @@ function createInngestAgent(options) {
3583
3853
  onSuspended: async (data) => {
3584
3854
  if (!resumedChunkSeen) return;
3585
3855
  clearTotalTimeout();
3856
+ releaseToolCallMarker();
3586
3857
  try {
3587
3858
  await callbackOptions.onSuspended?.(data);
3588
3859
  } finally {
@@ -3600,6 +3871,7 @@ function createInngestAgent(options) {
3600
3871
  });
3601
3872
  const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
3602
3873
  let notResumable = false;
3874
+ let sendStarted = false;
3603
3875
  const didThreadRunPublishTerminal = _mastra_core_agent_durable.agentThreadStreamRuntime.captureThreadRunTerminalPublish(runId, agent.getPubSub());
3604
3876
  const dispatch = ready.then(async () => {
3605
3877
  const snapshot = suspendedSnapshot;
@@ -3614,7 +3886,9 @@ function createInngestAgent(options) {
3614
3886
  traceId: snapshot.tracingContext.traceId,
3615
3887
  parentSpanId: snapshot.tracingContext.spanId
3616
3888
  } : void 0;
3889
+ sendStarted = true;
3617
3890
  await inngest$1.send({
3891
+ ...snapshot?.timestamp && claim.fence ? { id: `${runId}:resume:${snapshot.timestamp}:${claim.fence.generation}` } : {},
3618
3892
  name: eventName,
3619
3893
  data: buildDurableResumeEventData({
3620
3894
  inputData: resumeData,
@@ -3626,7 +3900,9 @@ function createInngestAgent(options) {
3626
3900
  resume: {
3627
3901
  steps,
3628
3902
  resumePayload: resumeData,
3629
- resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0
3903
+ resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0,
3904
+ label: toolCallId,
3905
+ claim: claim.fence
3630
3906
  }
3631
3907
  })
3632
3908
  });
@@ -3640,6 +3916,7 @@ function createInngestAgent(options) {
3640
3916
  } catch (error) {
3641
3917
  streamCleanup();
3642
3918
  finalizeResumeRegistry();
3919
+ if (!sendStarted) await claim.release().catch((releaseError) => mastra?.getLogger?.()?.warn?.(`[InngestAgent] resume(${runId}) failed to release its claim`, releaseError));
3643
3920
  throw error;
3644
3921
  }
3645
3922
  const resumeMemory = resumeOptions?.memory;
@@ -4826,4 +5103,4 @@ Object.defineProperty(exports, "serve", {
4826
5103
  }
4827
5104
  });
4828
5105
 
4829
- //# sourceMappingURL=src-BFLWFGPN.cjs.map
5106
+ //# sourceMappingURL=src-QjUHaLdm.cjs.map