@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.
@@ -7,23 +7,75 @@ import { toStandardSchema } from "@mastra/core/schema";
7
7
  import { Tool, createTool } from "@mastra/core/tools";
8
8
  import * as coreWorkflows from "@mastra/core/workflows";
9
9
  import { DefaultExecutionEngine, Run, Workflow, createStepFromAgent, createStepFromTool, createTimeTravelExecutionParams, getEntryWorkflow, hydrateSerializedStepErrors, isSingleStepEntry } from "@mastra/core/workflows";
10
- import { AGENT_STREAM_TOPIC, AgentStreamEventTypes, DURABLE_STOP_WHEN_ERROR_ID, DurableAgentDefaults, DurableStepIds, agentThreadStreamRuntime, applyReservedMemoryContextKeys, baseIterationStateSchema, createBaseIterationStateUpdate, createDurableAgentStream, createDurableBackgroundTaskCheckStep, createDurableGoalStep, createDurableIsTaskCompleteStep, createDurableLLMExecutionStep, createDurableLLMMappingStep, createDurableToolCallStep, deleteRunRegistryEntry, durableAgenticOutputSchema, emitAbortEvent, emitChunkEvent, emitErrorEvent, emitFinishEvent, executeDurableAgentScorers, getRunRegistryEntry, getRunStreamSlot, getScopeStreamSlot, globalRunRegistry, loadRunStoredMessages, modelConfigSchema, modelListEntrySchema, normalizeResumeGenerateArgs, persistDurableRunInput, prepareForDurableExecution, pruneAgentLoopSnapshot, publishAbortRequest, requestAcknowledgedAbort, resolveDurableToolCallConcurrency, runDurableFinishSideEffects, runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle, takeRunScorerInstances, validateModelTimeoutSettings } from "@mastra/core/agent/durable";
10
+ import * as coreDurable from "@mastra/core/agent/durable";
11
+ import { AGENT_STREAM_TOPIC, AgentStreamEventTypes, DURABLE_STOP_WHEN_ERROR_ID, DurableAgentDefaults, DurableStepIds, agentThreadStreamRuntime, applyReservedMemoryContextKeys, baseIterationStateSchema, createBaseIterationStateUpdate, createDurableAgentStream, createDurableBackgroundTaskCheckStep, createDurableGoalStep, createDurableIsTaskCompleteStep, createDurableLLMExecutionStep, createDurableLLMMappingStep, createDurableToolCallStep, deleteRunRegistryEntry, durableAgenticOutputSchema, emitAbortEvent, emitChunkEvent, emitErrorEvent, emitFinishEvent, emitSuspendedEvent, executeDurableAgentScorers, getRunRegistryEntry, getRunStreamSlot, getScopeStreamSlot, globalRunRegistry, loadRunStoredMessages, modelConfigSchema, modelListEntrySchema, normalizeResumeGenerateArgs, persistDurableRunInput, prepareForDurableExecution, pruneAgentLoopSnapshot, publishAbortRequest, requestAcknowledgedAbort, resolveDurableToolCallConcurrency, runDurableFinishSideEffects, runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle, takeRunScorerInstances, validateModelTimeoutSettings } from "@mastra/core/agent/durable";
11
12
  import { RequestContext } from "@mastra/core/di";
12
13
  import { CachingPubSub, PubSub } from "@mastra/core/events";
13
14
  import { NonRetriableError } from "inngest";
15
+ import { MASTRA_AUTH_TOKEN_KEY, RequestContext as RequestContext$1 } from "@mastra/core/request-context";
14
16
  import { AsyncLocalStorage } from "async_hooks";
15
17
  import { coreFeatures } from "@mastra/core/features";
16
18
  import { subscribe } from "inngest/realtime";
17
19
  import { ReadableStream as ReadableStream$1 } from "stream/web";
18
20
  import { ChunkFrom, WorkflowRunOutput } from "@mastra/core/stream";
19
- import { MASTRA_AUTH_TOKEN_KEY, RequestContext as RequestContext$1 } from "@mastra/core/request-context";
20
21
  import { serve } from "inngest/hono";
21
22
  import { InMemoryServerCache } from "@mastra/core/cache";
22
23
  import { createTimeoutAbortSignal, isMastraTimeoutError } from "@mastra/core/loop";
24
+ import { matchesRunFence } from "@mastra/core/storage";
23
25
  import { deepMerge, rebindProcessorTools } from "@mastra/core/utils";
24
26
  import { MessageList as MessageList$1 } from "@mastra/core/agent/message-list";
25
27
  import { PUBSUB_SYMBOL } from "@mastra/core/workflows/_constants";
26
28
  import { z } from "zod";
