@mastra/inngest 1.8.7-alpha.0 → 1.8.7
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.
- package/CHANGELOG.md +22 -0
- package/dist/{connect-Buu9qcAs.cjs → connect-BC21XS-T.cjs} +46 -44
- package/dist/connect-BC21XS-T.cjs.map +1 -0
- package/dist/{connect-BnjpNupE.js → connect-D7Dro-2T.js} +46 -44
- package/dist/connect-D7Dro-2T.js.map +1 -0
- package/dist/connect.cjs +1 -1
- package/dist/connect.js +1 -1
- package/dist/durable-agent/create-inngest-agent.d.ts.map +1 -1
- package/dist/index.cjs +11 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/pubsub.d.ts.map +1 -1
- package/dist/run.d.ts.map +1 -1
- package/package.json +8 -8
- package/dist/connect-BnjpNupE.js.map +0 -1
- package/dist/connect-Buu9qcAs.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @mastra/inngest
|
|
2
2
|
|
|
3
|
+
## 1.8.7
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed Inngest workflow resumes failing when persisted state grows too large by restoring resume state from storage instead of copying it into events. ([#21549](https://github.com/mastra-ai/mastra/pull/21549))
|
|
8
|
+
|
|
9
|
+
- Fixed durable agent resumes to restore request context and continue the original trace after suspension. ([#21566](https://github.com/mastra-ai/mastra/pull/21566))
|
|
10
|
+
|
|
11
|
+
- Fixed durable Inngest streams retaining events after consumers unsubscribe and prevented internal workflow watch events from filling replay caches. ([#21572](https://github.com/mastra-ai/mastra/pull/21572))
|
|
12
|
+
|
|
13
|
+
- Updated dependencies [[`587f6ef`](https://github.com/mastra-ai/mastra/commit/587f6efcfc25880b93760a8607d1cd381ec612fe), [`7e096f0`](https://github.com/mastra-ai/mastra/commit/7e096f02f0dddbf09b85d306458351245ed2f886), [`d7e6745`](https://github.com/mastra-ai/mastra/commit/d7e67456954863c55440ea9c49bc6ceb9949972d), [`6223446`](https://github.com/mastra-ai/mastra/commit/6223446ddce6166e96e0ba5e00d628b615dee8ca), [`15101bb`](https://github.com/mastra-ai/mastra/commit/15101bb53c0d934f31af6b8813b88191e382a5e5), [`4e7a421`](https://github.com/mastra-ai/mastra/commit/4e7a421dce8a48742f785d1e93ad2f43a572b282), [`c2c3deb`](https://github.com/mastra-ai/mastra/commit/c2c3debcf670c7082d0a5e553aa99818a864698c), [`d8308a2`](https://github.com/mastra-ai/mastra/commit/d8308a2be3c07e777393d1017a381dcae3890d30), [`b0a2a07`](https://github.com/mastra-ai/mastra/commit/b0a2a07800d42bd9823292e7db832374ed084c9c), [`74e5bd3`](https://github.com/mastra-ai/mastra/commit/74e5bd315b8b3a1e04cb6cf480bb0f5fc4951dc8), [`242e324`](https://github.com/mastra-ai/mastra/commit/242e3241e73cbd5c9bb86a31ebb49ca0256488d4), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`d774e89`](https://github.com/mastra-ai/mastra/commit/d774e8930c781df8c9effe3763e6b501c099b6cc), [`9c27a53`](https://github.com/mastra-ai/mastra/commit/9c27a53cd9d3de4f3f025bc387d94ce371c33f95), [`8f0a332`](https://github.com/mastra-ai/mastra/commit/8f0a3321bf180368d76fe7b36aa1a8f60f00b6de), [`0b4f108`](https://github.com/mastra-ai/mastra/commit/0b4f1089aa8d92e67c2a8e99726822c5ee410784), [`9acb50f`](https://github.com/mastra-ai/mastra/commit/9acb50f71cec9c362f06820033f90ae6b1f8282f), [`46e9e3f`](https://github.com/mastra-ai/mastra/commit/46e9e3f73babe1bc70080a596cf2ac0b9da48519), [`3f9a190`](https://github.com/mastra-ai/mastra/commit/3f9a19057c027155867b9317294ee4ca7bd0581a), [`dff25a1`](https://github.com/mastra-ai/mastra/commit/dff25a1103fa72ee082a9b6f805ebeb5ce400753), [`6db7a5d`](https://github.com/mastra-ai/mastra/commit/6db7a5dd3dd2b6f7ef75dcd804fcffef5fa83963), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`583e235`](https://github.com/mastra-ai/mastra/commit/583e23519c13af16c1746f9c49722d011216611b), [`b098de9`](https://github.com/mastra-ai/mastra/commit/b098de9d7cb9f672e0883a5c716465a3a689693d), [`e8808e3`](https://github.com/mastra-ai/mastra/commit/e8808e3d8eb585a2565be53e56a7e0e1477352a4), [`a77f8d4`](https://github.com/mastra-ai/mastra/commit/a77f8d4740d2178a74c41e4bf678b4fcd8fa0bb2), [`7f78585`](https://github.com/mastra-ai/mastra/commit/7f785857e401570e2ffb316911f126ed363aa537), [`33374ba`](https://github.com/mastra-ai/mastra/commit/33374ba359e4fb13eaa918ae925fe167a3c55414), [`940bf5c`](https://github.com/mastra-ai/mastra/commit/940bf5ccf04f2c9ebd8a1390431733222a03b1cd), [`c549e2f`](https://github.com/mastra-ai/mastra/commit/c549e2f40edc1cac5d9e74e82f90da22b48df084), [`58c43d3`](https://github.com/mastra-ai/mastra/commit/58c43d3f7cb2eeaeb8ac733ae71dde822348e588), [`ef6e295`](https://github.com/mastra-ai/mastra/commit/ef6e295b59bc25a5b61b633a89c97bcfce9fb465), [`208e1b3`](https://github.com/mastra-ai/mastra/commit/208e1b39f30f4b386e494394e9d71d96f0f90241), [`c938d34`](https://github.com/mastra-ai/mastra/commit/c938d34739936c8ecbabd67ad6a4a4396f41c4c6), [`88ddc7c`](https://github.com/mastra-ai/mastra/commit/88ddc7ce01d40175f13a3228b789a906779680bd), [`f2a4afd`](https://github.com/mastra-ai/mastra/commit/f2a4afd7e37e809669001ed17724b341a5c1f45e), [`d438148`](https://github.com/mastra-ai/mastra/commit/d438148e222c1e2fb3c652725ce75680962ebec4), [`ba05fe0`](https://github.com/mastra-ai/mastra/commit/ba05fe0738f70cb686777546e968237d09269142), [`40d358e`](https://github.com/mastra-ai/mastra/commit/40d358e29d55543803e64b49241122f598ffabc7), [`d26a8d4`](https://github.com/mastra-ai/mastra/commit/d26a8d4281f28414715b333c85bedaf70d0b2890), [`e80cd7e`](https://github.com/mastra-ai/mastra/commit/e80cd7e7683e7d732e1cc6784bcac1d2640d2ce3), [`ccbbcd9`](https://github.com/mastra-ai/mastra/commit/ccbbcd974eedff4367a54ed0e24c9ee742ab2f61), [`1d9a0ea`](https://github.com/mastra-ai/mastra/commit/1d9a0ea4a9901baee6cd56737243bd6d1f631ac0), [`677cdc6`](https://github.com/mastra-ai/mastra/commit/677cdc6af564dec29a13464d12b7ab2a4efc22e9), [`c549e2f`](https://github.com/mastra-ai/mastra/commit/c549e2f40edc1cac5d9e74e82f90da22b48df084), [`a7dd322`](https://github.com/mastra-ai/mastra/commit/a7dd32247d95afc539f483ca37f4594af0387f59), [`3f5c6f7`](https://github.com/mastra-ai/mastra/commit/3f5c6f728ea35da344248de9aa070f12849f3aa0), [`a318490`](https://github.com/mastra-ai/mastra/commit/a318490e17da32f338d50929c770d901a9b3dd72), [`b860493`](https://github.com/mastra-ai/mastra/commit/b86049391100e665d579f700c8a2034c036defc3), [`d4be8c1`](https://github.com/mastra-ai/mastra/commit/d4be8c1739d22d621e3f78790e1dd5eb5ecc3589), [`a5d2eb1`](https://github.com/mastra-ai/mastra/commit/a5d2eb10347eade1ae2816d88f466c25186c54a5), [`3667679`](https://github.com/mastra-ai/mastra/commit/3667679db057edfb086846d13369fdda4902ad65), [`49696e8`](https://github.com/mastra-ai/mastra/commit/49696e8e42f870674a0a58f5abcd22cc54dd2864), [`2ef2f23`](https://github.com/mastra-ai/mastra/commit/2ef2f230a7aed342e7dc3b2000cd42e4c43e08a7), [`763e0c6`](https://github.com/mastra-ai/mastra/commit/763e0c61e04d76ad9a9efd301aa57525ca0cbea9), [`20504b2`](https://github.com/mastra-ai/mastra/commit/20504b2ecebd0e077acda3d457ab57480a98ed3e), [`77e6b1b`](https://github.com/mastra-ai/mastra/commit/77e6b1bc4c46ce94fe501023fb4393c812ec6be3), [`c5f964d`](https://github.com/mastra-ai/mastra/commit/c5f964d3f77064e978f8066ec506eed77ba5c63c), [`23e0be2`](https://github.com/mastra-ai/mastra/commit/23e0be261381e49534b4ff3101c60ee64a946cbf), [`7fc8806`](https://github.com/mastra-ai/mastra/commit/7fc880627d3cbf995d31ea0e8b807bf15417e651), [`0e02eac`](https://github.com/mastra-ai/mastra/commit/0e02eacdb2e30e1697a41910b41163742a181dc1), [`4df174c`](https://github.com/mastra-ai/mastra/commit/4df174c32bddf093a82f273070b8380aef7c9e90), [`f7c25b5`](https://github.com/mastra-ai/mastra/commit/f7c25b5106ddfb48e591f98df7a51e0f2dd01dba), [`7aad631`](https://github.com/mastra-ai/mastra/commit/7aad631b43bc10db77d5b8c66b200d7a49d18bf2), [`512100a`](https://github.com/mastra-ai/mastra/commit/512100a7d8b7e9c920f2590c6b3612f5de0d3cff), [`e81744c`](https://github.com/mastra-ai/mastra/commit/e81744cd13c46619c142dc521dc0baac47607a84), [`f8f653f`](https://github.com/mastra-ai/mastra/commit/f8f653f10980d01a73706cc3c8689ca5e40ce808), [`dc09cc1`](https://github.com/mastra-ai/mastra/commit/dc09cc1083d861cde192c1cd235324dc75b8c731), [`9ef432b`](https://github.com/mastra-ai/mastra/commit/9ef432b6faa534b57b0d182a610e13dd9a7123ff), [`36b4649`](https://github.com/mastra-ai/mastra/commit/36b4649045a3a380cbab8ceca866db4086223aff), [`b9cf308`](https://github.com/mastra-ai/mastra/commit/b9cf30846f97f99ac1906ee8a68f4f2d117b0378), [`2e1d098`](https://github.com/mastra-ai/mastra/commit/2e1d0984e325fd319d32ea182f596b3170be3847), [`377eb81`](https://github.com/mastra-ai/mastra/commit/377eb81ce43b964e3a6b541df172da74a8ff3716), [`1794a79`](https://github.com/mastra-ai/mastra/commit/1794a79178c418004a7261b1ad9114066f7ef01d), [`0cdc5dc`](https://github.com/mastra-ai/mastra/commit/0cdc5dc69024957815da4f51acc4119eb4f447d7), [`5740ec6`](https://github.com/mastra-ai/mastra/commit/5740ec60c760ffdfbfaa59d603d03b847c864e05)]:
|
|
14
|
+
- @mastra/core@1.60.0
|
|
15
|
+
|
|
16
|
+
## 1.8.7-alpha.1
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- Fixed durable Inngest streams retaining events after consumers unsubscribe and prevented internal workflow watch events from filling replay caches. ([#21572](https://github.com/mastra-ai/mastra/pull/21572))
|
|
21
|
+
|
|
22
|
+
- Updated dependencies [[`0b4f108`](https://github.com/mastra-ai/mastra/commit/0b4f1089aa8d92e67c2a8e99726822c5ee410784), [`88ddc7c`](https://github.com/mastra-ai/mastra/commit/88ddc7ce01d40175f13a3228b789a906779680bd), [`a7dd322`](https://github.com/mastra-ai/mastra/commit/a7dd32247d95afc539f483ca37f4594af0387f59)]:
|
|
23
|
+
- @mastra/core@1.60.0-alpha.6
|
|
24
|
+
|
|
3
25
|
## 1.8.7-alpha.0
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
|
@@ -691,30 +691,31 @@ var InngestPubSub = class extends _mastra_core_events.PubSub {
|
|
|
691
691
|
}
|
|
692
692
|
const callbacks = /* @__PURE__ */ new Set([cb]);
|
|
693
693
|
const inngestTopic = topicType === "agent" ? "agent-stream" : "watch";
|
|
694
|
-
const
|
|
694
|
+
const subscription = await (0, inngest_realtime.subscribe)({
|
|
695
695
|
channel: topicType === "agent" ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`,
|
|
696
696
|
topics: [inngestTopic],
|
|
697
|
-
app: this.inngest
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
697
|
+
app: this.inngest,
|
|
698
|
+
onMessage: (message) => {
|
|
699
|
+
let event;
|
|
700
|
+
if (topicType === "agent" && message.data?.type && message.data?.runId) event = {
|
|
701
|
+
id: crypto.randomUUID(),
|
|
702
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
703
|
+
...message.data
|
|
704
|
+
};
|
|
705
|
+
else event = {
|
|
706
|
+
id: crypto.randomUUID(),
|
|
707
|
+
type: inngestTopic,
|
|
708
|
+
runId,
|
|
709
|
+
data: message.data,
|
|
710
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
711
|
+
};
|
|
712
|
+
for (const callback of callbacks) callback(event);
|
|
713
|
+
}
|
|
713
714
|
});
|
|
714
715
|
this.subscriptions.set(topic, {
|
|
715
716
|
unsubscribe: () => {
|
|
716
717
|
try {
|
|
717
|
-
|
|
718
|
+
subscription.close();
|
|
718
719
|
} catch (err) {
|
|
719
720
|
console.error("InngestPubSub unsubscribe error:", err);
|
|
720
721
|
}
|
|
@@ -790,39 +791,40 @@ var InngestRun = class extends _mastra_core_workflows.Run {
|
|
|
790
791
|
reject(error);
|
|
791
792
|
}
|
|
792
793
|
};
|
|
793
|
-
let
|
|
794
|
+
let realtimeSubscriptionPromise = null;
|
|
794
795
|
const startRealtimeSubscription = async () => {
|
|
795
796
|
try {
|
|
796
|
-
|
|
797
|
+
realtimeSubscriptionPromise = (0, inngest_realtime.subscribe)({
|
|
797
798
|
channel: `workflow:${this.workflowId}:${this.runId}`,
|
|
798
799
|
topics: ["watch"],
|
|
799
|
-
app: this.inngest
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
800
|
+
app: this.inngest,
|
|
801
|
+
onMessage: async (message) => {
|
|
802
|
+
if (resolved) return;
|
|
803
|
+
const event = message.data;
|
|
804
|
+
if (event?.type === "workflow-finish") {
|
|
805
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
806
|
+
workflowName: this.workflowId,
|
|
807
|
+
runId: this.runId
|
|
808
|
+
});
|
|
809
|
+
if (snapshot?.context) snapshot.context = (0, _mastra_core_workflows.hydrateSerializedStepErrors)(snapshot.context);
|
|
810
|
+
const realtimeResult = {
|
|
811
|
+
steps: snapshot?.context,
|
|
812
|
+
status: event.payload?.status ?? snapshot?.status,
|
|
813
|
+
input: (snapshot?.context)?.input
|
|
814
|
+
};
|
|
815
|
+
const resultValue = event.payload?.result ?? snapshot?.result;
|
|
816
|
+
if (resultValue !== void 0) realtimeResult.result = resultValue;
|
|
817
|
+
const rawError = event.payload?.error ?? snapshot?.error;
|
|
818
|
+
if (rawError) realtimeResult.error = (0, _mastra_core_error.getErrorFromUnknown)(rawError, { serializeStack: false });
|
|
819
|
+
if (snapshot?.value !== void 0) realtimeResult.state = snapshot.value;
|
|
820
|
+
handleResult({ output: { result: realtimeResult } }, "realtime");
|
|
821
|
+
}
|
|
820
822
|
}
|
|
821
823
|
});
|
|
822
824
|
unsubscribe = () => {
|
|
823
|
-
|
|
825
|
+
realtimeSubscriptionPromise?.then((subscription) => subscription.close()).catch(() => {});
|
|
824
826
|
};
|
|
825
|
-
await
|
|
827
|
+
await realtimeSubscriptionPromise;
|
|
826
828
|
} catch {}
|
|
827
829
|
};
|
|
828
830
|
const startPolling = async () => {
|
|
@@ -1924,4 +1926,4 @@ Object.defineProperty(exports, "connect", {
|
|
|
1924
1926
|
}
|
|
1925
1927
|
});
|
|
1926
1928
|
|
|
1927
|
-
//# sourceMappingURL=connect-
|
|
1929
|
+
//# sourceMappingURL=connect-BC21XS-T.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-BC21XS-T.cjs","names":["MastraNonRetryableError","NonRetriableError","DefaultExecutionEngine","stepRes","PubSub","Run","inngest","#mastra","NonRetriableError","ReadableStream","ChunkFrom","WorkflowRunOutput","Workflow","#mastra","inngest","#pubsubFactory","RequestContext","SpanType","EntityType","NonRetriableError"],"sources":["../src/nested-workflow-output.ts","../src/execution-engine.ts","../src/pubsub.ts","../src/run.ts","../src/workflow.ts","../src/functions.ts","../src/connect.ts"],"sourcesContent":["import type { WorkflowResult } from '@mastra/core/workflows';\n\nexport const NESTED_WORKFLOW_OUTPUT_MODE = {\n DEFAULT: 'default',\n COMPACT: 'compact',\n} as const;\n\nexport type NestedWorkflowOutputMode = (typeof NESTED_WORKFLOW_OUTPUT_MODE)[keyof typeof NESTED_WORKFLOW_OUTPUT_MODE];\n\ntype AnyWorkflowResult = WorkflowResult<any, any, any, any>;\ntype WorkflowResultWithStatus<TStatus extends AnyWorkflowResult['status']> = Extract<\n AnyWorkflowResult,\n { status: TStatus }\n>;\n\nexport type NestedWorkflowResult =\n | Pick<WorkflowResultWithStatus<'success'>, 'status' | 'state' | 'result'>\n | Pick<WorkflowResultWithStatus<'failed'>, 'status' | 'state' | 'error'>\n | Pick<WorkflowResultWithStatus<'tripwire'>, 'status' | 'state' | 'tripwire'>\n | Pick<WorkflowResultWithStatus<'suspended'>, 'status' | 'state' | 'steps'>\n | Pick<WorkflowResultWithStatus<'paused'>, 'status' | 'state'>;\n\n/**\n * Normalizes an optional nested workflow output mode to an explicit mode.\n *\n * @param mode - The output mode requested by the invoking workflow.\n * @returns The requested compact mode, or the default mode when compact output was not requested.\n */\nexport function resolveNestedWorkflowOutputMode(\n mode: NestedWorkflowOutputMode | undefined = NESTED_WORKFLOW_OUTPUT_MODE.DEFAULT,\n): NestedWorkflowOutputMode {\n return mode === NESTED_WORKFLOW_OUTPUT_MODE.COMPACT\n ? NESTED_WORKFLOW_OUTPUT_MODE.COMPACT\n : NESTED_WORKFLOW_OUTPUT_MODE.DEFAULT;\n}\n\n/**\n * Keeps only the status-specific fields consumed by a parent workflow after\n * `step.invoke()`. Suspended results retain steps so the parent can construct\n * the nested resume path; completed results do not carry the child input or\n * internal step history into the parent's memoized run state.\n *\n * @param result - The complete result returned by the nested workflow.\n * @returns The status-specific fields required by the invoking parent workflow.\n */\nexport function compactNestedWorkflowResult(result: AnyWorkflowResult): NestedWorkflowResult {\n switch (result.status) {\n case 'success':\n return { status: result.status, result: result.result, state: result.state };\n case 'failed':\n return { status: result.status, error: result.error, state: result.state };\n case 'tripwire':\n return { status: result.status, tripwire: result.tripwire, state: result.state };\n case 'suspended':\n return { status: result.status, steps: result.steps, state: result.state };\n case 'paused':\n return { status: result.status, state: result.state };\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { ActorSignal } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { getErrorFromUnknown, MastraNonRetryableError } from '@mastra/core/error';\nimport type { SerializedError } from '@mastra/core/error';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { EntityType } from '@mastra/core/observability';\nimport { DefaultExecutionEngine, createTimeTravelExecutionParams } from '@mastra/core/workflows';\nimport type {\n ExecutionContext,\n Step,\n StepResult,\n StepFailure,\n ExecutionEngineOptions,\n TimeTravelExecutionParams,\n} from '@mastra/core/workflows';\nimport type { Inngest, BaseContext } from 'inngest';\nimport { NonRetriableError } from 'inngest';\nimport type { NestedWorkflowResult } from './nested-workflow-output';\nimport { NESTED_WORKFLOW_OUTPUT_MODE } from './nested-workflow-output';\nimport { InngestWorkflow } from './workflow';\n\nfunction isNonRetryableStepFailure(error: unknown): boolean {\n if (error instanceof MastraNonRetryableError || error instanceof NonRetriableError) {\n return true;\n }\n\n if (error instanceof Error && error.cause !== undefined && isNonRetryableStepFailure(error.cause)) {\n return true;\n }\n\n if (error && typeof error === 'object') {\n const record = error as {\n nonRetryable?: true;\n error?: unknown;\n name?: string;\n isNonRetryable?: boolean;\n };\n\n if (record.nonRetryable) {\n return true;\n }\n\n if (record.name === 'MastraNonRetryableError' || record.isNonRetryable) {\n return true;\n }\n\n if (record.error !== undefined && isNonRetryableStepFailure(record.error)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport class InngestExecutionEngine extends DefaultExecutionEngine {\n private inngestStep: BaseContext<Inngest>['step'];\n private inngestAttempts: number;\n\n constructor(\n mastra: Mastra,\n inngestStep: BaseContext<Inngest>['step'],\n inngestAttempts: number = 0,\n options: ExecutionEngineOptions,\n ) {\n super({ mastra, options });\n this.inngestStep = inngestStep;\n this.inngestAttempts = inngestAttempts;\n }\n\n // =============================================================================\n // Hook Overrides\n // =============================================================================\n\n /**\n * Format errors while preserving Error instances and their custom properties.\n * Uses getErrorFromUnknown to ensure all error properties are preserved.\n */\n protected formatResultError(\n error: Error | string | undefined,\n lastOutput: StepResult<any, any, any, any>,\n ): SerializedError {\n const outputError = (lastOutput as StepFailure<any, any, any, any>)?.error;\n const errorSource = error || outputError;\n const errorInstance = getErrorFromUnknown(errorSource, {\n serializeStack: true, // Include stack in JSON for better debugging in Inngest\n fallbackMessage: 'Unknown workflow error',\n });\n return errorInstance.toJSON();\n }\n\n /**\n * Detect InngestWorkflow instances for special nested workflow handling\n */\n isNestedWorkflowStep(step: Step<any, any, any>): boolean {\n return step instanceof InngestWorkflow;\n }\n\n /**\n * Inngest requires requestContext serialization for memoization.\n * When steps are replayed, the original function doesn't re-execute,\n * so requestContext modifications must be captured and restored.\n */\n requiresDurableContextSerialization(): boolean {\n return true;\n }\n\n /**\n * Execute a step with retry logic for Inngest.\n * Retries are handled via step-level retry (RetryAfterError thrown INSIDE step.run()).\n * After retries exhausted, error propagates here and we return a failed result.\n */\n async executeStepWithRetry<T>(\n stepId: string,\n runStep: () => Promise<T>,\n params: {\n retries: number;\n delay: number;\n stepSpan?: any;\n workflowId: string;\n runId: string;\n },\n ): Promise<\n | { ok: true; result: T }\n | { ok: false; error: { status: 'failed'; error: Error; endedAt: number; nonRetryable?: true } }\n > {\n for (let i = 0; i < params.retries + 1; i++) {\n if (i > 0 && params.delay) {\n await new Promise(resolve => setTimeout(resolve, params.delay));\n }\n try {\n //removed retry config with RetryAfterError from wrapDurableOperation, since we're manually handling retries here\n const result = await this.wrapDurableOperation(stepId, runStep);\n return { ok: true, result };\n } catch (e) {\n const isNonRetryable = isNonRetryableStepFailure(e);\n\n if (isNonRetryable || i === params.retries) {\n // After step-level retries exhausted, extract failure from error cause\n const cause = (e as any)?.cause;\n if (cause?.status === 'failed') {\n params.stepSpan?.error({\n error: e,\n attributes: { status: 'failed' },\n });\n // Ensure cause.error is an Error instance\n if (cause.error && !(cause.error instanceof Error)) {\n cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });\n }\n return {\n ok: false,\n error: {\n ...cause,\n ...(isNonRetryable && { nonRetryable: true as const }),\n },\n };\n }\n\n // Fallback for other errors - preserve the original error instance\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n params.stepSpan?.error({\n error: errorInstance,\n attributes: { status: 'failed' },\n });\n return {\n ok: false,\n error: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n ...(isNonRetryable && { nonRetryable: true as const }),\n },\n };\n }\n }\n }\n // Should never reach here, but TypeScript needs it\n return { ok: false, error: { status: 'failed', error: new Error('Unknown error'), endedAt: Date.now() } };\n }\n\n /**\n * Use Inngest's sleep primitive for durability\n */\n async executeSleepDuration(duration: number, sleepId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleep(`workflow.${workflowId}.sleep.${sleepId}`, duration < 0 ? 0 : duration);\n }\n\n /**\n * Use Inngest's sleepUntil primitive for durability\n */\n async executeSleepUntilDate(date: Date, sleepUntilId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleepUntil(`workflow.${workflowId}.sleepUntil.${sleepUntilId}`, date);\n }\n\n /**\n * Wrap durable operations in Inngest step.run() for durability.\n *\n * IMPORTANT: Errors are wrapped with a cause structure before throwing.\n * This is necessary because Inngest's error serialization (serialize-error-cjs)\n * only captures standard Error properties (message, name, stack, code, cause).\n * Custom properties like statusCode, responseHeaders from AI SDK errors would\n * be lost. By putting our serialized error (via getErrorFromUnknown with toJSON())\n * in the cause property, we ensure custom properties survive serialization.\n * The cause property is in serialize-error-cjs's allowlist, and when the cause\n * object is finally JSON.stringify'd, our error's toJSON() is called.\n */\n async wrapDurableOperation<T>(operationId: string, operationFn: () => Promise<T>): Promise<T> {\n const result = await this.inngestStep.run(operationId, async () => {\n try {\n const fnResult = await operationFn();\n return fnResult;\n } catch (e) {\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n const isNonRetryable = isNonRetryableStepFailure(e);\n throw new Error(errorInstance.message, {\n cause: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n ...(isNonRetryable && { nonRetryable: true as const }),\n },\n });\n }\n });\n return result as T;\n }\n\n /**\n * Provide Inngest step primitive in engine context\n */\n getEngineContext(): Record<string, any> {\n return { step: this.inngestStep };\n }\n\n /**\n * For Inngest, lifecycle callbacks are invoked in the workflow's finalize step\n * (wrapped in step.run for durability), not in execute(). Override to skip.\n */\n public async invokeLifecycleCallbacks(_result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n // No-op: Inngest handles callbacks in workflow.ts finalize step\n }\n\n /**\n * Actually invoke the lifecycle callbacks. Called from workflow.ts finalize step.\n */\n public async invokeLifecycleCallbacksInternal(result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n return super.invokeLifecycleCallbacks(result);\n }\n\n // =============================================================================\n // Durable Span Lifecycle Hooks\n // =============================================================================\n\n /**\n * Create a step span durably - on first execution, creates and exports span.\n * On replay, returns cached span data without re-creating.\n */\n async createStepSpan(params: {\n parentSpan: any;\n stepId: string;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n entityType?: string;\n entityId?: string;\n tracingPolicy?: any;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided (e.g., for steps inside control-flow),\n // otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n entityType: options.entityType as EntityType | undefined,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a step span durably.\n */\n async endStepSpan(params: {\n span: any;\n operationId: string;\n endOptions: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on step span durably.\n */\n async errorStepSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Create a generic child span durably (for control-flow operations).\n * On first execution, creates and exports span. On replay, returns cached span data.\n */\n async createChildSpan(params: {\n parentSpan: any;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n attributes?: Record<string, unknown>;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided, otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n tracingPolicy: this.options?.tracingPolicy,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a generic child span durably (for control-flow operations).\n */\n async endChildSpan(params: {\n span: any;\n operationId: string;\n endOptions?: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on a generic child span durably (for control-flow operations).\n */\n async errorChildSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Execute nested InngestWorkflow using inngestStep.invoke() for durability.\n * This MUST be called directly (not inside step.run()) due to Inngest constraints.\n *\n * @param params - The nested workflow step and its current execution state.\n * @returns The nested workflow step result, or null when the step is not an Inngest workflow.\n */\n async executeWorkflowStep(params: {\n step: Step<string, any, any>;\n stepResults: Record<string, StepResult<any, any, any, any>>;\n executionContext: ExecutionContext;\n resume?: {\n steps: string[];\n resumePayload: any;\n runId?: string;\n };\n timeTravel?: TimeTravelExecutionParams;\n prevOutput: any;\n inputData: any;\n pubsub: PubSub;\n startedAt: number;\n perStep?: boolean;\n stepSpan?: any;\n actor?: ActorSignal;\n requestContext?: RequestContext;\n }): Promise<StepResult<any, any, any, any> | null> {\n // Only handle InngestWorkflow instances\n if (!(params.step instanceof InngestWorkflow)) {\n return null;\n }\n\n const {\n step,\n stepResults,\n executionContext,\n resume,\n timeTravel,\n prevOutput,\n inputData,\n pubsub,\n startedAt,\n perStep,\n stepSpan,\n actor,\n requestContext: parentRequestContext,\n } = params;\n const forwardedRequestContext = parentRequestContext\n ? this.serializeRequestContext(parentRequestContext)\n : (inputData?.requestContextEntries ?? {});\n\n // Build trace context to propagate to nested workflow\n const nestedTracingContext = executionContext.tracingIds?.traceId\n ? {\n traceId: executionContext.tracingIds.traceId,\n parentSpanId: stepSpan?.id,\n }\n : undefined;\n\n const isResume = !!resume?.steps?.length;\n // New invocations return compact output; legacy memoized WorkflowResult\n // envelopes are structural supersets of this parent-facing contract.\n let result: NestedWorkflowResult;\n let runId: string;\n\n const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);\n\n try {\n if (isResume) {\n runId = stepResults[resume?.steps?.[0] ?? '']?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: runId,\n });\n\n const nestedResumeSteps = resume.steps.slice(1);\n if (nestedResumeSteps.length === 0) {\n const suspendedStepIds = Object.keys(snapshot?.suspendedPaths ?? {});\n if (suspendedStepIds.length === 0) {\n throw new Error(`No suspended steps found in nested workflow: ${step.id}`);\n }\n if (suspendedStepIds.length > 1) {\n const pathStrings = suspendedStepIds.map(stepId => `[${stepId}]`);\n throw new Error(\n `Multiple suspended steps found: ${pathStrings.join(', ')}. ` +\n 'Please specify which step to resume using the \"step\" parameter.',\n );\n }\n nestedResumeSteps.push(suspendedStepIds[0]!);\n }\n const nestedResumeStepId = nestedResumeSteps[0];\n\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n requestContext: forwardedRequestContext,\n runId: runId,\n resume: {\n runId: runId,\n steps: nestedResumeSteps,\n resumePayload: resume.resumePayload,\n resumePath: nestedResumeStepId ? (snapshot?.suspendedPaths?.[nestedResumeStepId] as any) : undefined,\n },\n outputOptions: { includeState: true },\n nestedWorkflowOutputMode: NESTED_WORKFLOW_OUTPUT_MODE.COMPACT,\n perStep,\n tracingOptions: nestedTracingContext,\n actor,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else if (isTimeTravel) {\n const workflowsStoreForTimeTravel = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = (await workflowsStoreForTimeTravel?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: executionContext.runId,\n })) ?? { context: {} };\n const timeTravelParams = createTimeTravelExecutionParams({\n steps: timeTravel.steps.slice(1),\n inputData: timeTravel.inputData,\n resumeData: timeTravel.resumeData,\n context: (timeTravel.nestedStepResults?.[step.id] ?? {}) as any,\n nestedStepsContext: (timeTravel.nestedStepResults ?? {}) as any,\n snapshot,\n graph: step.buildExecutionGraph(),\n });\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n timeTravel: timeTravelParams,\n initialState: executionContext.state ?? {},\n requestContext: forwardedRequestContext,\n runId: executionContext.runId,\n outputOptions: { includeState: true },\n nestedWorkflowOutputMode: NESTED_WORKFLOW_OUTPUT_MODE.COMPACT,\n perStep,\n tracingOptions: nestedTracingContext,\n actor,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else {\n // Name the child run on its trigger event. `cancelOn` matches a cancel\n // event against `data.runId` on the trigger, so a nested run invoked\n // without one cannot be cancelled by id — and it would take the\n // unnamed-run branch, warning about advice the caller cannot act on.\n const nestedRunId = randomUUID();\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? {},\n requestContext: forwardedRequestContext,\n runId: nestedRunId,\n outputOptions: { includeState: true },\n nestedWorkflowOutputMode: NESTED_WORKFLOW_OUTPUT_MODE.COMPACT,\n perStep,\n tracingOptions: nestedTracingContext,\n actor,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n }\n } catch (e) {\n // Nested workflow threw an error (likely from finalization step).\n // Compact nested failures carry the workflow result and runId in the cause.\n const errorCause = e && typeof e === 'object' && 'cause' in e ? e.cause : undefined;\n\n // Try to extract runId from error cause or generate new one\n if (errorCause && typeof errorCause === 'object' && 'status' in errorCause && errorCause.status === 'failed') {\n result = errorCause as Extract<NestedWorkflowResult, { status: 'failed' }>;\n runId = 'runId' in errorCause && typeof errorCause.runId === 'string' ? errorCause.runId : randomUUID();\n } else {\n // Fallback: if we can't get the result from error, construct a basic failed result\n runId = randomUUID();\n result = {\n status: 'failed',\n error: e instanceof Error ? e : new Error(String(e)),\n };\n }\n }\n\n const res = await this.inngestStep.run(\n `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,\n async () => {\n if (result.status === 'failed') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'failed',\n error: result?.error,\n payload: prevOutput,\n },\n },\n });\n\n return { executionContext, result: { status: 'failed', error: result?.error, endedAt: Date.now() } };\n } else if (result.status === 'suspended') {\n const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {\n const stepRes: StepResult<any, any, any, any> = stepResult as StepResult<any, any, any, any>;\n return stepRes?.status === 'suspended';\n });\n\n for (const [stepName, stepResult] of suspendedSteps) {\n const suspendPath: string[] = [stepName, ...(stepResult?.suspendPayload?.__workflow_meta?.path ?? [])];\n executionContext.suspendedPaths[step.id] = executionContext.executionPath;\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-suspended',\n payload: {\n id: step.id,\n status: 'suspended',\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: stepResult.payload,\n suspendPayload: {\n ...(stepResult as any)?.suspendPayload,\n __workflow_meta: { runId: runId, path: suspendPath },\n },\n },\n };\n }\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: {},\n },\n };\n } else if (result.status === 'tripwire') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'tripwire',\n error: result?.tripwire?.reason,\n payload: prevOutput,\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'tripwire',\n tripwire: result?.tripwire,\n endedAt: Date.now(),\n },\n };\n } else if (perStep || result.status === 'paused') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'paused',\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n return { executionContext, result: { status: 'paused' } };\n }\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'success',\n output: result?.result,\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n\n return { executionContext, result: { status: 'success', output: result?.result, endedAt: Date.now() } };\n },\n );\n\n Object.assign(executionContext, res.executionContext);\n return {\n ...res.result,\n startedAt,\n payload: inputData,\n resumedAt: resume?.steps[0] === step.id ? startedAt : undefined,\n resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : undefined,\n } as StepResult<any, any, any, any>;\n }\n}\n","import { PubSub } from '@mastra/core/events';\nimport type { Event } from '@mastra/core/events';\nimport type { Inngest } from 'inngest';\nimport { subscribe } from 'inngest/realtime';\n\n/**\n * Build a TopicRef compatible with Inngest SDK v4's `inngest.realtime.publish()`.\n * The runtime only requires `channel` and `topic`; `config.schema` is optional and\n * we leave it absent so no validation runs.\n */\nfunction buildTopicRef(channel: string, topic: string) {\n return { channel, topic, config: {} as any };\n}\n\n/**\n * Parse a topic string and extract the runId and topic type.\n *\n * Supported formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * - \"agent.stream.{runId}\" - agent stream events\n *\n * @returns { runId, topicType } or null if not a recognized format\n */\nfunction parseTopic(topic: string): { runId: string; topicType: 'workflow' | 'agent' } | null {\n // Try workflow format first\n const workflowMatch = topic.match(/^workflow\\.events\\.v2\\.(.+)$/);\n if (workflowMatch && workflowMatch[1]) {\n return { runId: workflowMatch[1], topicType: 'workflow' };\n }\n\n // Try agent stream format\n const agentMatch = topic.match(/^agent\\.stream\\.(.+)$/);\n if (agentMatch && agentMatch[1]) {\n return { runId: agentMatch[1], topicType: 'agent' };\n }\n\n return null;\n}\n\n/**\n * PubSub implementation for Inngest workflows.\n *\n * This bridges the PubSub abstract class interface with Inngest's realtime system:\n * - publish() uses `inngest.realtime.publish()` (Inngest SDK v4 client API).\n * This is non-durable: it executes immediately and is not memoized as a step.\n * When called inside an Inngest function it auto-includes the current runId.\n * - subscribe() uses `inngest/realtime` subscribe for real-time streaming.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> Inngest channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events (for InngestAgent)\n * -> Inngest channel: \"agent:{runId}\", topic: \"agent-stream\"\n */\nexport class InngestPubSub extends PubSub {\n private inngest: Inngest;\n private workflowId: string;\n private subscriptions: Map<\n string,\n {\n unsubscribe: () => void;\n callbacks: Set<(event: Event, ack?: () => Promise<void>) => void>;\n }\n > = new Map();\n\n constructor(inngest: Inngest, workflowId: string) {\n super();\n this.inngest = inngest;\n this.workflowId = workflowId;\n }\n\n /**\n * Publish an event to Inngest's realtime system.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events\n * -> channel: \"agent:{runId}\", topic: \"agent-stream\"\n * (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)\n */\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Use different Inngest topics and channels for different event types\n // Agent stream events use a runId-only channel so nested workflows publish to the same channel\n const inngestTopic = topicType === 'agent' ? 'agent-stream' : 'watch';\n const channel = topicType === 'agent' ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n try {\n // For agent stream events, send the full event structure so subscribers can access type/runId/data\n // For workflow events, send just the data (existing behavior)\n const dataToSend = topicType === 'agent' ? event : event.data;\n await this.inngest.realtime.publish(buildTopicRef(channel, inngestTopic), dataToSend);\n } catch (err: any) {\n // For agent stream terminal events, rethrow — losing a finish/error event\n // causes the client stream to hang indefinitely\n if (topicType === 'agent' && (event.type === 'finish' || event.type === 'error')) {\n throw err;\n }\n // Non-terminal events: log but don't throw\n console.error('InngestPubSub publish error:', err?.message ?? err);\n }\n }\n\n /**\n * Subscribe to events from Inngest's realtime system.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events\n * -> channel: \"agent:{runId}\", topic: \"agent-stream\"\n * (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)\n */\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Check if we already have a subscription for this topic\n if (this.subscriptions.has(topic)) {\n this.subscriptions.get(topic)!.callbacks.add(cb);\n return;\n }\n\n const callbacks = new Set<(event: Event, ack?: () => Promise<void>) => void>([cb]);\n\n // Use different Inngest topics and channels for different event types\n // Agent stream events use a runId-only channel so nested workflows publish to the same channel\n const inngestTopic = topicType === 'agent' ? 'agent-stream' : 'watch';\n const channel = topicType === 'agent' ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n // Await the subscribe call to ensure the WebSocket connection is established\n // before we consider the subscription \"ready\". This prevents race conditions\n // where the workflow triggers before the subscription can receive events.\n const subscription = await subscribe({\n channel,\n topics: [inngestTopic],\n app: this.inngest,\n onMessage: (message: any) => {\n // For agent stream events, message.data is the full AgentStreamEvent structure (type, runId, data)\n // For workflow events, wrap message.data in a PubSub Event format\n // IMPORTANT: Always generate a unique `id` and `createdAt` for every event.\n // CachingPubSub deduplicates events by `id` — without a unique id, all events\n // after the first would be filtered out (since undefined === undefined in the seen set).\n let event: Event;\n if (topicType === 'agent' && message.data?.type && message.data?.runId) {\n // Agent stream event - spread the AgentStreamEvent data and add required Event fields\n event = {\n id: crypto.randomUUID(),\n createdAt: new Date(),\n ...message.data,\n } as unknown as Event;\n } else {\n // Workflow event or fallback - wrap in standard Event format\n event = {\n id: crypto.randomUUID(),\n type: inngestTopic,\n runId,\n data: message.data,\n createdAt: new Date(),\n };\n }\n\n for (const callback of callbacks) {\n callback(event);\n }\n },\n });\n\n this.subscriptions.set(topic, {\n unsubscribe: () => {\n try {\n void subscription.close();\n } catch (err) {\n console.error('InngestPubSub unsubscribe error:', err);\n }\n },\n callbacks,\n });\n }\n\n /**\n * Unsubscribe a callback from a topic.\n * If no callbacks remain, the underlying Inngest subscription is cancelled.\n */\n async unsubscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const sub = this.subscriptions.get(topic);\n if (!sub) {\n return;\n }\n\n sub.callbacks.delete(cb);\n\n // If no more callbacks, cancel the subscription\n if (sub.callbacks.size === 0) {\n sub.unsubscribe();\n this.subscriptions.delete(topic);\n }\n }\n\n /**\n * Flush any pending operations. No-op for Inngest.\n */\n async flush(): Promise<void> {\n // No-op for Inngest\n }\n\n /**\n * Clean up all subscriptions during graceful shutdown.\n */\n async close(): Promise<void> {\n for (const [, sub] of this.subscriptions) {\n sub.unsubscribe();\n }\n this.subscriptions.clear();\n }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport type { ActorSignal } from '@mastra/core/auth/ee';\nimport { getErrorFromUnknown } from '@mastra/core/error';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { TracingContext, TracingOptions } from '@mastra/core/observability';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { WorkflowRunOutput, ChunkFrom } from '@mastra/core/stream';\nimport { createTimeTravelExecutionParams, Run, hydrateSerializedStepErrors } from '@mastra/core/workflows';\nimport type {\n ExecutionEngine,\n ExecutionGraph,\n OutputWriter,\n SerializedStepFlowEntry,\n Step,\n StepWithComponent,\n StreamEvent,\n TimeTravelContext,\n WorkflowEngineType,\n WorkflowResult,\n WorkflowStreamEvent,\n} from '@mastra/core/workflows';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport { subscribe } from 'inngest/realtime';\nimport type { Realtime } from 'inngest/realtime';\nimport type { InngestEngineType } from './types';\n\nexport class InngestRun<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TRequestContext = unknown,\n> extends Run<TEngineType, TSteps, TState, TInput, TOutput, TRequestContext> {\n private inngest: Inngest;\n serializedStepGraph: SerializedStepFlowEntry[];\n #mastra: Mastra;\n\n constructor(\n params: {\n workflowId: string;\n runId: string;\n resourceId?: string;\n executionEngine: ExecutionEngine;\n executionGraph: ExecutionGraph;\n serializedStepGraph: SerializedStepFlowEntry[];\n mastra?: Mastra;\n retryConfig?: {\n attempts?: number;\n delay?: number;\n };\n cleanup?: () => void;\n workflowSteps: Record<string, StepWithComponent>;\n workflowEngineType: WorkflowEngineType;\n validateInputs?: boolean;\n },\n inngest: Inngest,\n ) {\n super(params);\n this.inngest = inngest;\n this.serializedStepGraph = params.serializedStepGraph;\n this.#mastra = params.mastra!;\n }\n\n /**\n * Get run output using hybrid approach: realtime subscription + polling fallback.\n * Resolves as soon as either method detects completion.\n */\n async getRunOutput(_eventId: string, maxWaitMs = 300000) {\n const storage = this.#mastra?.getStorage();\n const workflowsStore = await storage?.getStore('workflows');\n if (!workflowsStore) {\n throw new NonRetriableError(`Workflow storage is required to retrieve output for run ${this.runId}`);\n }\n return new Promise<any>((resolve, reject) => {\n let resolved = false;\n let unsubscribe: (() => void) | null = null;\n let pollTimeoutId: NodeJS.Timeout | null = null;\n\n const cleanup = () => {\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch {\n // Ignore unsubscribe errors\n }\n }\n if (pollTimeoutId) {\n clearTimeout(pollTimeoutId);\n }\n };\n\n const handleResult = (result: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve(result);\n }\n };\n\n const handleError = (error: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(error);\n }\n };\n\n // Start realtime subscription for workflow-finish event\n let realtimeSubscriptionPromise: Promise<Realtime.Subscribe.CallbackSubscription> | null = null;\n\n const startRealtimeSubscription = async () => {\n try {\n realtimeSubscriptionPromise = subscribe({\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n onMessage: async (message: any) => {\n if (resolved) return;\n\n const event = message.data;\n\n if (event?.type === 'workflow-finish') {\n // Got the finish event - load snapshot and resolve\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot?.context) {\n snapshot.context = hydrateSerializedStepErrors(snapshot.context);\n }\n\n const realtimeResult: Record<string, unknown> = {\n steps: snapshot?.context,\n status: event.payload?.status ?? snapshot?.status,\n input: (snapshot?.context as Record<string, unknown>)?.input,\n };\n const resultValue = event.payload?.result ?? snapshot?.result;\n if (resultValue !== undefined) realtimeResult.result = resultValue;\n const rawError = event.payload?.error ?? snapshot?.error;\n if (rawError) {\n realtimeResult.error = getErrorFromUnknown(rawError, { serializeStack: false });\n }\n if (snapshot?.value !== undefined) realtimeResult.state = snapshot.value;\n const result = { output: { result: realtimeResult } };\n\n handleResult(result, 'realtime');\n }\n },\n });\n\n // Set unsubscribe immediately so cleanup can close the subscription even before setup resolves.\n unsubscribe = () => {\n realtimeSubscriptionPromise?.then(subscription => subscription.close()).catch(() => {});\n };\n\n await realtimeSubscriptionPromise;\n } catch {\n // Realtime subscription failed - polling will still work as fallback\n }\n };\n\n // Start polling by checking our own workflow snapshot store directly.\n // This avoids the Inngest runs API which has a 15-second response cache.\n const startPolling = async () => {\n const startTime = Date.now();\n\n const poll = async () => {\n if (resolved) {\n return;\n }\n if (Date.now() - startTime >= maxWaitMs) {\n handleError(new NonRetriableError(`Workflow did not complete within ${maxWaitMs}ms`), 'polling-timeout');\n return;\n }\n\n try {\n const snapshot = await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n // Still running or in an intermediate state — schedule next poll\n // 'running' = initial state, 'waiting' = sleeping/waiting, 'pending' = not yet started\n if (\n !snapshot ||\n snapshot.status === 'running' ||\n snapshot.status === 'waiting' ||\n snapshot.status === 'pending'\n ) {\n pollTimeoutId = setTimeout(poll, 150 + Math.random() * 100);\n return;\n }\n\n if (snapshot.context) {\n snapshot.context = hydrateSerializedStepErrors(snapshot.context);\n }\n\n const pollingResult: Record<string, unknown> = {\n steps: snapshot.context,\n status: snapshot.status,\n input: (snapshot.context as Record<string, unknown>)?.input,\n };\n if (snapshot.result !== undefined) pollingResult.result = snapshot.result;\n if (snapshot.error !== undefined) {\n pollingResult.error = getErrorFromUnknown(snapshot.error, { serializeStack: false });\n }\n if (snapshot.value !== undefined) pollingResult.state = snapshot.value;\n\n handleResult({ output: { result: pollingResult } }, `polling-${snapshot.status}`);\n } catch (error) {\n if (error instanceof NonRetriableError) {\n handleError(error, 'polling-non-retriable');\n return;\n }\n handleError(\n new NonRetriableError(\n `Failed to poll workflow status: ${error instanceof Error ? error.message : String(error)}`,\n ),\n 'polling-error',\n );\n }\n };\n\n // Start first poll\n void poll();\n };\n\n // Start both in parallel\n void startRealtimeSubscription();\n void startPolling();\n });\n }\n\n async cancel() {\n const storage = this.#mastra?.getStorage();\n\n await this.inngest.send({\n name: `cancel.workflow.${this.workflowId}`,\n data: {\n runId: this.runId,\n },\n });\n\n const workflowsStore = await storage?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot) {\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n ...snapshot,\n status: 'canceled' as any,\n value: snapshot.value,\n },\n });\n }\n }\n\n async start(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n outputWriter?: OutputWriter;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n return this._start(args);\n }\n\n /**\n * Starts the workflow execution without waiting for completion (fire-and-forget).\n * Returns immediately with the runId after sending the event to Inngest.\n * The workflow executes independently in Inngest.\n * Use this when you don't need to wait for the result or want to avoid polling failures.\n */\n async startAsync(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<{ runId: string }> {\n // Persist initial snapshot\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n // Validate inputs\n const inputDataToUse = await this._validateInput(args.inputData);\n const initialStateToUse = await this._validateInitialState(args.initialState ?? ({} as TState));\n\n // Send event to Inngest (fire-and-forget)\n const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions: args.outputOptions,\n tracingOptions: args.tracingOptions,\n requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},\n actor: args.actor,\n perStep: args.perStep,\n },\n });\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n\n // Return immediately - NO POLLING\n return { runId: this.runId };\n }\n\n async _start({\n inputData,\n initialState,\n outputOptions,\n tracingOptions,\n format,\n requestContext,\n actor,\n perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n initialState?: TState;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n format?: 'legacy' | 'vnext' | undefined;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n const inputDataToUse = await this._validateInput(inputData);\n const initialStateToUse = await this._validateInitialState(initialState ?? ({} as TState));\n\n const eventName = `workflow.${this.workflowId}`;\n\n const eventOutput = await this.inngest.send({\n name: eventName,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions,\n tracingOptions,\n format,\n requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {},\n actor,\n perStep,\n },\n });\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n\n const runOutput = await this.getRunOutput(eventId);\n const result = runOutput?.output?.result;\n\n this.hydrateFailedResult(result);\n\n // Only include state when explicitly requested, matching core engine behavior\n if (!outputOptions?.includeState) {\n delete result.state;\n }\n\n if (result.status !== 'suspended') {\n this.cleanup?.();\n }\n return result;\n }\n\n async resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const p = this._resume(params).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n this.executionResults = p;\n return p;\n }\n\n /**\n * Performs all resume preparation and dispatches the resume event to Inngest,\n * but does NOT wait for the workflow result. Shared by `_resume()` (which polls\n * for the result afterwards) and `resumeAsync()` (which returns immediately).\n *\n * Send-time failures (invalid resume data, event send failure) reject synchronously,\n * and the snapshot is rolled back to its prior state on send failure.\n */\n async _resumeAndSendEvent<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<{ eventId: string }> {\n const storage = this.#mastra?.getStorage();\n\n const workflowsStore = await storage?.getStore('workflows');\n if (!workflowsStore) {\n throw new NonRetriableError(`Workflow storage is required to resume run ${this.runId}`);\n }\n const snapshot = await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (!snapshot) {\n throw new NonRetriableError(`Cannot resume run ${this.runId}: snapshot not found`);\n }\n\n // Support label-based resume: look up step from resumeLabels\n const snapshotResumeLabel = params.label ? snapshot.resumeLabels?.[params.label] : undefined;\n const stepParam = snapshotResumeLabel?.stepId ?? params.step;\n\n let steps: string[] = [];\n if (stepParam) {\n if (typeof stepParam === 'string') {\n steps = stepParam.split('.');\n } else {\n steps = (Array.isArray(stepParam) ? stepParam : [stepParam]).map(step =>\n typeof step === 'string' ? step : step?.id,\n );\n }\n }\n\n const suspendedStep = this.workflowSteps[steps?.[0] ?? ''];\n\n const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);\n\n // Merge persisted requestContext from snapshot with any new values from params\n const persistedRequestContext = (snapshot as any)?.requestContext ?? {};\n const newRequestContext = params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {};\n const mergedRequestContext = { ...persistedRequestContext, ...newRequestContext };\n\n // Mark the snapshot as 'running' before sending the event so that\n // snapshot-based polling doesn't return the stale suspended/paused result.\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n ...snapshot,\n status: 'running',\n result: undefined,\n error: undefined,\n timestamp: Date.now(),\n } as any,\n });\n\n let eventOutput;\n try {\n eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: resumeDataToUse,\n runId: this.runId,\n workflowId: this.workflowId,\n resume: {\n steps,\n resumePayload: resumeDataToUse,\n resumePath: steps?.[0] ? (snapshot?.suspendedPaths?.[steps?.[0]] as any) : undefined,\n },\n requestContext: mergedRequestContext,\n // `actor` is a per-call trust signal, not rehydrated from the snapshot like\n // `requestContext` is above. This intentionally matches the default engine,\n // which passes `actor: params.actor` on resume and never reads it from the\n // snapshot (see packages/core/src/workflows/workflow.ts `_resume`). The caller\n // (a trusted background system) re-supplies `actor` on each resume; we never\n // persist a membership-bypass signal into durable storage.\n actor: params.actor,\n perStep: params.perStep,\n },\n });\n } catch (err) {\n // Rollback: restore the original snapshot so the run isn't stuck in 'running'.\n // The rollback itself can fail (e.g. transient storage error); log it but\n // always rethrow the original error so the underlying failure isn't masked.\n try {\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: snapshot as any,\n });\n } catch (rollbackErr) {\n console.error('Failed to rollback snapshot during resume error recovery:', rollbackErr);\n }\n throw err;\n }\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n\n return { eventId };\n }\n\n async _resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const { eventId } = await this._resumeAndSendEvent(params);\n const runOutput = await this.getRunOutput(eventId);\n const result = runOutput?.output?.result;\n this.hydrateFailedResult(result);\n return result;\n }\n\n /**\n * Resumes a suspended workflow without waiting for completion (fire-and-forget).\n * Returns immediately with the runId after sending the resume event to Inngest.\n * The workflow continues executing independently in Inngest.\n *\n * Mirrors `startAsync()`: send-time failures (invalid resume data, event send\n * failure) still reject synchronously and roll back the snapshot, but the result\n * is never polled via `getRunOutput()`. This avoids the polling-based 404 race when\n * you don't need the resolved result inline.\n *\n * NOTE: this is exposed over HTTP / the client SDK as `resume-no-wait` / `resumeNoWait()`,\n * not `resumeAsync`, because the existing `resumeAsync()` client/server surface awaits the\n * full workflow result. TODO(v2): consolidate so `resumeAsync` consistently means\n * fire-and-forget across core, client SDK and HTTP routes (breaking change deferred to v2).\n */\n async resumeAsync<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<{ runId: string }> {\n await this._resumeAndSendEvent(params);\n // Return immediately - NO POLLING\n return { runId: this.runId };\n }\n\n async timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const p = this._timeTravel(params).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n this.executionResults = p;\n return p;\n }\n\n async _timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }) {\n if (!params.step || (Array.isArray(params.step) && params.step?.length === 0)) {\n throw new Error('Step is required and must be a valid step or array of steps');\n }\n\n let steps: string[] = [];\n if (typeof params.step === 'string') {\n steps = params.step.split('.');\n } else {\n steps = (Array.isArray(params.step) ? params.step : [params.step]).map(step =>\n typeof step === 'string' ? step : step?.id,\n );\n }\n\n if (steps.length === 0) {\n throw new Error('No steps provided to timeTravel');\n }\n\n const storage = this.#mastra?.getStorage();\n const workflowsStore = await storage?.getStore('workflows');\n if (!workflowsStore) {\n throw new NonRetriableError(`Workflow storage is required to time-travel run ${this.runId}`);\n }\n\n const snapshot = await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n let snapshotForRollback = snapshot;\n if (!snapshot) {\n const pendingSnapshot = {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'pending' as const,\n value: {},\n context: {} as any,\n activePaths: [] as number[],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n };\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: pendingSnapshot,\n });\n snapshotForRollback = pendingSnapshot;\n }\n\n if (snapshot?.status === 'running') {\n throw new Error('This workflow run is still running, cannot time travel');\n }\n\n let inputDataToUse = params.inputData;\n\n if (inputDataToUse && steps.length === 1) {\n inputDataToUse = await this._validateTimetravelInputData(params.inputData, this.workflowSteps[steps[0]!]!);\n }\n\n const timeTravelData = createTimeTravelExecutionParams({\n steps,\n inputData: inputDataToUse,\n resumeData: params.resumeData,\n context: params.context,\n nestedStepsContext: params.nestedStepsContext,\n snapshot: (snapshot ?? { context: {} }) as any,\n graph: this.executionGraph,\n initialState: params.initialState,\n perStep: params.perStep,\n });\n\n // Save previous snapshot for rollback if send fails\n const previousSnapshot = snapshotForRollback;\n\n // Mark the snapshot as 'running' before sending the event so that\n // snapshot-based polling doesn't return the stale result from a previous run.\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n let eventOutput;\n try {\n eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n initialState: timeTravelData.state,\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: timeTravelData.stepResults,\n timeTravel: timeTravelData,\n tracingOptions: params.tracingOptions,\n outputOptions: params.outputOptions,\n requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},\n actor: params.actor,\n perStep: params.perStep,\n },\n });\n } catch (err) {\n // Rollback: restore the previous snapshot so the run isn't stuck in 'running'.\n // The rollback itself can fail (e.g. transient storage error); log it but\n // always rethrow the original error so the underlying failure isn't masked.\n if (previousSnapshot) {\n try {\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: previousSnapshot as any,\n });\n } catch (rollbackErr) {\n console.error('Failed to rollback snapshot during time-travel error recovery:', rollbackErr);\n }\n }\n throw err;\n }\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n const runOutput = await this.getRunOutput(eventId);\n const result = runOutput?.output?.result;\n this.hydrateFailedResult(result);\n\n // Only include state when explicitly requested, matching core engine behavior\n if (!params.outputOptions?.includeState) {\n delete result.state;\n }\n\n return result;\n }\n\n watch(cb: (event: WorkflowStreamEvent) => void): () => void {\n let active = true;\n const streamPromise = subscribe(\n {\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n },\n (message: any) => {\n if (active) {\n cb(message.data);\n }\n },\n );\n\n return () => {\n active = false;\n streamPromise\n .then(async (stream: Awaited<typeof streamPromise>) => {\n return stream.cancel();\n })\n .catch(err => {\n console.error(err);\n });\n };\n }\n\n streamLegacy({\n inputData,\n requestContext,\n actor,\n }: { inputData?: TInput; requestContext?: RequestContext<TRequestContext>; actor?: ActorSignal } = {}): {\n stream: ReadableStream<StreamEvent>;\n getWorkflowState: () => Promise<WorkflowResult<TState, TInput, TOutput, TSteps>>;\n } {\n const { readable, writable } = new TransformStream<StreamEvent, StreamEvent>();\n\n const writer = writable.getWriter();\n void writer.write({\n // @ts-expect-error - stream event type mismatch\n type: 'start',\n payload: { runId: this.runId },\n });\n\n const unwatch = this.watch(async event => {\n try {\n const e: any = {\n ...event,\n type: event.type.replace('workflow-', ''),\n };\n\n if (e.type === 'step-output') {\n e.type = e.payload.output.type;\n e.payload = e.payload.output.payload;\n }\n // watch events are data stream events, so we need to cast them to the correct type\n await writer.write(e as any);\n } catch {}\n });\n\n this.closeStreamAction = async () => {\n await writer.write({\n type: 'finish',\n // @ts-expect-error - stream event type mismatch\n payload: { runId: this.runId },\n });\n unwatch();\n\n try {\n await writer.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n } finally {\n writer.releaseLock();\n }\n };\n\n this.executionResults = this._start({ inputData, requestContext, actor, format: 'legacy' }).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n return {\n stream: readable as ReadableStream<StreamEvent>,\n getWorkflowState: () => this.executionResults!,\n };\n }\n\n stream({\n inputData,\n requestContext,\n actor,\n tracingOptions,\n closeOnSuspend = true,\n initialState,\n outputOptions,\n perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n closeOnSuspend?: boolean;\n initialState?: TState;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n } = {}): WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n if (this.closeStreamAction && this.streamOutput) {\n return this.streamOutput;\n }\n\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n const unwatch = self.watch(async (event: WorkflowStreamEvent) => {\n const { type, from = ChunkFrom.WORKFLOW, payload } = event;\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n await controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n\n const executionResultsPromise = self._start({\n inputData,\n requestContext,\n actor,\n // tracingContext, // We are not able to pass a reference to a span here, what to do?\n initialState,\n tracingOptions,\n outputOptions,\n format: 'vnext',\n perStep,\n });\n let executionResults;\n try {\n executionResults = await executionResultsPromise;\n\n if (closeOnSuspend) {\n // always close stream, even if the workflow is suspended\n // this will trigger a finish event with workflow status set to suspended\n self.closeStreamAction?.().catch(() => {});\n } else if (executionResults.status !== 'suspended') {\n self.closeStreamAction?.().catch(() => {});\n }\n if (self.streamOutput) {\n self.streamOutput.updateResults(\n executionResults as unknown as WorkflowResult<TState, TInput, TOutput, TSteps>,\n );\n }\n } catch (err) {\n self.streamOutput?.rejectResults(err as unknown as Error);\n self.closeStreamAction?.().catch(() => {});\n }\n },\n });\n\n this.streamOutput = new WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>>({\n runId: this.runId,\n workflowId: this.workflowId,\n stream,\n });\n\n return this.streamOutput;\n }\n\n timeTravelStream<TTravelInput>({\n inputData,\n resumeData,\n initialState,\n step,\n context,\n nestedStepsContext,\n requestContext,\n actor,\n // tracingContext,\n tracingOptions,\n outputOptions,\n perStep,\n }: {\n inputData?: TTravelInput;\n initialState?: TState;\n resumeData?: any;\n step:\n | Step<string, any, any, any, any, any, TEngineType>\n | [...Step<string, any, any, any, any, any, TEngineType>[], Step<string, any, any, any, any, any, TEngineType>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext<TRequestContext>;\n actor?: ActorSignal;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }) {\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n const unwatch = self.watch(async (event: WorkflowStreamEvent) => {\n const { type, from = ChunkFrom.WORKFLOW, payload } = event;\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n const executionResultsPromise = self._timeTravel({\n inputData,\n step,\n context,\n nestedStepsContext,\n resumeData,\n initialState,\n requestContext,\n actor,\n tracingOptions,\n outputOptions,\n perStep,\n });\n\n self.executionResults = executionResultsPromise;\n\n let executionResults;\n try {\n executionResults = await executionResultsPromise;\n self.closeStreamAction?.().catch(() => {});\n\n if (self.streamOutput) {\n self.streamOutput.updateResults(executionResults);\n }\n } catch (err) {\n self.streamOutput?.rejectResults(err as unknown as Error);\n self.closeStreamAction?.().catch(() => {});\n }\n },\n });\n\n this.streamOutput = new WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>>({\n runId: this.runId,\n workflowId: this.workflowId,\n stream,\n });\n\n return this.streamOutput;\n }\n\n /**\n * Hydrates errors in a failed workflow result back to proper Error instances.\n * This ensures error.cause chains and custom properties are preserved.\n */\n private hydrateFailedResult(result: WorkflowResult<TState, TInput, TOutput, TSteps>): void {\n if (result.status === 'failed') {\n // Ensure error is a proper Error instance with all properties preserved\n result.error = getErrorFromUnknown(result.error, { serializeStack: false });\n // Re-hydrate serialized errors in step results\n if (result.steps) {\n hydrateSerializedStepErrors(result.steps);\n }\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { emitErrorEvent } from '@mastra/core/agent/durable';\nimport { RequestContext } from '@mastra/core/di';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { SpanType, EntityType } from '@mastra/core/observability';\nimport type { WorkflowRuns } from '@mastra/core/storage';\nimport { Workflow, getEntryWorkflow, isSingleStepEntry } from '@mastra/core/workflows';\nimport type {\n Step,\n StepResult,\n WorkflowConfig,\n StepFlowEntry,\n WorkflowResult,\n WorkflowRunState,\n WorkflowStreamEvent,\n Run,\n} from '@mastra/core/workflows';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport { InngestExecutionEngine } from './execution-engine';\nimport {\n compactNestedWorkflowResult,\n NESTED_WORKFLOW_OUTPUT_MODE,\n resolveNestedWorkflowOutputMode,\n} from './nested-workflow-output';\nimport { InngestPubSub } from './pubsub';\nimport { InngestRun } from './run';\nimport type {\n InngestEngineType,\n InngestFlowControlConfig,\n InngestFlowCronConfig,\n InngestWorkflowConfig,\n} from './types';\n\n/**\n * Resolves the nested `InngestWorkflow` wrapped by a graph entry, if any.\n * Handles both plain single-step entries and `loop` / `foreach` entries whose\n * body is a `SingleStepEntry` wrapper (so `{ type: 'step', step: workflow }`\n * bodies are unwrapped correctly).\n */\nfunction getNestedInngestWorkflow(entry: StepFlowEntry): InngestWorkflow | null {\n let nested: unknown = null;\n if (entry.type === 'loop' || entry.type === 'foreach') {\n nested = getEntryWorkflow(entry.step);\n } else if (isSingleStepEntry(entry)) {\n nested = getEntryWorkflow(entry);\n }\n return nested instanceof InngestWorkflow ? nested : null;\n}\n\nexport class InngestWorkflow<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType, any>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType,\n unknown\n >[],\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TPrevSchema = TInput,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> extends Workflow<TEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrevSchema, TRequestContext> {\n #mastra: Mastra;\n public inngest: Inngest;\n\n private function: ReturnType<Inngest['createFunction']> | undefined;\n private cronFunction: ReturnType<Inngest['createFunction']> | undefined;\n private readonly flowControlConfig?: InngestFlowControlConfig;\n private readonly cronConfig?: InngestFlowCronConfig<TInput, TState>;\n /**\n * Optional override that lets a host (e.g. `createInngestAgent`) provide the\n * PubSub instance used by workflow steps for publishing chunk/finish events.\n * When set, the workflow function uses this factory instead of constructing\n * a fresh `InngestPubSub`. This is what lets `DurableAgent.observe()` see\n * cached history when the agent wraps its PubSub in a `CachingPubSub`.\n */\n #pubsubFactory?: (defaultPubsub: PubSub) => PubSub;\n\n constructor(\n params: InngestWorkflowConfig<\n TWorkflowId,\n TState,\n TInput,\n TOutput,\n TSteps & Step<string, any, any, any, any, any, InngestEngineType, any>[],\n TRequestContext\n >,\n inngest: Inngest,\n ) {\n const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } =\n params;\n\n super(workflowParams as WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps, TRequestContext>);\n\n this.engineType = 'inngest';\n\n const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(\n ([_, value]) => value !== undefined,\n );\n\n this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : undefined;\n\n this.#mastra = params.mastra!;\n this.inngest = inngest;\n\n if (cron) {\n this.cronConfig = { cron, inputData, initialState };\n }\n }\n\n async listWorkflowRuns(args?: {\n fromDate?: Date;\n toDate?: Date;\n perPage?: number | false;\n page?: number;\n resourceId?: string;\n }) {\n const storage = this.#mastra?.getStorage();\n if (!storage) {\n this.logger.debug('Cannot get workflow runs. Mastra engine is not initialized');\n return { runs: [], total: 0 };\n }\n\n const workflowsStore = await storage.getStore('workflows');\n if (!workflowsStore) {\n return { runs: [], total: 0 };\n }\n return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...(args ?? {}) }) as unknown as WorkflowRuns;\n }\n\n /**\n * Override the PubSub used inside the durable workflow function. Callers like\n * `createInngestAgent` use this to route workflow event publishes through the\n * agent's `CachingPubSub`, so `observe()` can replay cached history.\n *\n * The factory receives the workflow's own default `InngestPubSub` (constructed\n * with this workflow's id) as input. Hosts should wrap that instance rather\n * than substitute it, so workflow-event channels (which encode the workflow\n * id) remain workflow-local. Returning a `CachingPubSub` wrapping the default\n * is the canonical pattern.\n *\n * The factory is propagated to every nested `InngestWorkflow` in the step\n * graph. Nested workflows run as their own Inngest functions and resolve\n * their own pubsub at runtime; each invocation passes its own workflow-local\n * default into the same factory, so the host can share cross-workflow state\n * (e.g. a single agent-scoped cache) without collapsing per-workflow channel\n * isolation.\n */\n __setPubsubFactory(factory: (defaultPubsub: PubSub) => PubSub) {\n this.#pubsubFactory = factory;\n const updateNested = (step: StepFlowEntry) => {\n const nested = getNestedInngestWorkflow(step);\n if (nested) {\n nested.__setPubsubFactory(factory);\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n for (const subStep of step.steps) {\n updateNested(subStep);\n }\n }\n };\n for (const step of this.executionGraph.steps) {\n updateNested(step);\n }\n }\n\n /**\n * Test-only accessor for the configured pubsub factory. Lets tests verify that\n * a host (e.g. `createInngestAgent`) wired the workflow to its agent pubsub\n * without having to drive a real Inngest invocation.\n */\n __getPubsubFactory(): ((defaultPubsub: PubSub) => PubSub) | undefined {\n return this.#pubsubFactory;\n }\n\n __registerMastra(mastra: Mastra) {\n super.__registerMastra(mastra);\n this.#mastra = mastra;\n this.executionEngine.__registerMastra(mastra);\n const updateNested = (step: StepFlowEntry) => {\n const nested = getNestedInngestWorkflow(step);\n if (nested) {\n nested.__registerMastra(mastra);\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n for (const subStep of step.steps) {\n updateNested(subStep);\n }\n }\n };\n\n if (this.executionGraph.steps.length) {\n for (const step of this.executionGraph.steps) {\n updateNested(step);\n }\n }\n }\n\n async createRun(options?: {\n runId?: string;\n resourceId?: string;\n disableScorers?: boolean;\n pubsub?: PubSub;\n }): Promise<Run<TEngineType, TSteps, TState, TInput, TOutput, TRequestContext>> {\n const runIdToUse = options?.runId || randomUUID();\n\n // Return a new Run instance with object parameters\n const existingInMemoryRun = this.runs.get(runIdToUse);\n const newRun = new InngestRun<TEngineType, TSteps, TState, TInput, TOutput, TRequestContext>(\n {\n workflowId: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n executionEngine: this.executionEngine,\n executionGraph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n mastra: this.#mastra,\n retryConfig: this.retryConfig,\n cleanup: () => this.runs.delete(runIdToUse),\n workflowSteps: this.steps,\n workflowEngineType: this.engineType,\n validateInputs: this.options.validateInputs,\n },\n this.inngest,\n );\n const run = (existingInMemoryRun ?? newRun) as Run<TEngineType, TSteps, TState, TInput, TOutput, TRequestContext>;\n\n this.runs.set(runIdToUse, run);\n\n const shouldPersistSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: run.workflowRunStatus,\n stepResults: {},\n });\n\n const existingStoredRun = await this.getWorkflowRunById(runIdToUse, {\n withNestedWorkflows: false,\n });\n\n // Check if run exists in persistent storage (not just in-memory)\n const existsInStorage = existingStoredRun && !existingStoredRun.isFromInMemory;\n\n if (!existsInStorage && shouldPersistSnapshot) {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n snapshot: {\n runId: runIdToUse,\n status: 'pending',\n value: {},\n context: {},\n activePaths: [],\n activeStepsPath: {},\n waitingPaths: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: {},\n resumeLabels: {},\n result: undefined,\n error: undefined,\n timestamp: Date.now(),\n },\n });\n }\n\n return run;\n }\n\n //createCronFunction is only called if cronConfig.cron is defined.\n private createCronFunction() {\n if (this.cronFunction) {\n return this.cronFunction;\n }\n this.cronFunction = this.inngest.createFunction(\n {\n id: `workflow.${this.id}.cron`,\n retries: 0,\n // Not scoped by `match` like the event-triggered function above: a cron\n // trigger carries no event data to match a runId against, and the run\n // is created inside the function, so the canceller has no id to name.\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n triggers: { cron: this.cronConfig?.cron ?? '' },\n ...this.flowControlConfig,\n },\n async () => {\n const run = await this.createRun();\n // @ts-expect-error - cron inputData type mismatch\n const result = await run.start({\n inputData: this.cronConfig?.inputData,\n initialState: this.cronConfig?.initialState,\n });\n return { result, runId: run.runId };\n },\n );\n return this.cronFunction;\n }\n\n /**\n * Gets the durable Inngest function that executes this workflow.\n *\n * @returns The memoized Inngest function for this workflow.\n */\n getFunction(): ReturnType<Inngest['createFunction']> {\n if (this.function) {\n return this.function;\n }\n\n // Always set function-level retries to 0, since retries are handled at the step level via executeStepWithRetry\n // which uses either step.retries or retryConfig.attempts (step.retries takes precedence).\n // step.retries is not accessible at function level, so we handle retries manually in executeStepWithRetry.\n // This is why we set retries to 0 here.\n this.function = this.inngest.createFunction(\n {\n id: `workflow.${this.id}`,\n retries: 0,\n // `match` scopes the cancellation to the run the cancel event names.\n // Without it Inngest cancels every in-flight run of this function, and\n // since all durable agents share one function, cancelling a single run\n // tore down every other run in the deployment — only the targeted run's\n // snapshot was marked canceled, so the rest simply vanished.\n // Every event that triggers this function carries `data.runId`, and\n // `Run.cancel()` sends the same field.\n cancelOn: [{ event: `cancel.workflow.${this.id}`, match: 'data.runId' }],\n triggers: { event: `workflow.${this.id}` },\n // Spread flow control configuration\n ...this.flowControlConfig,\n },\n /**\n * Executes a workflow invocation from its Inngest trigger event.\n *\n * @param context - The Inngest event, durable step tools, and current attempt.\n * @returns The workflow result and run identifier returned to Inngest.\n */\n async ({ event, step, attempt }) => {\n let {\n inputData,\n initialState,\n runId,\n resourceId,\n resume,\n outputOptions,\n format,\n timeTravel,\n perStep,\n tracingOptions,\n actor,\n nestedWorkflowOutputMode: requestedNestedWorkflowOutputMode,\n } = event.data;\n const nestedWorkflowOutputMode = resolveNestedWorkflowOutputMode(requestedNestedWorkflowOutputMode);\n const shouldCompactNestedWorkflowOutput = nestedWorkflowOutputMode === NESTED_WORKFLOW_OUTPUT_MODE.COMPACT;\n\n if (!runId) {\n // Reached when a trigger event arrives without a run id — an event sent\n // directly rather than through `createRun()`, which always supplies one.\n // The id generated here never reaches the trigger event that `cancelOn`\n // matches against, so `cancel.workflow.${this.id}` cannot target this\n // run. Warn rather than reject: an unnamed run is still a valid way to\n // start a workflow, it just can't be cancelled by id afterwards.\n runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {\n return randomUUID();\n });\n this.logger.warn?.(\n `Workflow \"${this.id}\" was triggered without a runId, so run \"${runId}\" cannot be cancelled by id. ` +\n `Send \\`data.runId\\` on the trigger event (or start the run with createRun()) to make it cancellable.`,\n );\n }\n\n if (resume && (initialState === undefined || resume.stepResults === undefined)) {\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.id,\n runId,\n });\n\n initialState ??= snapshot?.value;\n if (resume.stepResults === undefined && snapshot?.context !== undefined) {\n resume = { ...resume, stepResults: snapshot.context };\n }\n }\n\n // Create InngestPubSub instance. Publishes go through `inngest.realtime.publish()`\n // (Inngest SDK v4 client API), which auto-includes the current runId from the\n // function's async context.\n //\n // The default is constructed with `this.id` so workflow-event channels stay\n // workflow-local (InngestPubSub encodes the workflowId in `workflow:<id>:<runId>`).\n // Hosts (e.g. `createInngestAgent`) can override via `__setPubsubFactory` to\n // wrap this default - typically with a `CachingPubSub` so `observe()` can replay\n // cached history - without disturbing per-workflow channel isolation.\n const defaultPubsub = new InngestPubSub(this.inngest, this.id);\n const pubsub: PubSub = this.#pubsubFactory?.(defaultPubsub) ?? defaultPubsub;\n\n // Create requestContext before execute so we can reuse it in finalize\n const requestContext: RequestContext = new RequestContext(Object.entries(event.data.requestContext ?? {}));\n\n // Store mastra reference for use in proxy closure\n const mastra = this.#mastra;\n const tracingPolicy = this.options.tracingPolicy;\n\n // Create the workflow root span durably - exports SPAN_STARTED immediately on first execution\n // On replay, returns memoized ExportedSpan data without re-creating the span\n const workflowSpanData = await step.run(`workflow.${this.id}.span.start`, async () => {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (!observability) return undefined;\n\n const span = observability.startSpan({\n type: SpanType.WORKFLOW_RUN,\n name: `workflow run: '${this.id}'`,\n entityType: EntityType.WORKFLOW_RUN,\n entityId: this.id,\n entityName: this.id,\n input: inputData,\n metadata: {\n resourceId,\n runId,\n },\n tracingPolicy,\n tracingOptions,\n requestContext,\n });\n\n return span?.exportSpan();\n });\n\n const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);\n\n let result: WorkflowResult<TState, TInput, TOutput, TSteps>;\n try {\n result = await engine.execute<TState, TInput, WorkflowResult<TState, TInput, TOutput, TSteps>>({\n workflowId: this.id,\n runId,\n resourceId,\n graph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n input: inputData,\n initialState,\n pubsub,\n retryConfig: this.retryConfig,\n requestContext,\n actor,\n resume,\n timeTravel,\n perStep,\n format,\n abortController: new AbortController(),\n // For Inngest, we don't pass workflowSpan - step spans use tracingIds instead\n workflowSpan: undefined,\n // Pass tracing IDs for durable span operations\n tracingIds: workflowSpanData\n ? {\n traceId: workflowSpanData.traceId,\n workflowSpanId: workflowSpanData.id,\n }\n : undefined,\n outputOptions,\n outputWriter: async (chunk: WorkflowStreamEvent) => {\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: chunk,\n });\n } catch (err) {\n this.logger.debug?.('Failed to publish watch event:', err);\n }\n },\n });\n } catch (executionError) {\n // Execution threw an exception (not just returned failed status)\n // Create a failed result to pass to finalize\n result = {\n status: 'failed',\n steps: {},\n state: initialState ?? {},\n error: executionError instanceof Error ? executionError : new Error(String(executionError)),\n } as WorkflowResult<TState, TInput, TOutput, TSteps>;\n }\n\n const returnedResult = shouldCompactNestedWorkflowOutput ? compactNestedWorkflowResult(result) : result;\n\n // Final step to invoke lifecycle callbacks and end workflow span.\n // This step is memoized by step.run.\n let finalizeError: unknown;\n let finalizeErrored = false;\n try {\n /**\n * Finalizes workflow lifecycle reporting in a memoized Inngest step.\n *\n * @returns The workflow result, or only its status for compact nested invocations.\n */\n const finalizeWorkflow = async () => {\n // For durable agent workflows, emit error event on failure so the\n // client's stream can receive the error and close properly.\n if (result.status === 'failed' && inputData?.__workflowKind === 'durable-agent' && inputData?.runId) {\n const error = result.error instanceof Error ? result.error : new Error(String(result.error));\n try {\n await emitErrorEvent(pubsub, inputData.runId, error);\n } catch (e) {\n this.logger.debug?.('Failed to emit error event:', e);\n }\n }\n\n if (result.status !== 'paused') {\n // Invoke lifecycle callbacks (onFinish and onError)\n await engine.invokeLifecycleCallbacksInternal({\n status: result.status,\n result: 'result' in result ? result.result : undefined,\n error: 'error' in result ? result.error : undefined,\n steps: result.steps,\n tripwire: 'tripwire' in result ? result.tripwire : undefined,\n runId,\n workflowId: this.id,\n resourceId,\n input: inputData,\n requestContext,\n state: result.state ?? initialState ?? {},\n });\n }\n\n // End the workflow span with appropriate status\n // The workflow span was already created and SPAN_STARTED was exported in the span.start step\n if (workflowSpanData) {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n // Rebuild the span from cached data to call end/error\n const workflowSpan = observability.rebuildSpan(workflowSpanData);\n\n if (result.status === 'failed') {\n workflowSpan.error({\n error: result.error instanceof Error ? result.error : new Error(String(result.error)),\n attributes: { status: 'failed' },\n });\n } else {\n workflowSpan.end({\n output: result.status === 'success' ? result.result : undefined,\n attributes: { status: result.status },\n });\n }\n }\n }\n\n // Ensure final snapshot is persisted BEFORE publishing workflow-finish\n // This fixes a race condition where getRunOutput reads the snapshot before it's fully written\n const shouldPersistFinalSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: result.status,\n stepResults: result.steps,\n });\n if (shouldPersistFinalSnapshot) {\n const workflowsStore = await mastra?.getStorage()?.getStore('workflows');\n if (workflowsStore) {\n // For suspended workflows, read existing snapshot to preserve suspendedPaths and resumeLabels\n // which were set correctly by the handlers during execution\n let existingSnapshot:\n | { suspendedPaths?: Record<string, number[]>; resumeLabels?: Record<string, any> }\n | undefined;\n if (result.status === 'suspended') {\n existingSnapshot =\n (await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.id,\n runId,\n })) ?? undefined;\n }\n\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.id,\n runId,\n resourceId,\n snapshot: {\n runId,\n status: result.status,\n value: result.state ?? initialState ?? {},\n context: toSnapshotContext(result.steps),\n activePaths: [],\n activeStepsPath: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: existingSnapshot?.suspendedPaths ?? {},\n waitingPaths: {},\n resumeLabels: existingSnapshot?.resumeLabels ?? result.resumeLabels ?? {},\n result: result.status === 'success' ? toSnapshotResult(result.result) : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n requestContext: requestContext.toJSON(),\n tracingContext: workflowSpanData\n ? {\n traceId: workflowSpanData.traceId,\n spanId: workflowSpanData.id,\n }\n : undefined,\n timestamp: Date.now(),\n },\n });\n }\n }\n\n // Publish workflow-finish event for realtime subscribers (best-effort)\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: {\n type: 'workflow-finish',\n payload: {\n status: result.status,\n result: result.status === 'success' ? result.result : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n },\n },\n });\n } catch (publishError) {\n this.logger.debug?.('Failed to publish workflow-finish event:', publishError);\n }\n\n // Throw after span ended for failed workflows\n if (result.status === 'failed') {\n throw new NonRetriableError(`Workflow failed`, {\n cause: shouldCompactNestedWorkflowOutput ? { ...returnedResult, runId } : result,\n });\n }\n\n return shouldCompactNestedWorkflowOutput ? { status: result.status } : result;\n };\n await step.run(`workflow.${this.id}.finalize`, finalizeWorkflow);\n } catch (error) {\n finalizeErrored = true;\n finalizeError = error;\n } finally {\n // Keep this outside step.run memoization, but guaranteed on all paths.\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n try {\n await observability.flush();\n } catch (flushError) {\n this.logger.debug?.('Failed to flush observability:', flushError);\n }\n }\n }\n\n if (finalizeErrored) {\n throw finalizeError;\n }\n\n return { result: returnedResult, runId };\n },\n );\n return this.function;\n }\n\n getNestedFunctions(steps: StepFlowEntry[]): ReturnType<Inngest['createFunction']>[] {\n return steps.flatMap(step => {\n const nested = getNestedInngestWorkflow(step);\n if (nested) {\n return [nested.getFunction(), ...nested.getNestedFunctions(nested.executionGraph.steps)];\n }\n if (step.type === 'parallel' || step.type === 'conditional') {\n return this.getNestedFunctions(step.steps);\n }\n\n return [];\n });\n }\n\n getFunctions(): ReturnType<Inngest['createFunction']>[] {\n return [\n this.getFunction(),\n ...(this.cronConfig?.cron ? [this.createCronFunction()] : []),\n ...this.getNestedFunctions(this.executionGraph.steps),\n ];\n }\n}\n\n/**\n * Converts runtime step results to the serialized context shape expected by WorkflowRunState.\n * StepResult is a structural subset of SerializedStepResult (widening), so no data\n * transformation is needed — this bridges the generic type mismatch at the persistence boundary.\n */\nfunction toSnapshotContext(steps: Record<string, StepResult<any, any, any, any>>): WorkflowRunState['context'] {\n return steps as unknown as WorkflowRunState['context'];\n}\n\n/**\n * Converts a workflow output value to the record shape expected by WorkflowRunState.result.\n * Workflow outputs are generic (TOutput) but the snapshot schema stores them as Record<string, any>.\n */\nfunction toSnapshotResult(output: unknown): WorkflowRunState['result'] {\n return output as WorkflowRunState['result'];\n}\n","import type { Mastra } from '@mastra/core/mastra';\nimport type { InngestFunction } from 'inngest';\nimport { InngestWorkflow } from './workflow';\n\nexport function collectInngestFunctions({\n mastra,\n functions: userFunctions = [],\n}: {\n mastra: Mastra;\n functions?: InngestFunction.Like[];\n}) {\n const workflows = mastra.listWorkflows();\n const workflowFunctions = Array.from(\n new Set(\n Object.values(workflows).flatMap(workflow => {\n if (workflow instanceof InngestWorkflow) {\n workflow.__registerMastra(mastra);\n return workflow.getFunctions();\n }\n return [];\n }),\n ),\n );\n\n return [...workflowFunctions, ...userFunctions];\n}\n","import type { Mastra } from '@mastra/core/mastra';\nimport type { Inngest, InngestFunction, RegisterOptions } from 'inngest';\nimport type { connect as inngestConnect } from 'inngest/connect';\nimport { collectInngestFunctions } from './functions';\n\ntype InngestConnectOptions = Parameters<typeof inngestConnect>[0];\n\nexport interface MastraConnectOptions extends Omit<InngestConnectOptions, 'apps'> {\n mastra: Mastra;\n inngest: Inngest;\n /**\n * Optional array of additional Inngest functions to expose through the same Connect worker.\n */\n functions?: InngestFunction.Like[];\n /**\n * Forwarded to Inngest as part of the app registration (timeout, signing key overrides, etc.).\n *\n * When a field is present in both `registerOptions` and the top-level Connect options\n * (e.g. `signingKey`), `registerOptions` wins. This matches the override behavior of\n * `serve()` so the two surfaces stay consistent.\n */\n registerOptions?: RegisterOptions;\n}\n\n/**\n * Connect Mastra workflows to Inngest using an outbound worker connection.\n *\n * Use this instead of `serve()` when the worker process should not expose an inbound HTTP\n * endpoint. The same workflow functions collected by `serve()` are forwarded to\n * `inngest/connect`, alongside any additional user functions.\n *\n * If the Mastra instance has no `InngestWorkflow` and no additional `functions` are\n * provided, a warning is emitted because the worker would otherwise idle forever with\n * nothing to execute.\n *\n * @example Worker process\n * ```ts\n * import { connect } from '@mastra/inngest/connect';\n * import { mastra } from './mastra';\n * import { inngest } from './mastra/inngest';\n *\n * await connect({ mastra, inngest });\n * ```\n */\nexport async function connect(options: MastraConnectOptions) {\n const { mastra, inngest, functions, registerOptions, ...connectOptions } = options;\n const appFunctions = collectInngestFunctions({ mastra, functions });\n\n if (appFunctions.length === 0) {\n console.warn(\n '[@mastra/inngest] connect() was called with no Inngest workflows and no additional functions. ' +\n 'The worker will connect to Inngest but has nothing to execute. ' +\n 'Register at least one InngestWorkflow on the Mastra instance or pass `functions: [...]`.',\n );\n }\n\n const { connect: connectWorker } = await import('inngest/connect');\n\n return connectWorker({\n // Top-level Connect options first, then registerOptions so they take precedence\n // for any overlapping keys (e.g. `signingKey`). This matches serve()'s behavior.\n ...connectOptions,\n ...registerOptions,\n apps: [{ client: inngest, functions: appFunctions }],\n });\n}\n"],"mappings":";;;;;;;;;;;;AAEA,MAAa,8BAA8B;CACzC,SAAS;CACT,SAAS;AACX;;;;;;;AAuBA,SAAgB,gCACd,OAA6C,4BAA4B,SAC/C;CAC1B,OAAO,SAAS,4BAA4B,UACxC,4BAA4B,UAC5B,4BAA4B;AAClC;;;;;;;;;;AAWA,SAAgB,4BAA4B,QAAiD;CAC3F,QAAQ,OAAO,QAAf;EACE,KAAK,WACH,OAAO;GAAE,QAAQ,OAAO;GAAQ,QAAQ,OAAO;GAAQ,OAAO,OAAO;EAAM;EAC7E,KAAK,UACH,OAAO;GAAE,QAAQ,OAAO;GAAQ,OAAO,OAAO;GAAO,OAAO,OAAO;EAAM;EAC3E,KAAK,YACH,O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