29
+ // src/durable-event-payload.ts
30
+ /**
31
+ * Lease on an InngestAgent resume claim until its event starts. A claim whose event never started
32
+ * (its resume died before sending, or the send failed) lapses, and a later resume takes it over.
33
+ */
34
+ const RESUME_CLAIM_DISPATCH_LEASE_MS = 6e4;
35
+ /**
36
+ * Flatten a `RequestContext` into the plain JSON object the event carries.
37
+ * Absent context serializes to `{}`, never `undefined`.
38
+ */
39
+ function serializeRequestContext(requestContext) {
40
+ const obj = requestContext ? requestContext.toJSON() : {};
41
+ delete obj[MASTRA_AUTH_TOKEN_KEY];
42
+ return obj;
43
+ }
44
+ /**
45
+ * Resume request-context rule: values persisted in the snapshot are the base,
46
+ * and anything the caller supplies on this resume call overrides them.
47
+ */
48
+ function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
49
+ return {
50
+ ...snapshotRequestContext ?? {},
51
+ ...serializeRequestContext(requestContext)
52
+ };
53
+ }
54
+ function buildDurableTriggerEventData(args) {
55
+ const { requestContext, ...rest } = args;
56
+ return {
57
+ ...rest,
58
+ requestContext: toRequestContextEntries(requestContext)
59
+ };
60
+ }
61
+ function buildDurableResumeEventData(args) {
62
+ const { requestContext, ...rest } = args;
63
+ return {
64
+ ...rest,
65
+ requestContext: toRequestContextEntries(requestContext)
66
+ };
67
+ }
68
+ function buildDurableTimeTravelEventData(args) {
69
+ const { requestContext, ...rest } = args;
70
+ return {
71
+ ...rest,
72
+ requestContext: toRequestContextEntries(requestContext)
73
+ };
74
+ }
75
+ function toRequestContextEntries(requestContext) {
76
+ if (!requestContext) return {};
77
+ return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
78
+ }
27
79
  // src/nested-workflow-output.ts
28
80
  const NESTED_WORKFLOW_OUTPUT_MODE = {
29
81
  DEFAULT: "default",
@@ -84,6 +136,10 @@ function workflowTermination(...args) {
84
136
  function agentLoopTermination(...args) {
85
137
  return coreFeatures.has("execution-outcomes") ? coreObservability.agentLoopTermination?.(...args) ?? {} : {};
86
138
  }
139
+ /** End the caller's live root spans with `error`; a no-op on cores without the helper. */
140
+ function endRunSpansWithError(...args) {
141
+ if (coreFeatures.has("execution-outcomes")) coreDurable.endRunSpansWithError?.(...args);
142
+ }
87
143
  /** Keep completed-request usage when a failed request makes the total incomplete. */
88
144
  function generationUsage(usage, steps) {
89
145
  const usageIncomplete = coreFeatures.has("execution-outcomes") && coreObservability.isUsageIncomplete?.(usage);
@@ -443,7 +499,9 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
443
499
  runId,
444
500
  steps: nestedResumeSteps,
445
501
  resumePayload: resume.resumePayload,
446
- resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0
502
+ resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0,
503
+ label: resume.label,
504
+ forEachIndex: resume.label ? snapshot?.resumeLabels?.[resume.label]?.foreachIndex : void 0
447
505
  } },
448
506
  outputOptions: {
449
507
  includeState: true,
@@ -561,6 +619,26 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
561
619
  const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
562
620
  return stepResult?.status === "suspended";
563
621
  });
622
+ const agentInput = stepResults.input;
623
+ const resumedCallFinished = isResume && !!resume?.label && !result.resumeLabels?.[resume.label];
624
+ const parked = (suspendedSteps[0]?.[1])?.suspendPayload;
625
+ const approval = parked?.requireToolApproval;
626
+ const parkedToolCallId = parked?.toolCallId ?? approval?.toolCallId;
627
+ let parkedBefore = false;
628
+ if (resumedCallFinished && agentInput?.__workflowKind === "durable-agent" && parkedToolCallId) parkedBefore = !!(await (await this.mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
629
+ workflowName: executionContext.workflowId,
630
+ runId: executionContext.runId
631
+ }))?.resumeLabels?.[parkedToolCallId];
632
+ if (parkedBefore && agentInput?.runId) {
633
+ const meta = parked?.__workflow_meta;
634
+ await emitSuspendedEvent(pubsub, agentInput.runId, {
635
+ toolCallId: parkedToolCallId,
636
+ toolName: approval?.toolName ?? parked?.toolName,
637
+ args: approval?.args ?? parked?.args ?? meta?.foreachOutput?.[meta.foreachIndex]?.payload?.args,
638
+ suspendPayload: parked?.toolCallSuspended,
639
+ type: parked?.type === "approval" ? "approval" : "suspension"
640
+ });
641
+ }
564
642
  for (const [stepName, stepResult] of suspendedSteps) {
565
643
  const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
566
644
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
@@ -1052,51 +1130,6 @@ var InngestPubSub = class extends PubSub {
1052
1130
  this.subscriptions.clear();
1053
1131
  }
1054
1132
  };
1055
- // src/durable-event-payload.ts
1056
- /**
1057
- * Flatten a `RequestContext` into the plain JSON object the event carries.
1058
- * Absent context serializes to `{}`, never `undefined`.
1059
- */
1060
- function serializeRequestContext(requestContext) {
1061
- const obj = requestContext ? requestContext.toJSON() : {};
1062
- delete obj[MASTRA_AUTH_TOKEN_KEY];
1063
- return obj;
1064
- }
1065
- /**
1066
- * Resume request-context rule: values persisted in the snapshot are the base,
1067
- * and anything the caller supplies on this resume call overrides them.
1068
- */
1069
- function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
1070
- return {
1071
- ...snapshotRequestContext ?? {},
1072
- ...serializeRequestContext(requestContext)
1073
- };
1074
- }
1075
- function buildDurableTriggerEventData(args) {
1076
- const { requestContext, ...rest } = args;
1077
- return {
1078
- ...rest,
1079
- requestContext: toRequestContextEntries(requestContext)
1080
- };
1081
- }
1082
- function buildDurableResumeEventData(args) {
1083
- const { requestContext, ...rest } = args;
1084
- return {
1085
- ...rest,
1086
- requestContext: toRequestContextEntries(requestContext)
1087
- };
1088
- }
1089
- function buildDurableTimeTravelEventData(args) {
1090
- const { requestContext, ...rest } = args;
1091
- return {
1092
- ...rest,
1093
- requestContext: toRequestContextEntries(requestContext)
1094
- };
1095
- }
1096
- function toRequestContextEntries(requestContext) {
1097
- if (!requestContext) return {};
1098
- return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
1099
- }
1100
1133
  // src/run.ts
1101
1134
  var InngestRun = class extends Run {
1102
1135
  inngest;
@@ -1817,6 +1850,8 @@ var InngestWorkflow = class extends Workflow {
1817
1850
  */
1818
1851
  #pubsubFactory;
1819
1852
  #emitWorkflowEvents = true;
1853
+ /** Functions a host (e.g. the durable agent loop) serves alongside this workflow's own. */
1854
+ #hostFunctions = [];
1820
1855
  constructor(params, inngest) {
1821
1856
  const { concurrency, rateLimit, throttle, debounce, priority, retries, cron, inputData, initialState, ...workflowParams } = params;
1822
1857
  super(workflowParams);
@@ -1881,6 +1916,9 @@ var InngestWorkflow = class extends Workflow {
1881
1916
  this.__setEmitWorkflowEvents(this.#emitWorkflowEvents);
1882
1917
  return committed;
1883
1918
  }
1919
+ __addHostFunctions(functions) {
1920
+ this.#hostFunctions.push(...functions);
1921
+ }
1884
1922
  __setEmitWorkflowEvents(enabled) {
1885
1923
  this.#emitWorkflowEvents = enabled;
1886
1924
  const updateNested = (step) => {
@@ -2012,6 +2050,18 @@ var InngestWorkflow = class extends Workflow {
2012
2050
  });
2013
2051
  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.`);
2014
2052
  }
2053
+ const resumeClaim = resume?.claim;
2054
+ if (resumeClaim) {
2055
+ if (!await step.run(`workflow.${this.id}.resume-claim`, async () => {
2056
+ return (await (await this.#mastra?.getStorage()?.getStore("workflows"))?.renewRunOwnership({
2057
+ ...resumeClaim,
2058
+ leaseMs: 864e5
2059
+ }))?.renewed ?? true;
2060
+ })) return {
2061
+ result: void 0,
2062
+ runId
2063
+ };
2064
+ }
2015
2065
  if (resume && (initialState === void 0 || resume.stepResults === void 0)) {
2016
2066
  const snapshot = await (await this.#mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
2017
2067
  workflowName: this.id,
@@ -2190,6 +2240,7 @@ var InngestWorkflow = class extends Workflow {
2190
2240
  });
2191
2241
  }
2192
2242
  }
2243
+ if (resumeClaim) await (await mastra?.getStorage()?.getStore("workflows"))?.releaseRunOwnership(resumeClaim);
2193
2244
  try {
2194
2245
  await pubsub.publish(`workflow.events.v2.${runId}`, {
2195
2246
  type: "watch",
@@ -2245,7 +2296,8 @@ var InngestWorkflow = class extends Workflow {
2245
2296
  return [
2246
2297
  this.getFunction(),
2247
2298
  ...this.cronConfig?.cron ? [this.createCronFunction()] : [],
2248
- ...this.getNestedFunctions(this.executionGraph.steps)
2299
+ ...this.getNestedFunctions(this.executionGraph.steps),
2300
+ ...this.#hostFunctions
2249
2301
  ];
2250
2302
  }
2251
2303
  };
@@ -2375,6 +2427,7 @@ const durableAgenticInputSchema = z.object({
2375
2427
  * Iteration state schema - extends base with observability fields.
2376
2428
  */
2377
2429
  const iterationStateSchema = baseIterationStateSchema.extend({
2430
+ accumulatedSteps: z.array(z.any()),
2378
2431
  modelList: z.array(modelListEntrySchema).optional(),
2379
2432
  agentSpanData: z.any().optional(),
2380
2433
  modelSpanData: z.any().optional(),
@@ -2404,7 +2457,77 @@ const InngestDurableStepIds = {
2404
2457
  AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_EXECUTION}`,
2405
2458
  AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_LOOP}`
2406
2459
  };
2460
+ /** Run ownership key of the claim an InngestAgent resume holds on the loop run. */
2461
+ const resumeClaimKey = (runId) => `${InngestDurableStepIds.AGENTIC_LOOP}:resume-claim:${runId}`;
2462
+ /**
2463
+ * The store a resume claim lives in. A claim needs an atomic status change and a lease, so a
2464
+ * claim whose resume died can be taken over; without both, resumes are not claimed at all.
2465
+ */
2466
+ async function resumeClaimStore(mastra) {
2467
+ const store = await mastra?.getStorage()?.getStore("workflows");
2468
+ if (!store?.supportsConcurrentUpdates?.()) return void 0;
2469
+ return await Promise.resolve().then(() => store.supportsRunFencing()).catch(() => false) ? store : void 0;
2470
+ }
2471
+ const setLoopStatus = (store, runId, status, expectedStatus) => store.updateWorkflowState({
2472
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP,
2473
+ runId,
2474
+ opts: {
2475
+ status,
2476
+ expectedStatus
2477
+ }
2478
+ });
2479
+ /**
2480
+ * Ends a resumed segment Inngest failed or cancelled, which never reaches the finalize step that
2481
+ * would: marks the run failed or canceled, ends its stream and releases its claim. The run is not
2482
+ * parked again, since a nested segment Inngest did not cancel can still be running its tools.
2483
+ */
2484
+ function createResumeClaimReleaseFunction(inngest, workflow) {
2485
+ const loopEvent = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
2486
+ return inngest.createFunction({
2487
+ id: `${loopEvent}.resume-claim-release`,
2488
+ triggers: [{
2489
+ event: "inngest/function.failed",
2490
+ if: `event.data.event.name == '${loopEvent}'`
2491
+ }, {
2492
+ event: "inngest/function.cancelled",
2493
+ if: `event.data.event.name == '${loopEvent}'`
2494
+ }]
2495
+ }, async ({ event }) => {
2496
+ const original = event.data.event?.data;
2497
+ const claim = original?.resume?.claim;
2498
+ const mastra = workflow.mastra;
2499
+ const store = await resumeClaimStore(mastra);
2500
+ if (!original?.runId || !claim || !store) return;
2501
+ if (!(await store.renewRunOwnership({
2502
+ ...claim,
2503
+ leaseMs: 6e4
2504
+ })).renewed) return;
2505
+ const cancelled = event.name === "inngest/function.cancelled";
2506
+ await setLoopStatus(store, original.runId, cancelled ? "canceled" : "failed", "running");
2507
+ const defaultPubsub = new InngestPubSub(inngest, workflow.id, mastra?.getLogger?.());
2508
+ const pubsub = workflow.__getPubsubFactory()?.(defaultPubsub) ?? defaultPubsub;
2509
+ try {
2510
+ if (cancelled) await emitAbortEvent(pubsub, original.runId, {
2511
+ steps: [],
2512
+ text: ""
2513
+ });
2514
+ else {
2515
+ const message = event.data.error?.message;
2516
+ await emitErrorEvent(pubsub, original.runId, new Error(message ?? "The resumed agent run failed."));
2517
+ }
2518
+ } catch (error) {
2519
+ mastra?.getLogger?.()?.warn?.(`[InngestAgent] run ${original.runId} failed to publish its end`, error);
2520
+ }
2521
+ await store.releaseRunOwnership(claim);
2522
+ });
2523
+ }
2407
2524
  function createInngestDurableAgenticWorkflow(options) {
2525
+ const workflow = createAgenticLoopWorkflow(options);
2526
+ const inngestWorkflow = workflow;
2527
+ inngestWorkflow.__addHostFunctions([createResumeClaimReleaseFunction(options.inngest, inngestWorkflow)]);
2528
+ return workflow;
2529
+ }
2530
+ function createAgenticLoopWorkflow(options) {
2408
2531
  const { inngest, maxSteps = DurableAgentDefaults.MAX_STEPS, retries } = options;
2409
2532
  const { createWorkflow } = init(inngest);
2410
2533
  const llmExecutionStep = createDurableLLMExecutionStep();
@@ -2546,8 +2669,12 @@ function createInngestDurableAgenticWorkflow(options) {
2546
2669
  });
2547
2670
  }
2548
2671
  };
2672
+ const recordStopCause = (cause) => {
2673
+ state.tracingStopCause = cause;
2674
+ if (tracingRegistry) tracingRegistry.tracingStopCause = cause;
2675
+ };
2549
2676
  if (state.delegationBailed) {
2550
- if (tracingRegistry) tracingRegistry.tracingStopCause = state.lastStepResult?.isContinued ? "delegation" : "model_finished";
2677
+ recordStopCause(state.lastStepResult?.isContinued ? "delegation" : "model_finished");
2551
2678
  await emitStepFinish(false);
2552
2679
  return false;
2553
2680
  }
@@ -2555,7 +2682,7 @@ function createInngestDurableAgenticWorkflow(options) {
2555
2682
  const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
2556
2683
  const underMaxSteps = state.iterationCount < effectiveMaxSteps;
2557
2684
  if (!shouldContinue || !underMaxSteps) {
2558
- if (tracingRegistry) tracingRegistry.tracingStopCause = shouldContinue ? "max_steps" : "model_finished";
2685
+ recordStopCause(shouldContinue ? "max_steps" : "model_finished");
2559
2686
  await emitStepFinish(false);
2560
2687
  return false;
2561
2688
  }
@@ -2581,7 +2708,7 @@ function createInngestDurableAgenticWorkflow(options) {
2581
2708
  }
2582
2709
  }))).some(Boolean);
2583
2710
  });
2584
- if (stopped && tracingRegistry) tracingRegistry.tracingStopCause = "stop_condition";
2711
+ if (stopped) recordStopCause("stop_condition");
2585
2712
  await emitStepFinish(!stopped);
2586
2713
  return !stopped;
2587
2714
  }).map(async (params) => {
@@ -2600,6 +2727,7 @@ function createInngestDurableAgenticWorkflow(options) {
2600
2727
  requestContext,
2601
2728
  tracingContext,
2602
2729
  logger: mastra?.getLogger?.(),
2730
+ messageId: state.messageId,
2603
2731
  outputResult: {
2604
2732
  text: finalText ?? "",
2605
2733
  usage: state.accumulatedUsage,
@@ -2612,16 +2740,17 @@ function createInngestDurableAgenticWorkflow(options) {
2612
2740
  finalText = finishResult.outputText;
2613
2741
  }
2614
2742
  const tripwire = finishResult.tripwire;
2743
+ if (pubsub && !tripwire) for (const chunk of finishResult.structuredOutputChunks ?? []) await emitChunkEvent(pubsub, state.runId, {
2744
+ ...chunk,
2745
+ runId: state.runId
2746
+ });
2747
+ if (pubsub) for (const chunk of finishResult.outputResultChunks ?? []) await emitChunkEvent(pubsub, state.runId, chunk, true);
2615
2748
  if (tripwire && pubsub) await emitChunkEvent(pubsub, state.runId, {
2616
2749
  type: "tripwire",
2617
2750
  runId: state.runId,
2618
2751
  from: ChunkFrom.AGENT,
2619
2752
  payload: tripwire
2620
2753
  });
2621
- if (pubsub && !tripwire) for (const chunk of finishResult.structuredOutputChunks ?? []) await emitChunkEvent(pubsub, state.runId, {
2622
- ...chunk,
2623
- runId: state.runId
2624
- });
2625
2754
  if (pubsub && !tripwire && finishResult.titleForStream) {
2626
2755
  const title = await finishResult.titleForStream;
2627
2756
  if (title && initData.state?.threadId) await emitChunkEvent(pubsub, state.runId, {
@@ -2660,6 +2789,17 @@ function createInngestDurableAgenticWorkflow(options) {
2660
2789
  ...completionClock ? { completionStartTime: new Date(completionClock) } : {},
2661
2790
  ...timeToFirstTokenMs !== void 0 ? { timeToFirstTokenMs } : {}
2662
2791
  };
2792
+ const finishReason = finalOutput.stepResult?.reason;
2793
+ const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
2794
+ const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
2795
+ if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
2796
+ const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
2797
+ stopCause,
2798
+ delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
2799
+ finishReason,
2800
+ tripwire: tripwire ?? state.lastStepResult?.tripwire,
2801
+ maxSteps: state.options?.maxSteps ?? maxSteps
2802
+ });
2663
2803
  if (state.modelSpanData) {
2664
2804
  const modelSpan = registry?.resumeModelSpan ?? registry?.modelSpan ?? observability?.rebuildSpan(state.modelSpanData);
2665
2805
  const toolCalls = state.accumulatedSteps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
@@ -2669,13 +2809,7 @@ function createInngestDurableAgenticWorkflow(options) {
2669
2809
  })));
2670
2810
  const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps);
2671
2811
  modelSpan?.createTracker()?.endGeneration({
2672
- ...["tripwire", "error"].includes(finalOutput.stepResult?.reason ?? "") && registry?.tracingTermination ? registry.tracingTermination : agentLoopTermination({
2673
- stopCause: registry?.tracingStopCause,
2674
- delegationFailure: registry?.tracingDelegationFailure,
2675
- finishReason: finalOutput.stepResult?.reason,
2676
- tripwire,
2677
- maxSteps: state.options?.maxSteps ?? maxSteps
2678
- }),
2812
+ ...termination,
2679
2813
  output: {
2680
2814
  text: finalText,
2681
2815
  ...toolCalls.length ? { toolCalls } : {}
@@ -2691,13 +2825,7 @@ function createInngestDurableAgenticWorkflow(options) {
2691
2825
  });
2692
2826
  }
2693
2827
  if (state.agentSpanData) (registry?.resumeAgentSpan ?? registry?.agentSpan ?? observability?.rebuildSpan(state.agentSpanData))?.end({
2694
- ...["tripwire", "error"].includes(finalOutput.stepResult?.reason ?? "") && registry?.tracingTermination ? registry.tracingTermination : agentLoopTermination({
2695
- stopCause: registry?.tracingStopCause,
2696
- delegationFailure: registry?.tracingDelegationFailure,
2697
- finishReason: finalOutput.stepResult?.reason,
2698
- tripwire,
2699
- maxSteps: state.options?.maxSteps ?? maxSteps
2700
- }),
2828
+ ...termination,
2701
2829
  output: { text: finalText },
2702
2830
  ...Object.keys(clocks).length ? { attributes: clocks } : {}
2703
2831
  });
@@ -2812,6 +2940,43 @@ var InngestAgentPubSubRouter = class extends PubSub {
2812
2940
  const STREAM_CLEANUP = Symbol("mastra.durable.inngest.streamCleanup");
2813
2941
  const RESUME_SNAPSHOT_WAIT_MS = 1e4;
2814
2942
  const RESUME_SNAPSHOT_POLL_MS = 100;
2943
+ /** runId -> toolCallId -> token of the resume of that tool call in flight in this process. */
2944
+ const inFlightToolCallResumes = /* @__PURE__ */ new Map();
2945
+ /** Names this process in resume claim owner ids, to recognize its own claims. */
2946
+ const RESUME_CLAIM_PROCESS_ID = crypto.randomUUID();
2947
+ /**
2948
+ * Marks a resume of `toolCallId` as in flight. Returns `undefined` when another resume already
2949
+ * holds the mark. The returned release only clears its own mark.
2950
+ */
2951
+ function markToolCallResume(runId, toolCallId) {
2952
+ const token = Symbol(toolCallId);
2953
+ const marks = inFlightToolCallResumes.get(runId) ?? /* @__PURE__ */ new Map();
2954
+ if (marks.has(toolCallId)) return void 0;
2955
+ marks.set(toolCallId, token);
2956
+ inFlightToolCallResumes.set(runId, marks);
2957
+ return () => {
2958
+ if (marks.get(toolCallId) !== token) return;
2959
+ marks.delete(toolCallId);
2960
+ if (marks.size === 0) inFlightToolCallResumes.delete(runId);
2961
+ };
2962
+ }
2963
+ function resumeAlreadyClaimedError(agentName, runId, toolCallId) {
2964
+ return new MastraError({
2965
+ id: "AGENT_RESUME_ALREADY_CLAIMED",
2966
+ domain: ErrorDomain.AGENT,
2967
+ category: ErrorCategory.USER,
2968
+ text: `InngestAgent "${agentName}" resume(${runId}) cannot resume the run because another resume of it is already running.`,
2969
+ details: {
2970
+ agentName,
2971
+ runId,
2972
+ ...toolCallId ? { toolCallId } : {}
2973
+ }
2974
+ });
2975
+ }
2976
+ /** A second approval of a tool call this process is already resuming fails right away (#27485). */
2977
+ function assertToolCallResumeNotInFlight(agentName, runId, toolCallId) {
2978
+ if (toolCallId && inFlightToolCallResumes.get(runId)?.has(toolCallId)) throw resumeAlreadyClaimedError(agentName, runId, toolCallId);
2979
+ }
2815
2980
  /**
2816
2981
  * Merges the wrapped agent's `defaultOptions` under the call options, matching
2817
2982
  * core `DurableAgent`, so lifecycle callbacks configured as defaults fire unless
@@ -2923,18 +3088,30 @@ function createInngestAgent(options) {
2923
3088
  async function deleteFencedSuspendedRun(runId) {
2924
3089
  try {
2925
3090
  const workflowsStore = await mastra?.getStorage()?.getStore("workflows");
2926
- if ((await workflowsStore?.loadWorkflowSnapshot({
2927
- runId,
2928
- workflowName: InngestDurableStepIds.AGENTIC_LOOP
2929
- }))?.status !== "suspended") return;
2930
- await workflowsStore?.deleteWorkflowRunById({
3091
+ const snapshot = await workflowsStore?.loadWorkflowSnapshot({
2931
3092
  runId,
2932
3093
  workflowName: InngestDurableStepIds.AGENTIC_LOOP
2933
3094
  });
2934
- await workflowsStore?.deleteWorkflowRunById({
2935
- runId,
2936
- workflowName: InngestDurableStepIds.AGENTIC_EXECUTION
2937
- });
3095
+ const store = await resumeClaimStore(mastra);
3096
+ const owner = await store?.getRunOwnership({ runId: resumeClaimKey(runId) });
3097
+ const parked = !owner?.live && (snapshot?.status === "suspended" || snapshot?.status === "running" && Object.keys(snapshot.suspendedPaths ?? {}).length > 0);
3098
+ const fence = parked && store ? await store.claimRunOwnership({
3099
+ runId: resumeClaimKey(runId),
3100
+ ownerId: `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/`,
3101
+ leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
3102
+ expectedGeneration: owner?.generation ?? 0
3103
+ }) : void 0;
3104
+ if (fence?.acquired) await store?.releaseRunOwnership(fence.record);
3105
+ if (parked && (!store || fence?.acquired)) {
3106
+ await workflowsStore?.deleteWorkflowRunById({
3107
+ runId,
3108
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP
3109
+ });
3110
+ await workflowsStore?.deleteWorkflowRunById({
3111
+ runId,
3112
+ workflowName: InngestDurableStepIds.AGENTIC_EXECUTION
3113
+ });
3114
+ }
2938
3115
  await emitAbortEvent(getPubsub(), runId, {
2939
3116
  steps: [],
2940
3117
  text: ""
@@ -3045,6 +3222,62 @@ function createInngestAgent(options) {
3045
3222
  return false;
3046
3223
  }
3047
3224
  }
3225
+ /** The live lease of the resume holding the run's claim, if any. */
3226
+ async function liveResumeClaim(runId) {
3227
+ const owner = await (await resumeClaimStore(mastra))?.getRunOwnership({ runId: resumeClaimKey(runId) });
3228
+ return owner?.live ? owner : void 0;
3229
+ }
3230
+ /**
3231
+ * Claims a suspension read by `resume()` (`suspended` -> `running`) so no other resume, in this
3232
+ * process or another, dispatches it again (#27485, #27925). The lease is taken first and is the
3233
+ * mutex: a `running` snapshot without a live lease is a claim whose event never started, which
3234
+ * this resume takes over. Returns `undefined` when another resume got there first.
3235
+ */
3236
+ async function claimSuspension(runId, snapshot, toolCallId) {
3237
+ const store = await resumeClaimStore(mastra);
3238
+ if (!store || !snapshot.status) return { release: async () => {} };
3239
+ const key = resumeClaimKey(runId);
3240
+ const owner = await store.getRunOwnership({ runId: key });
3241
+ if (owner?.live) return void 0;
3242
+ const ownerId = `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/${toolCallId ?? ""}`;
3243
+ const lease = await store.claimRunOwnership({
3244
+ runId: key,
3245
+ ownerId,
3246
+ leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
3247
+ expectedGeneration: owner?.generation ?? 0
3248
+ });
3249
+ if (!lease.acquired) return void 0;
3250
+ const fence = {
3251
+ runId: key,
3252
+ generation: lease.record.generation,
3253
+ ownerId
3254
+ };
3255
+ const claimed = await setLoopStatus(store, runId, "running", snapshot.status);
3256
+ if (claimed?.timestamp !== snapshot.timestamp) {
3257
+ if (claimed && snapshot.status !== "running") await setLoopStatus(store, runId, "suspended", "running");
3258
+ await store.releaseRunOwnership(fence);
3259
+ return;
3260
+ }
3261
+ return {
3262
+ fence,
3263
+ release: async () => {
3264
+ if (!matchesRunFence(await store.getRunOwnership({ runId: key }), fence)) return;
3265
+ await setLoopStatus(store, runId, "suspended", "running");
3266
+ await store.releaseRunOwnership(fence);
3267
+ }
3268
+ };
3269
+ }
3270
+ /**
3271
+ * Throws unless this resume may wait for the live one holding the run: one resuming a different
3272
+ * call, or any resume once the holder's segment parked again in this process. Any other resume is a
3273
+ * duplicate, and waiting would hand its resume data to whatever the run suspends on next.
3274
+ */
3275
+ function assertMayWaitFor(owner, runId, toolCallId) {
3276
+ const [ownerProcess, , ...label] = owner.ownerId.split("/");
3277
+ const ownerToolCallId = label.join("/");
3278
+ if (ownerProcess === RESUME_CLAIM_PROCESS_ID && !inFlightToolCallResumes.get(runId)?.has(ownerToolCallId) || toolCallId && ownerToolCallId !== toolCallId) return;
3279
+ throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
3280
+ }
3048
3281
  /**
3049
3282
  * Tool calls and text from before the suspension, seeded into the resumed stream
3050
3283
  * so its `toolCalls` and `text` include them without replaying their chunks.
@@ -3343,6 +3576,7 @@ function createInngestAgent(options) {
3343
3576
  throw error;
3344
3577
  }
3345
3578
  }).catch(async (error) => {
3579
+ endRunSpansWithError(runId, error);
3346
3580
  await emitError(runId, error);
3347
3581
  await failStream(error);
3348
3582
  });
@@ -3395,6 +3629,11 @@ function createInngestAgent(options) {
3395
3629
  bgManager: mastra?.backgroundTaskManager
3396
3630
  });
3397
3631
  }
3632
+ const markedToolCallId = resumeOptions?.toolCallId ?? "";
3633
+ if (inFlightToolCallResumes.get(runId)?.has(markedToolCallId)) {
3634
+ if (!await resumeClaimStore(mastra) || await liveResumeClaim(runId)) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
3635
+ inFlightToolCallResumes.get(runId)?.delete(markedToolCallId);
3636
+ }
3398
3637
  const existingRegistryEntry = getRunRegistryEntry(runId, mastra);
3399
3638
  await (existingRegistryEntry?.workflowExecution)?.catch(() => {});
3400
3639
  const resumableSnapshot = (async () => {
@@ -3406,9 +3645,21 @@ function createInngestAgent(options) {
3406
3645
  });
3407
3646
  const toolCallId = resumeOptions?.toolCallId;
3408
3647
  let nestedSnapshot;
3648
+ let held = false;
3409
3649
  const isReady = async (s) => {
3410
3650
  nestedSnapshot = void 0;
3411
- if (s?.status !== "suspended" || toolCallId && !s.resumeLabels?.[toolCallId]) return false;
3651
+ held = false;
3652
+ const claimed = s?.status === "running" && Object.keys(s.suspendedPaths ?? {}).length > 0;
3653
+ if (s?.status !== "suspended" && !claimed) return false;
3654
+ const owner = await liveResumeClaim(runId);
3655
+ if (owner) {
3656
+ held = true;
3657
+ if (s.status !== "suspended") assertMayWaitFor(owner, runId, toolCallId);
3658
+ return false;
3659
+ }
3660
+ if (claimed && !await resumeClaimStore(mastra)) return false;
3661
+ if (toolCallId && !s.resumeLabels?.[toolCallId]) return false;
3662
+ if (s.activePaths?.length) return false;
3412
3663
  const labelIds = Object.keys(s.resumeLabels ?? {});
3413
3664
  if (labelIds.length === 0) return true;
3414
3665
  nestedSnapshot = await workflowsStore.loadWorkflowSnapshot({
@@ -3419,14 +3670,18 @@ function createInngestAgent(options) {
3419
3670
  };
3420
3671
  let snapshot = await loadSnapshot();
3421
3672
  const deadline = Date.now() + RESUME_SNAPSHOT_WAIT_MS;
3422
- while (!await isReady(snapshot) && Date.now() < deadline) {
3673
+ let ready;
3674
+ while (!(ready = await isReady(snapshot)) && Date.now() < deadline) {
3675
+ assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
3423
3676
  await new Promise((resolve) => setTimeout(resolve, RESUME_SNAPSHOT_POLL_MS));
3424
3677
  snapshot = await loadSnapshot();
3425
3678
  }
3426
3679
  return {
3427
3680
  hasStore: true,
3428
3681
  snapshot,
3429
- nestedSnapshot
3682
+ nestedSnapshot,
3683
+ ready,
3684
+ held
3430
3685
  };
3431
3686
  })();
3432
3687
  resumableSnapshot.catch(() => {});
@@ -3436,8 +3691,10 @@ function createInngestAgent(options) {
3436
3691
  requestContext: new RequestContext$1([...savedRequestContext, ...resumeOptions?.requestContext?.entries() ?? []])
3437
3692
  });
3438
3693
  validateModelTimeoutSettings(callbackOptions.modelSettings?.timeout);
3439
- const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot } = await resumableSnapshot;
3440
- if (hasStore && suspendedSnapshot?.status !== "suspended") throw new NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (suspendedSnapshot?.status ? ` (status: ${suspendedSnapshot.status}).` : " (no snapshot found)."));
3694
+ const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot, ready: snapshotReady, held } = await resumableSnapshot;
3695
+ const takeover = snapshotReady && suspendedSnapshot?.status === "running";
3696
+ if (held || !takeover && suspendedSnapshot?.status === "running" && Object.keys(suspendedSnapshot.suspendedPaths ?? {}).length) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
3697
+ if (hasStore && !takeover && suspendedSnapshot?.status !== "suspended") throw new NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (suspendedSnapshot?.status ? ` (status: ${suspendedSnapshot.status}).` : " (no snapshot found)."));
3441
3698
  const suspendedStepIds = suspendedSnapshot?.suspendedPaths ? Object.keys(suspendedSnapshot.suspendedPaths) : [];
3442
3699
  const resumeLabels = suspendedSnapshot?.resumeLabels ?? {};
3443
3700
  const expandToLeafPath = (stepId) => {
@@ -3448,7 +3705,7 @@ function createInngestAgent(options) {
3448
3705
  let steps;
3449
3706
  if (toolCallId) {
3450
3707
  const targetStepId = resumeLabels[toolCallId]?.stepId;
3451
- if (!targetStepId) {
3708
+ if (!targetStepId || nestedSnapshot && !nestedSnapshot.resumeLabels?.[toolCallId]) {
3452
3709
  const available = Object.keys(resumeLabels);
3453
3710
  throw new 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.`));
3454
3711
  }
@@ -3460,6 +3717,15 @@ function createInngestAgent(options) {
3460
3717
  }
3461
3718
  const resumeOffset = await getPubsubOffset(runId);
3462
3719
  const { toolCalls: initialToolCalls, resumedText } = await loadSuspendedIteration(runId, suspendedSnapshot, nestedSnapshot);
3720
+ const markKey = toolCallId ?? (await resumeClaimStore(mastra) ? "" : void 0);
3721
+ const releaseToolCallMarker = markKey === void 0 ? () => {} : markToolCallResume(runId, markKey);
3722
+ if (!releaseToolCallMarker) throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
3723
+ const claim = await claimSuspension(runId, suspendedSnapshot ?? {}, toolCallId);
3724
+ if (!claim) {
3725
+ releaseToolCallMarker();
3726
+ assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
3727
+ return proxyRef.resume(runId, resumeData, resumeOptions);
3728
+ }
3463
3729
  const abortController = new AbortController();
3464
3730
  const stopForwardingAbort = resumeOptions?.abortSignal ? forwardExternalAbort(resumeOptions.abortSignal, abortController, runId) : void 0;
3465
3731
  let existingEntry = existingRegistryEntry;
@@ -3513,6 +3779,7 @@ function createInngestAgent(options) {
3513
3779
  let resumeCleanedUp = false;
3514
3780
  const finalizeResumeRegistry = () => {
3515
3781
  clearTotalTimeout();
3782
+ releaseToolCallMarker();
3516
3783
  if (resumeCleanedUp) return;
3517
3784
  resumeCleanedUp = true;
3518
3785
  stopForwardingAbort?.();
@@ -3541,7 +3808,10 @@ function createInngestAgent(options) {
3541
3808
  requestContext: callbackOptions.requestContext,
3542
3809
  onChunk: (chunk) => {
3543
3810
  resumedChunkSeen = true;
3544
- if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") stopForwardingAbort?.();
3811
+ if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
3812
+ stopForwardingAbort?.();
3813
+ if (!toolCallId || chunk.payload.toolCallId === toolCallId) releaseToolCallMarker();
3814
+ }
3545
3815
  return callbackOptions.onChunk?.(chunk);
3546
3816
  },
3547
3817
  onStepFinish: callbackOptions.onStepFinish,
@@ -3562,6 +3832,7 @@ function createInngestAgent(options) {
3562
3832
  onSuspended: async (data) => {
3563
3833
  if (!resumedChunkSeen) return;
3564
3834
  clearTotalTimeout();
3835
+ releaseToolCallMarker();
3565
3836
  try {
3566
3837
  await callbackOptions.onSuspended?.(data);
3567
3838
  } finally {
@@ -3579,6 +3850,7 @@ function createInngestAgent(options) {
3579
3850
  });
3580
3851
  const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
3581
3852
  let notResumable = false;
3853
+ let sendStarted = false;
3582
3854
  const didThreadRunPublishTerminal = agentThreadStreamRuntime.captureThreadRunTerminalPublish(runId, agent.getPubSub());
3583
3855
  const dispatch = ready.then(async () => {
3584
3856
  const snapshot = suspendedSnapshot;
@@ -3593,7 +3865,9 @@ function createInngestAgent(options) {
3593
3865
  traceId: snapshot.tracingContext.traceId,
3594
3866
  parentSpanId: snapshot.tracingContext.spanId
3595
3867
  } : void 0;
3868
+ sendStarted = true;
3596
3869
  await inngest.send({
3870
+ ...snapshot?.timestamp && claim.fence ? { id: `${runId}:resume:${snapshot.timestamp}:${claim.fence.generation}` } : {},
3597
3871
  name: eventName,
3598
3872
  data: buildDurableResumeEventData({
3599
3873
  inputData: resumeData,
@@ -3605,7 +3879,9 @@ function createInngestAgent(options) {
3605
3879
  resume: {
3606
3880
  steps,
3607
3881
  resumePayload: resumeData,
3608
- resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0
3882
+ resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0,
3883
+ label: toolCallId,
3884
+ claim: claim.fence
3609
3885
  }
3610
3886
  })
3611
3887
  });
@@ -3619,6 +3895,7 @@ function createInngestAgent(options) {
3619
3895
  } catch (error) {
3620
3896
  streamCleanup();
3621
3897
  finalizeResumeRegistry();
3898
+ if (!sendStarted) await claim.release().catch((releaseError) => mastra?.getLogger?.()?.warn?.(`[InngestAgent] resume(${runId}) failed to release its claim`, releaseError));
3622
3899
  throw error;
3623
3900
  }
3624
3901
  const resumeMemory = resumeOptions?.memory;
@@ -4722,4 +4999,4 @@ function init(inngest) {
4722
4999
  }
4723
5000
  export { createServe as a, isInngestAgent as c, InngestRun as d, InngestPubSub as f, connect as i, createInngestDurableAgenticWorkflow as l, InngestExecutionEngine as m, init as n, serve$1 as o, OVERSIZED_EVENT_CHUNK_TYPE as p, _compatibilityCheck as r, createInngestAgent as s, createStep as t, InngestWorkflow as u };
4724
5001
 
4725
- //# sourceMappingURL=src-BdUtmnY0.js.map
5002
+ //# sourceMappingURL=src-Bw7re0-u.js.map