@mastra/inngest 0.0.0-dynamic-model-router-20251010193247 → 0.0.0-elated-armadillo-be37a1-20251219210627

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/dist/index.js CHANGED
@@ -1,39 +1,473 @@
1
+ import { Tool } from '@mastra/core/tools';
2
+ import { DefaultExecutionEngine, createTimeTravelExecutionParams, Run, hydrateSerializedStepErrors, Workflow } from '@mastra/core/workflows';
3
+ import { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
4
+ import { z } from 'zod';
1
5
  import { randomUUID } from 'crypto';
6
+ import { RequestContext } from '@mastra/core/di';
7
+ import { RetryAfterError, NonRetriableError } from 'inngest';
8
+ import { getErrorFromUnknown } from '@mastra/core/error';
2
9
  import { subscribe } from '@inngest/realtime';
3
- import { wrapMastra, AISpanType } from '@mastra/core/ai-tracing';
4
- import { RuntimeContext } from '@mastra/core/di';
5
- import { ToolStream, Tool } from '@mastra/core/tools';
6
- import { Run, Workflow, DefaultExecutionEngine, getStepResult, validateStepInput } from '@mastra/core/workflows';
7
- import { EMITTER_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
8
- import { NonRetriableError, RetryAfterError } from 'inngest';
10
+ import { PubSub } from '@mastra/core/events';
11
+ import { ReadableStream } from 'stream/web';
12
+ import { ChunkFrom, WorkflowRunOutput } from '@mastra/core/stream';
9
13
  import { serve as serve$1 } from 'inngest/hono';
10
- import { z } from 'zod';
11
14
 
12
15
  // src/index.ts
13
- function serve({
14
- mastra,
15
- inngest,
16
- functions: userFunctions = [],
17
- registerOptions
18
- }) {
19
- const wfs = mastra.getWorkflows();
20
- const workflowFunctions = Array.from(
21
- new Set(
22
- Object.values(wfs).flatMap((wf) => {
23
- if (wf instanceof InngestWorkflow) {
24
- wf.__registerMastra(mastra);
25
- return wf.getFunctions();
16
+ var InngestExecutionEngine = class extends DefaultExecutionEngine {
17
+ inngestStep;
18
+ inngestAttempts;
19
+ constructor(mastra, inngestStep, inngestAttempts = 0, options) {
20
+ super({ mastra, options });
21
+ this.inngestStep = inngestStep;
22
+ this.inngestAttempts = inngestAttempts;
23
+ }
24
+ // =============================================================================
25
+ // Hook Overrides
26
+ // =============================================================================
27
+ /**
28
+ * Format errors while preserving Error instances and their custom properties.
29
+ * Uses getErrorFromUnknown to ensure all error properties are preserved.
30
+ */
31
+ formatResultError(error, lastOutput) {
32
+ const outputError = lastOutput?.error;
33
+ const errorSource = error || outputError;
34
+ const errorInstance = getErrorFromUnknown(errorSource, {
35
+ serializeStack: true,
36
+ // Include stack in JSON for better debugging in Inngest
37
+ fallbackMessage: "Unknown workflow error"
38
+ });
39
+ return errorInstance.toJSON();
40
+ }
41
+ /**
42
+ * Detect InngestWorkflow instances for special nested workflow handling
43
+ */
44
+ isNestedWorkflowStep(step) {
45
+ return step instanceof InngestWorkflow;
46
+ }
47
+ /**
48
+ * Inngest requires requestContext serialization for memoization.
49
+ * When steps are replayed, the original function doesn't re-execute,
50
+ * so requestContext modifications must be captured and restored.
51
+ */
52
+ requiresDurableContextSerialization() {
53
+ return true;
54
+ }
55
+ /**
56
+ * Execute a step with retry logic for Inngest.
57
+ * Retries are handled via step-level retry (RetryAfterError thrown INSIDE step.run()).
58
+ * After retries exhausted, error propagates here and we return a failed result.
59
+ */
60
+ async executeStepWithRetry(stepId, runStep, params) {
61
+ try {
62
+ const result = await this.wrapDurableOperation(stepId, runStep, { delay: params.delay });
63
+ return { ok: true, result };
64
+ } catch (e) {
65
+ const cause = e?.cause;
66
+ if (cause?.status === "failed") {
67
+ params.stepSpan?.error({
68
+ error: e,
69
+ attributes: { status: "failed" }
70
+ });
71
+ if (cause.error && !(cause.error instanceof Error)) {
72
+ cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });
26
73
  }
27
- return [];
28
- })
29
- )
30
- );
31
- return serve$1({
32
- ...registerOptions,
33
- client: inngest,
34
- functions: [...workflowFunctions, ...userFunctions]
35
- });
36
- }
74
+ return { ok: false, error: cause };
75
+ }
76
+ const errorInstance = getErrorFromUnknown(e, {
77
+ serializeStack: false,
78
+ fallbackMessage: "Unknown step execution error"
79
+ });
80
+ params.stepSpan?.error({
81
+ error: errorInstance,
82
+ attributes: { status: "failed" }
83
+ });
84
+ return {
85
+ ok: false,
86
+ error: {
87
+ status: "failed",
88
+ error: errorInstance,
89
+ endedAt: Date.now()
90
+ }
91
+ };
92
+ }
93
+ }
94
+ /**
95
+ * Use Inngest's sleep primitive for durability
96
+ */
97
+ async executeSleepDuration(duration, sleepId, workflowId) {
98
+ await this.inngestStep.sleep(`workflow.${workflowId}.sleep.${sleepId}`, duration < 0 ? 0 : duration);
99
+ }
100
+ /**
101
+ * Use Inngest's sleepUntil primitive for durability
102
+ */
103
+ async executeSleepUntilDate(date, sleepUntilId, workflowId) {
104
+ await this.inngestStep.sleepUntil(`workflow.${workflowId}.sleepUntil.${sleepUntilId}`, date);
105
+ }
106
+ /**
107
+ * Wrap durable operations in Inngest step.run() for durability.
108
+ * If retryConfig is provided, throws RetryAfterError INSIDE step.run() to trigger
109
+ * Inngest's step-level retry mechanism (not function-level retry).
110
+ */
111
+ async wrapDurableOperation(operationId, operationFn, retryConfig) {
112
+ return this.inngestStep.run(operationId, async () => {
113
+ try {
114
+ return await operationFn();
115
+ } catch (e) {
116
+ if (retryConfig) {
117
+ const errorInstance = getErrorFromUnknown(e, {
118
+ serializeStack: false,
119
+ fallbackMessage: "Unknown step execution error"
120
+ });
121
+ throw new RetryAfterError(errorInstance.message, retryConfig.delay, {
122
+ cause: {
123
+ status: "failed",
124
+ error: errorInstance,
125
+ endedAt: Date.now()
126
+ }
127
+ });
128
+ }
129
+ throw e;
130
+ }
131
+ });
132
+ }
133
+ /**
134
+ * Provide Inngest step primitive in engine context
135
+ */
136
+ getEngineContext() {
137
+ return { step: this.inngestStep };
138
+ }
139
+ /**
140
+ * For Inngest, lifecycle callbacks are invoked in the workflow's finalize step
141
+ * (wrapped in step.run for durability), not in execute(). Override to skip.
142
+ */
143
+ async invokeLifecycleCallbacks(_result) {
144
+ }
145
+ /**
146
+ * Actually invoke the lifecycle callbacks. Called from workflow.ts finalize step.
147
+ */
148
+ async invokeLifecycleCallbacksInternal(result) {
149
+ return super.invokeLifecycleCallbacks(result);
150
+ }
151
+ /**
152
+ * Execute nested InngestWorkflow using inngestStep.invoke() for durability.
153
+ * This MUST be called directly (not inside step.run()) due to Inngest constraints.
154
+ */
155
+ async executeWorkflowStep(params) {
156
+ if (!(params.step instanceof InngestWorkflow)) {
157
+ return null;
158
+ }
159
+ const { step, stepResults, executionContext, resume, timeTravel, prevOutput, inputData, pubsub, startedAt } = params;
160
+ const isResume = !!resume?.steps?.length;
161
+ let result;
162
+ let runId;
163
+ const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);
164
+ try {
165
+ if (isResume) {
166
+ runId = stepResults[resume?.steps?.[0] ?? ""]?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();
167
+ const snapshot = await this.mastra?.getStorage()?.loadWorkflowSnapshot({
168
+ workflowName: step.id,
169
+ runId
170
+ });
171
+ const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
172
+ function: step.getFunction(),
173
+ data: {
174
+ inputData,
175
+ initialState: executionContext.state ?? snapshot?.value ?? {},
176
+ runId,
177
+ resume: {
178
+ runId,
179
+ steps: resume.steps.slice(1),
180
+ stepResults: snapshot?.context,
181
+ resumePayload: resume.resumePayload,
182
+ resumePath: resume.steps?.[1] ? snapshot?.suspendedPaths?.[resume.steps?.[1]] : void 0
183
+ },
184
+ outputOptions: { includeState: true }
185
+ }
186
+ });
187
+ result = invokeResp.result;
188
+ runId = invokeResp.runId;
189
+ executionContext.state = invokeResp.result.state;
190
+ } else if (isTimeTravel) {
191
+ const snapshot = await this.mastra?.getStorage()?.loadWorkflowSnapshot({
192
+ workflowName: step.id,
193
+ runId: executionContext.runId
194
+ }) ?? { context: {} };
195
+ const timeTravelParams = createTimeTravelExecutionParams({
196
+ steps: timeTravel.steps.slice(1),
197
+ inputData: timeTravel.inputData,
198
+ resumeData: timeTravel.resumeData,
199
+ context: timeTravel.nestedStepResults?.[step.id] ?? {},
200
+ nestedStepsContext: timeTravel.nestedStepResults ?? {},
201
+ snapshot,
202
+ graph: step.buildExecutionGraph()
203
+ });
204
+ const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
205
+ function: step.getFunction(),
206
+ data: {
207
+ timeTravel: timeTravelParams,
208
+ initialState: executionContext.state ?? {},
209
+ runId: executionContext.runId,
210
+ outputOptions: { includeState: true }
211
+ }
212
+ });
213
+ result = invokeResp.result;
214
+ runId = invokeResp.runId;
215
+ executionContext.state = invokeResp.result.state;
216
+ } else {
217
+ const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
218
+ function: step.getFunction(),
219
+ data: {
220
+ inputData,
221
+ initialState: executionContext.state ?? {},
222
+ outputOptions: { includeState: true }
223
+ }
224
+ });
225
+ result = invokeResp.result;
226
+ runId = invokeResp.runId;
227
+ executionContext.state = invokeResp.result.state;
228
+ }
229
+ } catch (e) {
230
+ const errorCause = e?.cause;
231
+ if (errorCause && typeof errorCause === "object") {
232
+ result = errorCause;
233
+ runId = errorCause.runId || randomUUID();
234
+ } else {
235
+ runId = randomUUID();
236
+ result = {
237
+ status: "failed",
238
+ error: e instanceof Error ? e : new Error(String(e)),
239
+ steps: {},
240
+ input: inputData
241
+ };
242
+ }
243
+ }
244
+ const res = await this.inngestStep.run(
245
+ `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,
246
+ async () => {
247
+ if (result.status === "failed") {
248
+ await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
249
+ type: "watch",
250
+ runId: executionContext.runId,
251
+ data: {
252
+ type: "workflow-step-result",
253
+ payload: {
254
+ id: step.id,
255
+ status: "failed",
256
+ error: result?.error,
257
+ payload: prevOutput
258
+ }
259
+ }
260
+ });
261
+ return { executionContext, result: { status: "failed", error: result?.error } };
262
+ } else if (result.status === "suspended") {
263
+ const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
264
+ const stepRes = stepResult;
265
+ return stepRes?.status === "suspended";
266
+ });
267
+ for (const [stepName, stepResult] of suspendedSteps) {
268
+ const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
269
+ executionContext.suspendedPaths[step.id] = executionContext.executionPath;
270
+ await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
271
+ type: "watch",
272
+ runId: executionContext.runId,
273
+ data: {
274
+ type: "workflow-step-suspended",
275
+ payload: {
276
+ id: step.id,
277
+ status: "suspended"
278
+ }
279
+ }
280
+ });
281
+ return {
282
+ executionContext,
283
+ result: {
284
+ status: "suspended",
285
+ payload: stepResult.payload,
286
+ suspendPayload: {
287
+ ...stepResult?.suspendPayload,
288
+ __workflow_meta: { runId, path: suspendPath }
289
+ }
290
+ }
291
+ };
292
+ }
293
+ return {
294
+ executionContext,
295
+ result: {
296
+ status: "suspended",
297
+ payload: {}
298
+ }
299
+ };
300
+ } else if (result.status === "tripwire") {
301
+ await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
302
+ type: "watch",
303
+ runId: executionContext.runId,
304
+ data: {
305
+ type: "workflow-step-result",
306
+ payload: {
307
+ id: step.id,
308
+ status: "tripwire",
309
+ error: result?.tripwire?.reason,
310
+ payload: prevOutput
311
+ }
312
+ }
313
+ });
314
+ return {
315
+ executionContext,
316
+ result: {
317
+ status: "tripwire",
318
+ tripwire: result?.tripwire
319
+ }
320
+ };
321
+ }
322
+ await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
323
+ type: "watch",
324
+ runId: executionContext.runId,
325
+ data: {
326
+ type: "workflow-step-result",
327
+ payload: {
328
+ id: step.id,
329
+ status: "success",
330
+ output: result?.result
331
+ }
332
+ }
333
+ });
334
+ await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
335
+ type: "watch",
336
+ runId: executionContext.runId,
337
+ data: {
338
+ type: "workflow-step-finish",
339
+ payload: {
340
+ id: step.id,
341
+ metadata: {}
342
+ }
343
+ }
344
+ });
345
+ return { executionContext, result: { status: "success", output: result?.result } };
346
+ }
347
+ );
348
+ Object.assign(executionContext, res.executionContext);
349
+ return {
350
+ ...res.result,
351
+ startedAt,
352
+ endedAt: Date.now(),
353
+ payload: inputData,
354
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
355
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
356
+ };
357
+ }
358
+ };
359
+ var InngestPubSub = class extends PubSub {
360
+ inngest;
361
+ workflowId;
362
+ publishFn;
363
+ subscriptions = /* @__PURE__ */ new Map();
364
+ constructor(inngest, workflowId, publishFn) {
365
+ super();
366
+ this.inngest = inngest;
367
+ this.workflowId = workflowId;
368
+ this.publishFn = publishFn;
369
+ }
370
+ /**
371
+ * Publish an event to Inngest's realtime system.
372
+ *
373
+ * Topic format: "workflow.events.v2.{runId}"
374
+ * Maps to Inngest channel: "workflow:{workflowId}:{runId}"
375
+ */
376
+ async publish(topic, event) {
377
+ if (!this.publishFn) {
378
+ return;
379
+ }
380
+ const match = topic.match(/^workflow\.events\.v2\.(.+)$/);
381
+ if (!match) {
382
+ return;
383
+ }
384
+ const runId = match[1];
385
+ try {
386
+ await this.publishFn({
387
+ channel: `workflow:${this.workflowId}:${runId}`,
388
+ topic: "watch",
389
+ data: event.data
390
+ });
391
+ } catch (err) {
392
+ console.error("InngestPubSub publish error:", err?.message ?? err);
393
+ }
394
+ }
395
+ /**
396
+ * Subscribe to events from Inngest's realtime system.
397
+ *
398
+ * Topic format: "workflow.events.v2.{runId}"
399
+ * Maps to Inngest channel: "workflow:{workflowId}:{runId}"
400
+ */
401
+ async subscribe(topic, cb) {
402
+ const match = topic.match(/^workflow\.events\.v2\.(.+)$/);
403
+ if (!match || !match[1]) {
404
+ return;
405
+ }
406
+ const runId = match[1];
407
+ if (this.subscriptions.has(topic)) {
408
+ this.subscriptions.get(topic).callbacks.add(cb);
409
+ return;
410
+ }
411
+ const callbacks = /* @__PURE__ */ new Set([cb]);
412
+ const channel = `workflow:${this.workflowId}:${runId}`;
413
+ const streamPromise = subscribe(
414
+ {
415
+ channel,
416
+ topics: ["watch"],
417
+ app: this.inngest
418
+ },
419
+ (message) => {
420
+ const event = {
421
+ id: crypto.randomUUID(),
422
+ type: "watch",
423
+ runId,
424
+ data: message.data,
425
+ createdAt: /* @__PURE__ */ new Date()
426
+ };
427
+ for (const callback of callbacks) {
428
+ callback(event);
429
+ }
430
+ }
431
+ );
432
+ this.subscriptions.set(topic, {
433
+ unsubscribe: () => {
434
+ streamPromise.then((stream) => stream.cancel()).catch((err) => {
435
+ console.error("InngestPubSub unsubscribe error:", err);
436
+ });
437
+ },
438
+ callbacks
439
+ });
440
+ }
441
+ /**
442
+ * Unsubscribe a callback from a topic.
443
+ * If no callbacks remain, the underlying Inngest subscription is cancelled.
444
+ */
445
+ async unsubscribe(topic, cb) {
446
+ const sub = this.subscriptions.get(topic);
447
+ if (!sub) {
448
+ return;
449
+ }
450
+ sub.callbacks.delete(cb);
451
+ if (sub.callbacks.size === 0) {
452
+ sub.unsubscribe();
453
+ this.subscriptions.delete(topic);
454
+ }
455
+ }
456
+ /**
457
+ * Flush any pending operations. No-op for Inngest.
458
+ */
459
+ async flush() {
460
+ }
461
+ /**
462
+ * Clean up all subscriptions during graceful shutdown.
463
+ */
464
+ async close() {
465
+ for (const [, sub] of this.subscriptions) {
466
+ sub.unsubscribe();
467
+ }
468
+ this.subscriptions.clear();
469
+ }
470
+ };
37
471
  var InngestRun = class extends Run {
38
472
  inngest;
39
473
  serializedStepGraph;
@@ -45,71 +479,125 @@ var InngestRun = class extends Run {
45
479
  this.#mastra = params.mastra;
46
480
  }
47
481
  async getRuns(eventId) {
48
- const response = await fetch(`${this.inngest.apiBaseUrl ?? "https://api.inngest.com"}/v1/events/${eventId}/runs`, {
49
- headers: {
50
- Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`
482
+ const maxRetries = 3;
483
+ let lastError = null;
484
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
485
+ try {
486
+ const response = await fetch(
487
+ `${this.inngest.apiBaseUrl ?? "https://api.inngest.com"}/v1/events/${eventId}/runs`,
488
+ {
489
+ headers: {
490
+ Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`
491
+ }
492
+ }
493
+ );
494
+ if (response.status === 429) {
495
+ const retryAfter = parseInt(response.headers.get("retry-after") || "2", 10);
496
+ await new Promise((resolve) => setTimeout(resolve, retryAfter * 1e3));
497
+ continue;
498
+ }
499
+ if (!response.ok) {
500
+ throw new Error(`Inngest API error: ${response.status} ${response.statusText}`);
501
+ }
502
+ const text = await response.text();
503
+ if (!text) {
504
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * (attempt + 1)));
505
+ continue;
506
+ }
507
+ const json = JSON.parse(text);
508
+ return json.data;
509
+ } catch (error) {
510
+ lastError = error;
511
+ if (attempt < maxRetries - 1) {
512
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
513
+ }
51
514
  }
52
- });
53
- const json = await response.json();
54
- return json.data;
515
+ }
516
+ throw new NonRetriableError(`Failed to get runs after ${maxRetries} attempts: ${lastError?.message}`);
55
517
  }
56
- async getRunOutput(eventId) {
57
- let runs = await this.getRuns(eventId);
58
- while (runs?.[0]?.status !== "Completed" || runs?.[0]?.event_id !== eventId) {
59
- await new Promise((resolve) => setTimeout(resolve, 1e3));
60
- runs = await this.getRuns(eventId);
518
+ async getRunOutput(eventId, maxWaitMs = 3e5) {
519
+ const startTime = Date.now();
520
+ const storage = this.#mastra?.getStorage();
521
+ while (Date.now() - startTime < maxWaitMs) {
522
+ let runs;
523
+ try {
524
+ runs = await this.getRuns(eventId);
525
+ } catch (error) {
526
+ if (error instanceof NonRetriableError) {
527
+ throw error;
528
+ }
529
+ throw new NonRetriableError(
530
+ `Failed to poll workflow status: ${error instanceof Error ? error.message : String(error)}`
531
+ );
532
+ }
533
+ if (runs?.[0]?.status === "Completed" && runs?.[0]?.event_id === eventId) {
534
+ return runs[0];
535
+ }
61
536
  if (runs?.[0]?.status === "Failed") {
62
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
537
+ const snapshot = await storage?.loadWorkflowSnapshot({
63
538
  workflowName: this.workflowId,
64
539
  runId: this.runId
65
540
  });
541
+ if (snapshot?.context) {
542
+ snapshot.context = hydrateSerializedStepErrors(snapshot.context);
543
+ }
66
544
  return {
67
- output: { result: { steps: snapshot?.context, status: "failed", error: runs?.[0]?.output?.message } }
545
+ output: {
546
+ result: {
547
+ steps: snapshot?.context,
548
+ status: "failed",
549
+ // Get the original error from NonRetriableError's cause (which contains the workflow result)
550
+ error: getErrorFromUnknown(runs?.[0]?.output?.cause?.error, { serializeStack: false })
551
+ }
552
+ }
68
553
  };
69
554
  }
70
555
  if (runs?.[0]?.status === "Cancelled") {
71
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
556
+ const snapshot = await storage?.loadWorkflowSnapshot({
72
557
  workflowName: this.workflowId,
73
558
  runId: this.runId
74
559
  });
75
560
  return { output: { result: { steps: snapshot?.context, status: "canceled" } } };
76
561
  }
562
+ await new Promise((resolve) => setTimeout(resolve, 1e3 + Math.random() * 1e3));
77
563
  }
78
- return runs?.[0];
79
- }
80
- async sendEvent(event, data) {
81
- await this.inngest.send({
82
- name: `user-event-${event}`,
83
- data
84
- });
564
+ throw new NonRetriableError(`Workflow did not complete within ${maxWaitMs}ms`);
85
565
  }
86
566
  async cancel() {
567
+ const storage = this.#mastra?.getStorage();
87
568
  await this.inngest.send({
88
569
  name: `cancel.workflow.${this.workflowId}`,
89
570
  data: {
90
571
  runId: this.runId
91
572
  }
92
573
  });
93
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
574
+ const snapshot = await storage?.loadWorkflowSnapshot({
94
575
  workflowName: this.workflowId,
95
576
  runId: this.runId
96
577
  });
97
578
  if (snapshot) {
98
- await this.#mastra?.storage?.persistWorkflowSnapshot({
579
+ await storage?.persistWorkflowSnapshot({
99
580
  workflowName: this.workflowId,
100
581
  runId: this.runId,
101
582
  resourceId: this.resourceId,
102
583
  snapshot: {
103
584
  ...snapshot,
104
- status: "canceled"
585
+ status: "canceled",
586
+ value: snapshot.value
105
587
  }
106
588
  });
107
589
  }
108
590
  }
109
- async start({
110
- inputData,
111
- initialState
112
- }) {
591
+ async start(params) {
592
+ return this._start(params);
593
+ }
594
+ /**
595
+ * Starts the workflow execution without waiting for completion (fire-and-forget).
596
+ * Returns immediately with the runId after sending the event to Inngest.
597
+ * The workflow executes independently in Inngest.
598
+ * Use this when you don't need to wait for the result or want to avoid polling failures.
599
+ */
600
+ async startAsync(params) {
113
601
  await this.#mastra.getStorage()?.persistWorkflowSnapshot({
114
602
  workflowName: this.workflowId,
115
603
  runId: this.runId,
@@ -117,37 +605,87 @@ var InngestRun = class extends Run {
117
605
  snapshot: {
118
606
  runId: this.runId,
119
607
  serializedStepGraph: this.serializedStepGraph,
608
+ status: "running",
120
609
  value: {},
121
610
  context: {},
122
611
  activePaths: [],
123
612
  suspendedPaths: {},
613
+ activeStepsPath: {},
614
+ resumeLabels: {},
124
615
  waitingPaths: {},
125
- timestamp: Date.now(),
126
- status: "running"
616
+ timestamp: Date.now()
127
617
  }
128
618
  });
129
- const inputDataToUse = await this._validateInput(inputData);
130
- const initialStateToUse = await this._validateInitialState(initialState ?? {});
619
+ const inputDataToUse = await this._validateInput(params.inputData);
620
+ const initialStateToUse = await this._validateInitialState(params.initialState ?? {});
131
621
  const eventOutput = await this.inngest.send({
132
622
  name: `workflow.${this.workflowId}`,
133
623
  data: {
134
624
  inputData: inputDataToUse,
135
625
  initialState: initialStateToUse,
136
626
  runId: this.runId,
137
- resourceId: this.resourceId
627
+ resourceId: this.resourceId,
628
+ outputOptions: params.outputOptions,
629
+ tracingOptions: params.tracingOptions,
630
+ requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {}
138
631
  }
139
632
  });
140
633
  const eventId = eventOutput.ids[0];
141
634
  if (!eventId) {
142
635
  throw new Error("Event ID is not set");
143
636
  }
144
- const runOutput = await this.getRunOutput(eventId);
145
- const result = runOutput?.output?.result;
146
- if (result.status === "failed") {
147
- result.error = new Error(result.error);
148
- }
149
- if (result.status !== "suspended") {
150
- this.cleanup?.();
637
+ return { runId: this.runId };
638
+ }
639
+ async _start({
640
+ inputData,
641
+ initialState,
642
+ outputOptions,
643
+ tracingOptions,
644
+ format,
645
+ requestContext
646
+ }) {
647
+ await this.#mastra.getStorage()?.persistWorkflowSnapshot({
648
+ workflowName: this.workflowId,
649
+ runId: this.runId,
650
+ resourceId: this.resourceId,
651
+ snapshot: {
652
+ runId: this.runId,
653
+ serializedStepGraph: this.serializedStepGraph,
654
+ status: "running",
655
+ value: {},
656
+ context: {},
657
+ activePaths: [],
658
+ suspendedPaths: {},
659
+ activeStepsPath: {},
660
+ resumeLabels: {},
661
+ waitingPaths: {},
662
+ timestamp: Date.now()
663
+ }
664
+ });
665
+ const inputDataToUse = await this._validateInput(inputData);
666
+ const initialStateToUse = await this._validateInitialState(initialState ?? {});
667
+ const eventOutput = await this.inngest.send({
668
+ name: `workflow.${this.workflowId}`,
669
+ data: {
670
+ inputData: inputDataToUse,
671
+ initialState: initialStateToUse,
672
+ runId: this.runId,
673
+ resourceId: this.resourceId,
674
+ outputOptions,
675
+ tracingOptions,
676
+ format,
677
+ requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {}
678
+ }
679
+ });
680
+ const eventId = eventOutput.ids[0];
681
+ if (!eventId) {
682
+ throw new Error("Event ID is not set");
683
+ }
684
+ const runOutput = await this.getRunOutput(eventId);
685
+ const result = runOutput?.output?.result;
686
+ this.hydrateFailedResult(result);
687
+ if (result.status !== "suspended") {
688
+ this.cleanup?.();
151
689
  }
152
690
  return result;
153
691
  }
@@ -163,15 +701,24 @@ var InngestRun = class extends Run {
163
701
  return p;
164
702
  }
165
703
  async _resume(params) {
166
- const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
167
- (step) => typeof step === "string" ? step : step?.id
168
- );
169
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
704
+ const storage = this.#mastra?.getStorage();
705
+ let steps = [];
706
+ if (typeof params.step === "string") {
707
+ steps = params.step.split(".");
708
+ } else {
709
+ steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
710
+ (step) => typeof step === "string" ? step : step?.id
711
+ );
712
+ }
713
+ const snapshot = await storage?.loadWorkflowSnapshot({
170
714
  workflowName: this.workflowId,
171
715
  runId: this.runId
172
716
  });
173
717
  const suspendedStep = this.workflowSteps[steps?.[0] ?? ""];
174
718
  const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);
719
+ const persistedRequestContext = snapshot?.requestContext ?? {};
720
+ const newRequestContext = params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {};
721
+ const mergedRequestContext = { ...persistedRequestContext, ...newRequestContext };
175
722
  const eventOutput = await this.inngest.send({
176
723
  name: `workflow.${this.workflowId}`,
177
724
  data: {
@@ -184,9 +731,9 @@ var InngestRun = class extends Run {
184
731
  steps,
185
732
  stepResults: snapshot?.context,
186
733
  resumePayload: resumeDataToUse,
187
- // @ts-ignore
188
- resumePath: snapshot?.suspendedPaths?.[steps?.[0]]
189
- }
734
+ resumePath: steps?.[0] ? snapshot?.suspendedPaths?.[steps?.[0]] : void 0
735
+ },
736
+ requestContext: mergedRequestContext
190
737
  }
191
738
  });
192
739
  const eventId = eventOutput.ids[0];
@@ -195,17 +742,105 @@ var InngestRun = class extends Run {
195
742
  }
196
743
  const runOutput = await this.getRunOutput(eventId);
197
744
  const result = runOutput?.output?.result;
198
- if (result.status === "failed") {
199
- result.error = new Error(result.error);
745
+ this.hydrateFailedResult(result);
746
+ return result;
747
+ }
748
+ async timeTravel(params) {
749
+ const p = this._timeTravel(params).then((result) => {
750
+ if (result.status !== "suspended") {
751
+ this.closeStreamAction?.().catch(() => {
752
+ });
753
+ }
754
+ return result;
755
+ });
756
+ this.executionResults = p;
757
+ return p;
758
+ }
759
+ async _timeTravel(params) {
760
+ if (!params.step || Array.isArray(params.step) && params.step?.length === 0) {
761
+ throw new Error("Step is required and must be a valid step or array of steps");
762
+ }
763
+ let steps = [];
764
+ if (typeof params.step === "string") {
765
+ steps = params.step.split(".");
766
+ } else {
767
+ steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
768
+ (step) => typeof step === "string" ? step : step?.id
769
+ );
770
+ }
771
+ if (steps.length === 0) {
772
+ throw new Error("No steps provided to timeTravel");
773
+ }
774
+ const storage = this.#mastra?.getStorage();
775
+ const snapshot = await storage?.loadWorkflowSnapshot({
776
+ workflowName: this.workflowId,
777
+ runId: this.runId
778
+ });
779
+ if (!snapshot) {
780
+ await storage?.persistWorkflowSnapshot({
781
+ workflowName: this.workflowId,
782
+ runId: this.runId,
783
+ resourceId: this.resourceId,
784
+ snapshot: {
785
+ runId: this.runId,
786
+ serializedStepGraph: this.serializedStepGraph,
787
+ status: "pending",
788
+ value: {},
789
+ context: {},
790
+ activePaths: [],
791
+ suspendedPaths: {},
792
+ activeStepsPath: {},
793
+ resumeLabels: {},
794
+ waitingPaths: {},
795
+ timestamp: Date.now()
796
+ }
797
+ });
200
798
  }
799
+ if (snapshot?.status === "running") {
800
+ throw new Error("This workflow run is still running, cannot time travel");
801
+ }
802
+ let inputDataToUse = params.inputData;
803
+ if (inputDataToUse && steps.length === 1) {
804
+ inputDataToUse = await this._validateTimetravelInputData(params.inputData, this.workflowSteps[steps[0]]);
805
+ }
806
+ const timeTravelData = createTimeTravelExecutionParams({
807
+ steps,
808
+ inputData: inputDataToUse,
809
+ resumeData: params.resumeData,
810
+ context: params.context,
811
+ nestedStepsContext: params.nestedStepsContext,
812
+ snapshot: snapshot ?? { context: {} },
813
+ graph: this.executionGraph,
814
+ initialState: params.initialState
815
+ });
816
+ const eventOutput = await this.inngest.send({
817
+ name: `workflow.${this.workflowId}`,
818
+ data: {
819
+ initialState: timeTravelData.state,
820
+ runId: this.runId,
821
+ workflowId: this.workflowId,
822
+ stepResults: timeTravelData.stepResults,
823
+ timeTravel: timeTravelData,
824
+ tracingOptions: params.tracingOptions,
825
+ outputOptions: params.outputOptions,
826
+ requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {}
827
+ }
828
+ });
829
+ const eventId = eventOutput.ids[0];
830
+ if (!eventId) {
831
+ throw new Error("Event ID is not set");
832
+ }
833
+ const runOutput = await this.getRunOutput(eventId);
834
+ const result = runOutput?.output?.result;
835
+ this.hydrateFailedResult(result);
201
836
  return result;
202
837
  }
203
- watch(cb, type = "watch") {
838
+ watch(cb) {
204
839
  let active = true;
205
840
  const streamPromise = subscribe(
206
841
  {
207
842
  channel: `workflow:${this.workflowId}:${this.runId}`,
208
- topics: [type],
843
+ topics: ["watch"],
209
844
  app: this.inngest
210
845
  },
211
846
  (message) => {
@@ -223,20 +858,35 @@ var InngestRun = class extends Run {
223
858
  });
224
859
  };
225
860
  }
226
- stream({ inputData, runtimeContext } = {}) {
861
+ streamLegacy({ inputData, requestContext } = {}) {
227
862
  const { readable, writable } = new TransformStream();
228
863
  const writer = writable.getWriter();
864
+ void writer.write({
865
+ // @ts-ignore
866
+ type: "start",
867
+ // @ts-ignore
868
+ payload: { runId: this.runId }
869
+ });
229
870
  const unwatch = this.watch(async (event) => {
230
871
  try {
231
872
  const e = {
232
873
  ...event,
233
874
  type: event.type.replace("workflow-", "")
234
875
  };
876
+ if (e.type === "step-output") {
877
+ e.type = e.payload.output.type;
878
+ e.payload = e.payload.output.payload;
879
+ }
235
880
  await writer.write(e);
236
881
  } catch {
237
882
  }
238
- }, "watch-v2");
883
+ });
239
884
  this.closeStreamAction = async () => {
885
+ await writer.write({
886
+ type: "finish",
887
+ // @ts-ignore
888
+ payload: { runId: this.runId }
889
+ });
240
890
  unwatch();
241
891
  try {
242
892
  await writer.close();
@@ -246,7 +896,7 @@ var InngestRun = class extends Run {
246
896
  writer.releaseLock();
247
897
  }
248
898
  };
249
- this.executionResults = this.start({ inputData, runtimeContext }).then((result) => {
899
+ this.executionResults = this._start({ inputData, requestContext, format: "legacy" }).then((result) => {
250
900
  if (result.status !== "suspended") {
251
901
  this.closeStreamAction?.().catch(() => {
252
902
  });
@@ -258,7 +908,166 @@ var InngestRun = class extends Run {
258
908
  getWorkflowState: () => this.executionResults
259
909
  };
260
910
  }
911
+ stream({
912
+ inputData,
913
+ requestContext,
914
+ tracingOptions,
915
+ closeOnSuspend = true,
916
+ initialState,
917
+ outputOptions
918
+ } = {}) {
919
+ if (this.closeStreamAction && this.streamOutput) {
920
+ return this.streamOutput;
921
+ }
922
+ this.closeStreamAction = async () => {
923
+ };
924
+ const self = this;
925
+ const stream = new ReadableStream({
926
+ async start(controller) {
927
+ const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {
928
+ controller.enqueue({
929
+ type,
930
+ runId: self.runId,
931
+ from,
932
+ payload: {
933
+ stepName: payload?.id,
934
+ ...payload
935
+ }
936
+ });
937
+ });
938
+ self.closeStreamAction = async () => {
939
+ unwatch();
940
+ try {
941
+ await controller.close();
942
+ } catch (err) {
943
+ console.error("Error closing stream:", err);
944
+ }
945
+ };
946
+ const executionResultsPromise = self._start({
947
+ inputData,
948
+ requestContext,
949
+ // tracingContext, // We are not able to pass a reference to a span here, what to do?
950
+ initialState,
951
+ tracingOptions,
952
+ outputOptions,
953
+ format: "vnext"
954
+ });
955
+ let executionResults;
956
+ try {
957
+ executionResults = await executionResultsPromise;
958
+ if (closeOnSuspend) {
959
+ self.closeStreamAction?.().catch(() => {
960
+ });
961
+ } else if (executionResults.status !== "suspended") {
962
+ self.closeStreamAction?.().catch(() => {
963
+ });
964
+ }
965
+ if (self.streamOutput) {
966
+ self.streamOutput.updateResults(
967
+ executionResults
968
+ );
969
+ }
970
+ } catch (err) {
971
+ self.streamOutput?.rejectResults(err);
972
+ self.closeStreamAction?.().catch(() => {
973
+ });
974
+ }
975
+ }
976
+ });
977
+ this.streamOutput = new WorkflowRunOutput({
978
+ runId: this.runId,
979
+ workflowId: this.workflowId,
980
+ stream
981
+ });
982
+ return this.streamOutput;
983
+ }
984
+ streamVNext(args = {}) {
985
+ return this.stream(args);
986
+ }
987
+ timeTravelStream({
988
+ inputData,
989
+ resumeData,
990
+ initialState,
991
+ step,
992
+ context,
993
+ nestedStepsContext,
994
+ requestContext,
995
+ tracingOptions,
996
+ outputOptions
997
+ }) {
998
+ this.closeStreamAction = async () => {
999
+ };
1000
+ const self = this;
1001
+ const stream = new ReadableStream({
1002
+ async start(controller) {
1003
+ const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {
1004
+ controller.enqueue({
1005
+ type,
1006
+ runId: self.runId,
1007
+ from,
1008
+ payload: {
1009
+ stepName: payload?.id,
1010
+ ...payload
1011
+ }
1012
+ });
1013
+ });
1014
+ self.closeStreamAction = async () => {
1015
+ unwatch();
1016
+ try {
1017
+ controller.close();
1018
+ } catch (err) {
1019
+ console.error("Error closing stream:", err);
1020
+ }
1021
+ };
1022
+ const executionResultsPromise = self._timeTravel({
1023
+ inputData,
1024
+ step,
1025
+ context,
1026
+ nestedStepsContext,
1027
+ resumeData,
1028
+ initialState,
1029
+ requestContext,
1030
+ tracingOptions,
1031
+ outputOptions
1032
+ });
1033
+ self.executionResults = executionResultsPromise;
1034
+ let executionResults;
1035
+ try {
1036
+ executionResults = await executionResultsPromise;
1037
+ self.closeStreamAction?.().catch(() => {
1038
+ });
1039
+ if (self.streamOutput) {
1040
+ self.streamOutput.updateResults(executionResults);
1041
+ }
1042
+ } catch (err) {
1043
+ self.streamOutput?.rejectResults(err);
1044
+ self.closeStreamAction?.().catch(() => {
1045
+ });
1046
+ }
1047
+ }
1048
+ });
1049
+ this.streamOutput = new WorkflowRunOutput({
1050
+ runId: this.runId,
1051
+ workflowId: this.workflowId,
1052
+ stream
1053
+ });
1054
+ return this.streamOutput;
1055
+ }
1056
+ /**
1057
+ * Hydrates errors in a failed workflow result back to proper Error instances.
1058
+ * This ensures error.cause chains and custom properties are preserved.
1059
+ */
1060
+ hydrateFailedResult(result) {
1061
+ if (result.status === "failed") {
1062
+ result.error = getErrorFromUnknown(result.error, { serializeStack: false });
1063
+ if (result.steps) {
1064
+ hydrateSerializedStepErrors(result.steps);
1065
+ }
1066
+ }
1067
+ }
261
1068
  };
1069
+
1070
+ // src/workflow.ts
262
1071
  var InngestWorkflow = class _InngestWorkflow extends Workflow {
263
1072
  #mastra;
264
1073
  inngest;
@@ -267,6 +1076,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
267
1076
  constructor(params, inngest) {
268
1077
  const { concurrency, rateLimit, throttle, debounce, priority, ...workflowParams } = params;
269
1078
  super(workflowParams);
1079
+ this.engineType = "inngest";
270
1080
  const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(
271
1081
  ([_, value]) => value !== void 0
272
1082
  );
@@ -274,13 +1084,13 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
274
1084
  this.#mastra = params.mastra;
275
1085
  this.inngest = inngest;
276
1086
  }
277
- async getWorkflowRuns(args) {
1087
+ async listWorkflowRuns(args) {
278
1088
  const storage = this.#mastra?.getStorage();
279
1089
  if (!storage) {
280
1090
  this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
281
1091
  return { runs: [], total: 0 };
282
1092
  }
283
- return storage.getWorkflowRuns({ workflowName: this.id, ...args ?? {} });
1093
+ return storage.listWorkflowRuns({ workflowName: this.id, ...args ?? {} });
284
1094
  }
285
1095
  async getWorkflowRunById(runId) {
286
1096
  const storage = this.#mastra?.getStorage();
@@ -292,6 +1102,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
292
1102
  return run ?? (this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null);
293
1103
  }
294
1104
  __registerMastra(mastra) {
1105
+ super.__registerMastra(mastra);
295
1106
  this.#mastra = mastra;
296
1107
  this.executionEngine.__registerMastra(mastra);
297
1108
  const updateNested = (step) => {
@@ -309,16 +1120,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
309
1120
  }
310
1121
  }
311
1122
  }
312
- /**
313
- * @deprecated Use createRunAsync() instead.
314
- * @throws {Error} Always throws an error directing users to use createRunAsync()
315
- */
316
- createRun(_options) {
317
- throw new Error(
318
- "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = workflow.createRun();\n After: const run = await workflow.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
319
- );
320
- }
321
- async createRunAsync(options) {
1123
+ async createRun(options) {
322
1124
  const runIdToUse = options?.runId || randomUUID();
323
1125
  const run = this.runs.get(runIdToUse) ?? new InngestRun(
324
1126
  {
@@ -331,7 +1133,9 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
331
1133
  mastra: this.#mastra,
332
1134
  retryConfig: this.retryConfig,
333
1135
  cleanup: () => this.runs.delete(runIdToUse),
334
- workflowSteps: this.steps
1136
+ workflowSteps: this.steps,
1137
+ workflowEngineType: this.engineType,
1138
+ validateInputs: this.options.validateInputs
335
1139
  },
336
1140
  this.inngest
337
1141
  );
@@ -340,7 +1144,9 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
340
1144
  workflowStatus: run.workflowRunStatus,
341
1145
  stepResults: {}
342
1146
  });
343
- const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse, false);
1147
+ const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse, {
1148
+ withNestedWorkflows: false
1149
+ });
344
1150
  if (!workflowSnapshotInStorage && shouldPersistSnapshot) {
345
1151
  await this.mastra?.getStorage()?.persistWorkflowSnapshot({
346
1152
  workflowName: this.id,
@@ -352,12 +1158,13 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
352
1158
  value: {},
353
1159
  context: {},
354
1160
  activePaths: [],
1161
+ activeStepsPath: {},
355
1162
  waitingPaths: {},
356
1163
  serializedStepGraph: this.serializedStepGraph,
357
1164
  suspendedPaths: {},
1165
+ resumeLabels: {},
358
1166
  result: void 0,
359
1167
  error: void 0,
360
- // @ts-ignore
361
1168
  timestamp: Date.now()
362
1169
  }
363
1170
  });
@@ -371,42 +1178,20 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
371
1178
  this.function = this.inngest.createFunction(
372
1179
  {
373
1180
  id: `workflow.${this.id}`,
374
- // @ts-ignore
375
- retries: this.retryConfig?.attempts ?? 0,
1181
+ retries: Math.min(this.retryConfig?.attempts ?? 0, 20),
376
1182
  cancelOn: [{ event: `cancel.workflow.${this.id}` }],
377
1183
  // Spread flow control configuration
378
1184
  ...this.flowControlConfig
379
1185
  },
380
1186
  { event: `workflow.${this.id}` },
381
1187
  async ({ event, step, attempt, publish }) => {
382
- let { inputData, initialState, runId, resourceId, resume, outputOptions } = event.data;
1188
+ let { inputData, initialState, runId, resourceId, resume, outputOptions, format, timeTravel } = event.data;
383
1189
  if (!runId) {
384
1190
  runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
385
1191
  return randomUUID();
386
1192
  });
387
1193
  }
388
- const emitter = {
389
- emit: async (event2, data) => {
390
- if (!publish) {
391
- return;
392
- }
393
- try {
394
- await publish({
395
- channel: `workflow:${this.id}:${runId}`,
396
- topic: event2,
397
- data
398
- });
399
- } catch (err) {
400
- this.logger.error("Error emitting event: " + (err?.stack ?? err?.message ?? err));
401
- }
402
- },
403
- on: (_event, _callback) => {
404
- },
405
- off: (_event, _callback) => {
406
- },
407
- once: (_event, _callback) => {
408
- }
409
- };
1194
+ const pubsub = new InngestPubSub(this.inngest, this.id, publish);
410
1195
  const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);
411
1196
  const result = await engine.execute({
412
1197
  workflowId: this.id,
@@ -416,17 +1201,29 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
416
1201
  serializedStepGraph: this.serializedStepGraph,
417
1202
  input: inputData,
418
1203
  initialState,
419
- emitter,
1204
+ pubsub,
420
1205
  retryConfig: this.retryConfig,
421
- runtimeContext: new RuntimeContext(),
422
- // TODO
1206
+ requestContext: new RequestContext(Object.entries(event.data.requestContext ?? {})),
423
1207
  resume,
1208
+ timeTravel,
1209
+ format,
424
1210
  abortController: new AbortController(),
425
- currentSpan: void 0,
426
- // TODO: Pass actual parent AI span from workflow execution context
427
- outputOptions
1211
+ // currentSpan: undefined, // TODO: Pass actual parent Span from workflow execution context
1212
+ outputOptions,
1213
+ outputWriter: async (chunk) => {
1214
+ try {
1215
+ await pubsub.publish(`workflow.events.v2.${runId}`, {
1216
+ type: "watch",
1217
+ runId,
1218
+ data: chunk
1219
+ });
1220
+ } catch (err) {
1221
+ this.logger.debug?.("Failed to publish watch event:", err);
1222
+ }
1223
+ }
428
1224
  });
429
1225
  await step.run(`workflow.${this.id}.finalize`, async () => {
1226
+ await engine.invokeLifecycleCallbacksInternal(result);
430
1227
  if (result.status === "failed") {
431
1228
  throw new NonRetriableError(`Workflow failed`, {
432
1229
  cause: result
@@ -456,90 +1253,147 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
456
1253
  return [this.getFunction(), ...this.getNestedFunctions(this.executionGraph.steps)];
457
1254
  }
458
1255
  };
1256
+ function serve({
1257
+ mastra,
1258
+ inngest,
1259
+ functions: userFunctions = [],
1260
+ registerOptions
1261
+ }) {
1262
+ const wfs = mastra.listWorkflows();
1263
+ const workflowFunctions = Array.from(
1264
+ new Set(
1265
+ Object.values(wfs).flatMap((wf) => {
1266
+ if (wf instanceof InngestWorkflow) {
1267
+ wf.__registerMastra(mastra);
1268
+ return wf.getFunctions();
1269
+ }
1270
+ return [];
1271
+ })
1272
+ )
1273
+ );
1274
+ return serve$1({
1275
+ ...registerOptions,
1276
+ client: inngest,
1277
+ functions: [...workflowFunctions, ...userFunctions]
1278
+ });
1279
+ }
1280
+
1281
+ // src/types.ts
1282
+ var _compatibilityCheck = true;
1283
+
1284
+ // src/index.ts
459
1285
  function isAgent(params) {
460
1286
  return params?.component === "AGENT";
461
1287
  }
462
1288
  function isTool(params) {
463
1289
  return params instanceof Tool;
464
1290
  }
465
- function createStep(params) {
1291
+ function isInngestWorkflow(params) {
1292
+ return params instanceof InngestWorkflow;
1293
+ }
1294
+ function createStep(params, agentOptions) {
1295
+ if (isInngestWorkflow(params)) {
1296
+ return params;
1297
+ }
466
1298
  if (isAgent(params)) {
1299
+ const outputSchema = agentOptions?.structuredOutput?.schema ?? z.object({ text: z.string() });
467
1300
  return {
468
1301
  id: params.name,
469
1302
  description: params.getDescription(),
470
- // @ts-ignore
471
1303
  inputSchema: z.object({
472
1304
  prompt: z.string()
1305
+ // resourceId: z.string().optional(),
1306
+ // threadId: z.string().optional(),
473
1307
  }),
474
- // @ts-ignore
475
- outputSchema: z.object({
476
- text: z.string()
477
- }),
478
- execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort, tracingContext }) => {
1308
+ outputSchema,
1309
+ execute: async ({
1310
+ inputData,
1311
+ runId,
1312
+ [PUBSUB_SYMBOL]: pubsub,
1313
+ [STREAM_FORMAT_SYMBOL]: streamFormat,
1314
+ requestContext,
1315
+ tracingContext,
1316
+ abortSignal,
1317
+ abort,
1318
+ writer
1319
+ }) => {
479
1320
  let streamPromise = {};
480
1321
  streamPromise.promise = new Promise((resolve, reject) => {
481
1322
  streamPromise.resolve = resolve;
482
1323
  streamPromise.reject = reject;
483
1324
  });
1325
+ let structuredResult = null;
484
1326
  const toolData = {
485
1327
  name: params.name,
486
1328
  args: inputData
487
1329
  };
488
- if ((await params.getLLM()).getModel().specificationVersion === `v2`) {
489
- const { fullStream } = await params.stream(inputData.prompt, {
490
- runtimeContext,
1330
+ let stream;
1331
+ if ((await params.getModel()).specificationVersion === "v1") {
1332
+ const { fullStream } = await params.streamLegacy(inputData.prompt, {
1333
+ ...agentOptions ?? {},
1334
+ // resourceId: inputData.resourceId,
1335
+ // threadId: inputData.threadId,
1336
+ requestContext,
491
1337
  tracingContext,
492
1338
  onFinish: (result) => {
1339
+ const resultWithObject = result;
1340
+ if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
1341
+ structuredResult = resultWithObject.object;
1342
+ }
493
1343
  streamPromise.resolve(result.text);
1344
+ void agentOptions?.onFinish?.(result);
494
1345
  },
495
1346
  abortSignal
496
1347
  });
497
- if (abortSignal.aborted) {
498
- return abort();
499
- }
500
- await emitter.emit("watch-v2", {
501
- type: "tool-call-streaming-start",
502
- ...toolData ?? {}
503
- });
504
- for await (const chunk of fullStream) {
505
- if (chunk.type === "text-delta") {
506
- await emitter.emit("watch-v2", {
507
- type: "tool-call-delta",
508
- ...toolData ?? {},
509
- argsTextDelta: chunk.payload.text
510
- });
511
- }
512
- }
1348
+ stream = fullStream;
513
1349
  } else {
514
- const { fullStream } = await params.streamLegacy(inputData.prompt, {
515
- runtimeContext,
1350
+ const modelOutput = await params.stream(inputData.prompt, {
1351
+ ...agentOptions ?? {},
1352
+ requestContext,
516
1353
  tracingContext,
517
1354
  onFinish: (result) => {
1355
+ const resultWithObject = result;
1356
+ if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
1357
+ structuredResult = resultWithObject.object;
1358
+ }
518
1359
  streamPromise.resolve(result.text);
1360
+ void agentOptions?.onFinish?.(result);
519
1361
  },
520
1362
  abortSignal
521
1363
  });
522
- if (abortSignal.aborted) {
523
- return abort();
524
- }
525
- await emitter.emit("watch-v2", {
526
- type: "tool-call-streaming-start",
527
- ...toolData ?? {}
1364
+ stream = modelOutput.fullStream;
1365
+ }
1366
+ if (streamFormat === "legacy") {
1367
+ await pubsub.publish(`workflow.events.v2.${runId}`, {
1368
+ type: "watch",
1369
+ runId,
1370
+ data: { type: "tool-call-streaming-start", ...toolData ?? {} }
528
1371
  });
529
- for await (const chunk of fullStream) {
1372
+ for await (const chunk of stream) {
530
1373
  if (chunk.type === "text-delta") {
531
- await emitter.emit("watch-v2", {
532
- type: "tool-call-delta",
533
- ...toolData ?? {},
534
- argsTextDelta: chunk.textDelta
1374
+ await pubsub.publish(`workflow.events.v2.${runId}`, {
1375
+ type: "watch",
1376
+ runId,
1377
+ data: { type: "tool-call-delta", ...toolData ?? {}, argsTextDelta: chunk.textDelta }
535
1378
  });
536
1379
  }
537
1380
  }
1381
+ await pubsub.publish(`workflow.events.v2.${runId}`, {
1382
+ type: "watch",
1383
+ runId,
1384
+ data: { type: "tool-call-streaming-finish", ...toolData ?? {} }
1385
+ });
1386
+ } else {
1387
+ for await (const chunk of stream) {
1388
+ await writer.write(chunk);
1389
+ }
1390
+ }
1391
+ if (abortSignal.aborted) {
1392
+ return abort();
1393
+ }
1394
+ if (structuredResult !== null) {
1395
+ return structuredResult;
538
1396
  }
539
- await emitter.emit("watch-v2", {
540
- type: "tool-call-streaming-finish",
541
- ...toolData ?? {}
542
- });
543
1397
  return {
544
1398
  text: await streamPromise.promise
545
1399
  };
@@ -553,20 +1407,38 @@ function createStep(params) {
553
1407
  }
554
1408
  return {
555
1409
  // TODO: tool probably should have strong id type
556
- // @ts-ignore
557
1410
  id: params.id,
558
1411
  description: params.description,
559
1412
  inputSchema: params.inputSchema,
560
1413
  outputSchema: params.outputSchema,
561
- execute: async ({ inputData, mastra, runtimeContext, tracingContext, suspend, resumeData }) => {
562
- return params.execute({
563
- context: inputData,
564
- mastra: wrapMastra(mastra, tracingContext),
565
- runtimeContext,
1414
+ suspendSchema: params.suspendSchema,
1415
+ resumeSchema: params.resumeSchema,
1416
+ execute: async ({
1417
+ inputData,
1418
+ mastra,
1419
+ requestContext,
1420
+ tracingContext,
1421
+ suspend,
1422
+ resumeData,
1423
+ runId,
1424
+ workflowId,
1425
+ state,
1426
+ setState
1427
+ }) => {
1428
+ const toolContext = {
1429
+ mastra,
1430
+ requestContext,
566
1431
  tracingContext,
567
- suspend,
568
- resumeData
569
- });
1432
+ workflow: {
1433
+ runId,
1434
+ resumeData,
1435
+ suspend,
1436
+ workflowId,
1437
+ state,
1438
+ setState
1439
+ }
1440
+ };
1441
+ return params.execute(inputData, toolContext);
570
1442
  },
571
1443
  component: "TOOL"
572
1444
  };
@@ -600,6 +1472,8 @@ function init(inngest) {
600
1472
  suspendSchema: step.suspendSchema,
601
1473
  stateSchema: step.stateSchema,
602
1474
  execute: step.execute,
1475
+ retries: step.retries,
1476
+ scorers: step.scorers,
603
1477
  component: step.component
604
1478
  };
605
1479
  },
@@ -609,7 +1483,8 @@ function init(inngest) {
609
1483
  inputSchema: workflow.inputSchema,
610
1484
  outputSchema: workflow.outputSchema,
611
1485
  steps: workflow.stepDefs,
612
- mastra: workflow.mastra
1486
+ mastra: workflow.mastra,
1487
+ options: workflow.options
613
1488
  });
614
1489
  wf.setStepFlow(workflow.stepGraph);
615
1490
  wf.commit();
@@ -617,917 +1492,7 @@ function init(inngest) {
617
1492
  }
618
1493
  };
619
1494
  }
620
- var InngestExecutionEngine = class extends DefaultExecutionEngine {
621
- inngestStep;
622
- inngestAttempts;
623
- constructor(mastra, inngestStep, inngestAttempts = 0, options) {
624
- super({ mastra, options });
625
- this.inngestStep = inngestStep;
626
- this.inngestAttempts = inngestAttempts;
627
- }
628
- async execute(params) {
629
- await params.emitter.emit("watch-v2", {
630
- type: "workflow-start",
631
- payload: { runId: params.runId }
632
- });
633
- const result = await super.execute(params);
634
- await params.emitter.emit("watch-v2", {
635
- type: "workflow-finish",
636
- payload: { runId: params.runId }
637
- });
638
- return result;
639
- }
640
- async fmtReturnValue(executionSpan, emitter, stepResults, lastOutput, error) {
641
- const base = {
642
- status: lastOutput.status,
643
- steps: stepResults
644
- };
645
- if (lastOutput.status === "success") {
646
- await emitter.emit("watch", {
647
- type: "watch",
648
- payload: {
649
- workflowState: {
650
- status: lastOutput.status,
651
- steps: stepResults,
652
- result: lastOutput.output
653
- }
654
- },
655
- eventTimestamp: Date.now()
656
- });
657
- base.result = lastOutput.output;
658
- } else if (lastOutput.status === "failed") {
659
- base.error = error instanceof Error ? error?.stack ?? error.message : lastOutput?.error instanceof Error ? lastOutput.error.message : lastOutput.error ?? error ?? "Unknown error";
660
- await emitter.emit("watch", {
661
- type: "watch",
662
- payload: {
663
- workflowState: {
664
- status: lastOutput.status,
665
- steps: stepResults,
666
- result: null,
667
- error: base.error
668
- }
669
- },
670
- eventTimestamp: Date.now()
671
- });
672
- } else if (lastOutput.status === "suspended") {
673
- await emitter.emit("watch", {
674
- type: "watch",
675
- payload: {
676
- workflowState: {
677
- status: lastOutput.status,
678
- steps: stepResults,
679
- result: null,
680
- error: null
681
- }
682
- },
683
- eventTimestamp: Date.now()
684
- });
685
- const suspendedStepIds = Object.entries(stepResults).flatMap(([stepId, stepResult]) => {
686
- if (stepResult?.status === "suspended") {
687
- const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
688
- return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
689
- }
690
- return [];
691
- });
692
- base.suspended = suspendedStepIds;
693
- }
694
- executionSpan?.end();
695
- return base;
696
- }
697
- // async executeSleep({ id, duration }: { id: string; duration: number }): Promise<void> {
698
- // await this.inngestStep.sleep(id, duration);
699
- // }
700
- async executeSleep({
701
- workflowId,
702
- runId,
703
- entry,
704
- prevOutput,
705
- stepResults,
706
- emitter,
707
- abortController,
708
- runtimeContext,
709
- executionContext,
710
- writableStream,
711
- tracingContext
712
- }) {
713
- let { duration, fn } = entry;
714
- const sleepSpan = tracingContext?.currentSpan?.createChildSpan({
715
- type: AISpanType.WORKFLOW_SLEEP,
716
- name: `sleep: ${duration ? `${duration}ms` : "dynamic"}`,
717
- attributes: {
718
- durationMs: duration,
719
- sleepType: fn ? "dynamic" : "fixed"
720
- },
721
- tracingPolicy: this.options?.tracingPolicy
722
- });
723
- if (fn) {
724
- const stepCallId = randomUUID();
725
- duration = await this.inngestStep.run(`workflow.${workflowId}.sleep.${entry.id}`, async () => {
726
- return await fn({
727
- runId,
728
- workflowId,
729
- mastra: this.mastra,
730
- runtimeContext,
731
- inputData: prevOutput,
732
- state: executionContext.state,
733
- setState: (state) => {
734
- executionContext.state = state;
735
- },
736
- runCount: -1,
737
- tracingContext: {
738
- currentSpan: sleepSpan
739
- },
740
- getInitData: () => stepResults?.input,
741
- getStepResult: getStepResult.bind(this, stepResults),
742
- // TODO: this function shouldn't have suspend probably?
743
- suspend: async (_suspendPayload) => {
744
- },
745
- bail: () => {
746
- },
747
- abort: () => {
748
- abortController?.abort();
749
- },
750
- [EMITTER_SYMBOL]: emitter,
751
- // TODO: add streamVNext support
752
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
753
- engine: { step: this.inngestStep },
754
- abortSignal: abortController?.signal,
755
- writer: new ToolStream(
756
- {
757
- prefix: "workflow-step",
758
- callId: stepCallId,
759
- name: "sleep",
760
- runId
761
- },
762
- writableStream
763
- )
764
- });
765
- });
766
- sleepSpan?.update({
767
- attributes: {
768
- durationMs: duration
769
- }
770
- });
771
- }
772
- try {
773
- await this.inngestStep.sleep(entry.id, !duration || duration < 0 ? 0 : duration);
774
- sleepSpan?.end();
775
- } catch (e) {
776
- sleepSpan?.error({ error: e });
777
- throw e;
778
- }
779
- }
780
- async executeSleepUntil({
781
- workflowId,
782
- runId,
783
- entry,
784
- prevOutput,
785
- stepResults,
786
- emitter,
787
- abortController,
788
- runtimeContext,
789
- executionContext,
790
- writableStream,
791
- tracingContext
792
- }) {
793
- let { date, fn } = entry;
794
- const sleepUntilSpan = tracingContext?.currentSpan?.createChildSpan({
795
- type: AISpanType.WORKFLOW_SLEEP,
796
- name: `sleepUntil: ${date ? date.toISOString() : "dynamic"}`,
797
- attributes: {
798
- untilDate: date,
799
- durationMs: date ? Math.max(0, date.getTime() - Date.now()) : void 0,
800
- sleepType: fn ? "dynamic" : "fixed"
801
- },
802
- tracingPolicy: this.options?.tracingPolicy
803
- });
804
- if (fn) {
805
- date = await this.inngestStep.run(`workflow.${workflowId}.sleepUntil.${entry.id}`, async () => {
806
- const stepCallId = randomUUID();
807
- return await fn({
808
- runId,
809
- workflowId,
810
- mastra: this.mastra,
811
- runtimeContext,
812
- inputData: prevOutput,
813
- state: executionContext.state,
814
- setState: (state) => {
815
- executionContext.state = state;
816
- },
817
- runCount: -1,
818
- tracingContext: {
819
- currentSpan: sleepUntilSpan
820
- },
821
- getInitData: () => stepResults?.input,
822
- getStepResult: getStepResult.bind(this, stepResults),
823
- // TODO: this function shouldn't have suspend probably?
824
- suspend: async (_suspendPayload) => {
825
- },
826
- bail: () => {
827
- },
828
- abort: () => {
829
- abortController?.abort();
830
- },
831
- [EMITTER_SYMBOL]: emitter,
832
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
833
- // TODO: add streamVNext support
834
- engine: { step: this.inngestStep },
835
- abortSignal: abortController?.signal,
836
- writer: new ToolStream(
837
- {
838
- prefix: "workflow-step",
839
- callId: stepCallId,
840
- name: "sleep",
841
- runId
842
- },
843
- writableStream
844
- )
845
- });
846
- });
847
- if (date && !(date instanceof Date)) {
848
- date = new Date(date);
849
- }
850
- const time = !date ? 0 : date.getTime() - Date.now();
851
- sleepUntilSpan?.update({
852
- attributes: {
853
- durationMs: Math.max(0, time)
854
- }
855
- });
856
- }
857
- if (!(date instanceof Date)) {
858
- sleepUntilSpan?.end();
859
- return;
860
- }
861
- try {
862
- await this.inngestStep.sleepUntil(entry.id, date);
863
- sleepUntilSpan?.end();
864
- } catch (e) {
865
- sleepUntilSpan?.error({ error: e });
866
- throw e;
867
- }
868
- }
869
- async executeWaitForEvent({ event, timeout }) {
870
- const eventData = await this.inngestStep.waitForEvent(`user-event-${event}`, {
871
- event: `user-event-${event}`,
872
- timeout: timeout ?? 5e3
873
- });
874
- if (eventData === null) {
875
- throw "Timeout waiting for event";
876
- }
877
- return eventData?.data;
878
- }
879
- async executeStep({
880
- step,
881
- stepResults,
882
- executionContext,
883
- resume,
884
- prevOutput,
885
- emitter,
886
- abortController,
887
- runtimeContext,
888
- tracingContext,
889
- writableStream,
890
- disableScorers
891
- }) {
892
- const stepAISpan = tracingContext?.currentSpan?.createChildSpan({
893
- name: `workflow step: '${step.id}'`,
894
- type: AISpanType.WORKFLOW_STEP,
895
- input: prevOutput,
896
- attributes: {
897
- stepId: step.id
898
- },
899
- tracingPolicy: this.options?.tracingPolicy
900
- });
901
- const { inputData, validationError } = await validateStepInput({
902
- prevOutput,
903
- step,
904
- validateInputs: this.options?.validateInputs ?? false
905
- });
906
- const startedAt = await this.inngestStep.run(
907
- `workflow.${executionContext.workflowId}.run.${executionContext.runId}.step.${step.id}.running_ev`,
908
- async () => {
909
- const startedAt2 = Date.now();
910
- await emitter.emit("watch", {
911
- type: "watch",
912
- payload: {
913
- currentStep: {
914
- id: step.id,
915
- status: "running"
916
- },
917
- workflowState: {
918
- status: "running",
919
- steps: {
920
- ...stepResults,
921
- [step.id]: {
922
- status: "running"
923
- }
924
- },
925
- result: null,
926
- error: null
927
- }
928
- },
929
- eventTimestamp: Date.now()
930
- });
931
- await emitter.emit("watch-v2", {
932
- type: "workflow-step-start",
933
- payload: {
934
- id: step.id,
935
- status: "running",
936
- payload: inputData,
937
- startedAt: startedAt2
938
- }
939
- });
940
- return startedAt2;
941
- }
942
- );
943
- if (step instanceof InngestWorkflow) {
944
- const isResume = !!resume?.steps?.length;
945
- let result;
946
- let runId;
947
- try {
948
- if (isResume) {
949
- runId = stepResults[resume?.steps?.[0]]?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();
950
- const snapshot = await this.mastra?.getStorage()?.loadWorkflowSnapshot({
951
- workflowName: step.id,
952
- runId
953
- });
954
- const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
955
- function: step.getFunction(),
956
- data: {
957
- inputData,
958
- initialState: executionContext.state ?? snapshot?.value ?? {},
959
- runId,
960
- resume: {
961
- runId,
962
- steps: resume.steps.slice(1),
963
- stepResults: snapshot?.context,
964
- resumePayload: resume.resumePayload,
965
- // @ts-ignore
966
- resumePath: snapshot?.suspendedPaths?.[resume.steps?.[1]]
967
- },
968
- outputOptions: { includeState: true }
969
- }
970
- });
971
- result = invokeResp.result;
972
- runId = invokeResp.runId;
973
- executionContext.state = invokeResp.result.state;
974
- } else {
975
- const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
976
- function: step.getFunction(),
977
- data: {
978
- inputData,
979
- initialState: executionContext.state ?? {},
980
- outputOptions: { includeState: true }
981
- }
982
- });
983
- result = invokeResp.result;
984
- runId = invokeResp.runId;
985
- executionContext.state = invokeResp.result.state;
986
- }
987
- } catch (e) {
988
- const errorCause = e?.cause;
989
- if (errorCause && typeof errorCause === "object") {
990
- result = errorCause;
991
- runId = errorCause.runId || randomUUID();
992
- } else {
993
- runId = randomUUID();
994
- result = {
995
- status: "failed",
996
- error: e instanceof Error ? e : new Error(String(e)),
997
- steps: {},
998
- input: inputData
999
- };
1000
- }
1001
- }
1002
- const res = await this.inngestStep.run(
1003
- `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,
1004
- async () => {
1005
- if (result.status === "failed") {
1006
- await emitter.emit("watch", {
1007
- type: "watch",
1008
- payload: {
1009
- currentStep: {
1010
- id: step.id,
1011
- status: "failed",
1012
- error: result?.error
1013
- },
1014
- workflowState: {
1015
- status: "running",
1016
- steps: stepResults,
1017
- result: null,
1018
- error: null
1019
- }
1020
- },
1021
- eventTimestamp: Date.now()
1022
- });
1023
- await emitter.emit("watch-v2", {
1024
- type: "workflow-step-result",
1025
- payload: {
1026
- id: step.id,
1027
- status: "failed",
1028
- error: result?.error,
1029
- payload: prevOutput
1030
- }
1031
- });
1032
- return { executionContext, result: { status: "failed", error: result?.error } };
1033
- } else if (result.status === "suspended") {
1034
- const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
1035
- const stepRes2 = stepResult;
1036
- return stepRes2?.status === "suspended";
1037
- });
1038
- for (const [stepName, stepResult] of suspendedSteps) {
1039
- const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
1040
- executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1041
- await emitter.emit("watch", {
1042
- type: "watch",
1043
- payload: {
1044
- currentStep: {
1045
- id: step.id,
1046
- status: "suspended",
1047
- payload: stepResult.payload,
1048
- suspendPayload: {
1049
- ...stepResult?.suspendPayload,
1050
- __workflow_meta: { runId, path: suspendPath }
1051
- }
1052
- },
1053
- workflowState: {
1054
- status: "running",
1055
- steps: stepResults,
1056
- result: null,
1057
- error: null
1058
- }
1059
- },
1060
- eventTimestamp: Date.now()
1061
- });
1062
- await emitter.emit("watch-v2", {
1063
- type: "workflow-step-suspended",
1064
- payload: {
1065
- id: step.id,
1066
- status: "suspended"
1067
- }
1068
- });
1069
- return {
1070
- executionContext,
1071
- result: {
1072
- status: "suspended",
1073
- payload: stepResult.payload,
1074
- suspendPayload: {
1075
- ...stepResult?.suspendPayload,
1076
- __workflow_meta: { runId, path: suspendPath }
1077
- }
1078
- }
1079
- };
1080
- }
1081
- await emitter.emit("watch", {
1082
- type: "watch",
1083
- payload: {
1084
- currentStep: {
1085
- id: step.id,
1086
- status: "suspended",
1087
- payload: {}
1088
- },
1089
- workflowState: {
1090
- status: "running",
1091
- steps: stepResults,
1092
- result: null,
1093
- error: null
1094
- }
1095
- },
1096
- eventTimestamp: Date.now()
1097
- });
1098
- return {
1099
- executionContext,
1100
- result: {
1101
- status: "suspended",
1102
- payload: {}
1103
- }
1104
- };
1105
- }
1106
- await emitter.emit("watch", {
1107
- type: "watch",
1108
- payload: {
1109
- currentStep: {
1110
- id: step.id,
1111
- status: "success",
1112
- output: result?.result
1113
- },
1114
- workflowState: {
1115
- status: "running",
1116
- steps: stepResults,
1117
- result: null,
1118
- error: null
1119
- }
1120
- },
1121
- eventTimestamp: Date.now()
1122
- });
1123
- await emitter.emit("watch-v2", {
1124
- type: "workflow-step-result",
1125
- payload: {
1126
- id: step.id,
1127
- status: "success",
1128
- output: result?.result
1129
- }
1130
- });
1131
- await emitter.emit("watch-v2", {
1132
- type: "workflow-step-finish",
1133
- payload: {
1134
- id: step.id,
1135
- metadata: {}
1136
- }
1137
- });
1138
- return { executionContext, result: { status: "success", output: result?.result } };
1139
- }
1140
- );
1141
- Object.assign(executionContext, res.executionContext);
1142
- return {
1143
- ...res.result,
1144
- startedAt,
1145
- endedAt: Date.now(),
1146
- payload: inputData,
1147
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1148
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1149
- };
1150
- }
1151
- let stepRes;
1152
- try {
1153
- stepRes = await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}`, async () => {
1154
- let execResults;
1155
- let suspended;
1156
- let bailed;
1157
- try {
1158
- if (validationError) {
1159
- throw validationError;
1160
- }
1161
- const result = await step.execute({
1162
- runId: executionContext.runId,
1163
- mastra: this.mastra,
1164
- runtimeContext,
1165
- writableStream,
1166
- state: executionContext?.state ?? {},
1167
- setState: (state) => {
1168
- executionContext.state = state;
1169
- },
1170
- inputData,
1171
- resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
1172
- tracingContext: {
1173
- currentSpan: stepAISpan
1174
- },
1175
- getInitData: () => stepResults?.input,
1176
- getStepResult: getStepResult.bind(this, stepResults),
1177
- suspend: async (suspendPayload) => {
1178
- executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1179
- suspended = { payload: suspendPayload };
1180
- },
1181
- bail: (result2) => {
1182
- bailed = { payload: result2 };
1183
- },
1184
- resume: {
1185
- steps: resume?.steps?.slice(1) || [],
1186
- resumePayload: resume?.resumePayload,
1187
- // @ts-ignore
1188
- runId: stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId
1189
- },
1190
- [EMITTER_SYMBOL]: emitter,
1191
- engine: {
1192
- step: this.inngestStep
1193
- },
1194
- abortSignal: abortController.signal
1195
- });
1196
- const endedAt = Date.now();
1197
- execResults = {
1198
- status: "success",
1199
- output: result,
1200
- startedAt,
1201
- endedAt,
1202
- payload: inputData,
1203
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1204
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1205
- };
1206
- } catch (e) {
1207
- const stepFailure = {
1208
- status: "failed",
1209
- payload: inputData,
1210
- error: e instanceof Error ? e.message : String(e),
1211
- endedAt: Date.now(),
1212
- startedAt,
1213
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1214
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1215
- };
1216
- execResults = stepFailure;
1217
- const fallbackErrorMessage = `Step ${step.id} failed`;
1218
- stepAISpan?.error({ error: new Error(execResults.error ?? fallbackErrorMessage) });
1219
- throw new RetryAfterError(execResults.error ?? fallbackErrorMessage, executionContext.retryConfig.delay, {
1220
- cause: execResults
1221
- });
1222
- }
1223
- if (suspended) {
1224
- execResults = {
1225
- status: "suspended",
1226
- suspendPayload: suspended.payload,
1227
- payload: inputData,
1228
- suspendedAt: Date.now(),
1229
- startedAt,
1230
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1231
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1232
- };
1233
- } else if (bailed) {
1234
- execResults = {
1235
- status: "bailed",
1236
- output: bailed.payload,
1237
- payload: inputData,
1238
- endedAt: Date.now(),
1239
- startedAt
1240
- };
1241
- }
1242
- await emitter.emit("watch", {
1243
- type: "watch",
1244
- payload: {
1245
- currentStep: {
1246
- id: step.id,
1247
- ...execResults
1248
- },
1249
- workflowState: {
1250
- status: "running",
1251
- steps: { ...stepResults, [step.id]: execResults },
1252
- result: null,
1253
- error: null
1254
- }
1255
- },
1256
- eventTimestamp: Date.now()
1257
- });
1258
- if (execResults.status === "suspended") {
1259
- await emitter.emit("watch-v2", {
1260
- type: "workflow-step-suspended",
1261
- payload: {
1262
- id: step.id,
1263
- ...execResults
1264
- }
1265
- });
1266
- } else {
1267
- await emitter.emit("watch-v2", {
1268
- type: "workflow-step-result",
1269
- payload: {
1270
- id: step.id,
1271
- ...execResults
1272
- }
1273
- });
1274
- await emitter.emit("watch-v2", {
1275
- type: "workflow-step-finish",
1276
- payload: {
1277
- id: step.id,
1278
- metadata: {}
1279
- }
1280
- });
1281
- }
1282
- stepAISpan?.end({ output: execResults });
1283
- return { result: execResults, executionContext, stepResults };
1284
- });
1285
- } catch (e) {
1286
- const stepFailure = e instanceof Error ? e?.cause : {
1287
- status: "failed",
1288
- error: e instanceof Error ? e.message : String(e),
1289
- payload: inputData,
1290
- startedAt,
1291
- endedAt: Date.now()
1292
- };
1293
- stepRes = {
1294
- result: stepFailure,
1295
- executionContext,
1296
- stepResults: {
1297
- ...stepResults,
1298
- [step.id]: stepFailure
1299
- }
1300
- };
1301
- }
1302
- if (disableScorers !== false && stepRes.result.status === "success") {
1303
- await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}.score`, async () => {
1304
- if (step.scorers) {
1305
- await this.runScorers({
1306
- scorers: step.scorers,
1307
- runId: executionContext.runId,
1308
- input: inputData,
1309
- output: stepRes.result,
1310
- workflowId: executionContext.workflowId,
1311
- stepId: step.id,
1312
- runtimeContext,
1313
- disableScorers,
1314
- tracingContext: { currentSpan: stepAISpan }
1315
- });
1316
- }
1317
- });
1318
- }
1319
- Object.assign(executionContext.suspendedPaths, stepRes.executionContext.suspendedPaths);
1320
- Object.assign(stepResults, stepRes.stepResults);
1321
- executionContext.state = stepRes.executionContext.state;
1322
- return stepRes.result;
1323
- }
1324
- async persistStepUpdate({
1325
- workflowId,
1326
- runId,
1327
- stepResults,
1328
- resourceId,
1329
- executionContext,
1330
- serializedStepGraph,
1331
- workflowStatus,
1332
- result,
1333
- error
1334
- }) {
1335
- await this.inngestStep.run(
1336
- `workflow.${workflowId}.run.${runId}.path.${JSON.stringify(executionContext.executionPath)}.stepUpdate`,
1337
- async () => {
1338
- const shouldPersistSnapshot = this.options.shouldPersistSnapshot({ stepResults, workflowStatus });
1339
- if (!shouldPersistSnapshot) {
1340
- return;
1341
- }
1342
- await this.mastra?.getStorage()?.persistWorkflowSnapshot({
1343
- workflowName: workflowId,
1344
- runId,
1345
- resourceId,
1346
- snapshot: {
1347
- runId,
1348
- value: executionContext.state,
1349
- context: stepResults,
1350
- activePaths: [],
1351
- suspendedPaths: executionContext.suspendedPaths,
1352
- waitingPaths: {},
1353
- serializedStepGraph,
1354
- status: workflowStatus,
1355
- result,
1356
- error,
1357
- // @ts-ignore
1358
- timestamp: Date.now()
1359
- }
1360
- });
1361
- }
1362
- );
1363
- }
1364
- async executeConditional({
1365
- workflowId,
1366
- runId,
1367
- entry,
1368
- prevOutput,
1369
- prevStep,
1370
- stepResults,
1371
- serializedStepGraph,
1372
- resume,
1373
- executionContext,
1374
- emitter,
1375
- abortController,
1376
- runtimeContext,
1377
- writableStream,
1378
- disableScorers,
1379
- tracingContext
1380
- }) {
1381
- const conditionalSpan = tracingContext?.currentSpan?.createChildSpan({
1382
- type: AISpanType.WORKFLOW_CONDITIONAL,
1383
- name: `conditional: '${entry.conditions.length} conditions'`,
1384
- input: prevOutput,
1385
- attributes: {
1386
- conditionCount: entry.conditions.length
1387
- },
1388
- tracingPolicy: this.options?.tracingPolicy
1389
- });
1390
- let execResults;
1391
- const truthyIndexes = (await Promise.all(
1392
- entry.conditions.map(
1393
- (cond, index) => this.inngestStep.run(`workflow.${workflowId}.conditional.${index}`, async () => {
1394
- const evalSpan = conditionalSpan?.createChildSpan({
1395
- type: AISpanType.WORKFLOW_CONDITIONAL_EVAL,
1396
- name: `condition: '${index}'`,
1397
- input: prevOutput,
1398
- attributes: {
1399
- conditionIndex: index
1400
- },
1401
- tracingPolicy: this.options?.tracingPolicy
1402
- });
1403
- try {
1404
- const result = await cond({
1405
- runId,
1406
- workflowId,
1407
- mastra: this.mastra,
1408
- runtimeContext,
1409
- runCount: -1,
1410
- inputData: prevOutput,
1411
- state: executionContext.state,
1412
- setState: (state) => {
1413
- executionContext.state = state;
1414
- },
1415
- tracingContext: {
1416
- currentSpan: evalSpan
1417
- },
1418
- getInitData: () => stepResults?.input,
1419
- getStepResult: getStepResult.bind(this, stepResults),
1420
- // TODO: this function shouldn't have suspend probably?
1421
- suspend: async (_suspendPayload) => {
1422
- },
1423
- bail: () => {
1424
- },
1425
- abort: () => {
1426
- abortController.abort();
1427
- },
1428
- [EMITTER_SYMBOL]: emitter,
1429
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
1430
- // TODO: add streamVNext support
1431
- engine: {
1432
- step: this.inngestStep
1433
- },
1434
- abortSignal: abortController.signal,
1435
- writer: new ToolStream(
1436
- {
1437
- prefix: "workflow-step",
1438
- callId: randomUUID(),
1439
- name: "conditional",
1440
- runId
1441
- },
1442
- writableStream
1443
- )
1444
- });
1445
- evalSpan?.end({
1446
- output: result,
1447
- attributes: {
1448
- result: !!result
1449
- }
1450
- });
1451
- return result ? index : null;
1452
- } catch (e) {
1453
- evalSpan?.error({
1454
- error: e instanceof Error ? e : new Error(String(e)),
1455
- attributes: {
1456
- result: false
1457
- }
1458
- });
1459
- return null;
1460
- }
1461
- })
1462
- )
1463
- )).filter((index) => index !== null);
1464
- const stepsToRun = entry.steps.filter((_, index) => truthyIndexes.includes(index));
1465
- conditionalSpan?.update({
1466
- attributes: {
1467
- truthyIndexes,
1468
- selectedSteps: stepsToRun.map((s) => s.type === "step" ? s.step.id : `control-${s.type}`)
1469
- }
1470
- });
1471
- const results = await Promise.all(
1472
- stepsToRun.map(
1473
- (step, index) => this.executeEntry({
1474
- workflowId,
1475
- runId,
1476
- entry: step,
1477
- serializedStepGraph,
1478
- prevStep,
1479
- stepResults,
1480
- resume,
1481
- executionContext: {
1482
- workflowId,
1483
- runId,
1484
- executionPath: [...executionContext.executionPath, index],
1485
- suspendedPaths: executionContext.suspendedPaths,
1486
- retryConfig: executionContext.retryConfig,
1487
- executionSpan: executionContext.executionSpan,
1488
- state: executionContext.state
1489
- },
1490
- emitter,
1491
- abortController,
1492
- runtimeContext,
1493
- writableStream,
1494
- disableScorers,
1495
- tracingContext: {
1496
- currentSpan: conditionalSpan
1497
- }
1498
- })
1499
- )
1500
- );
1501
- const hasFailed = results.find((result) => result.result.status === "failed");
1502
- const hasSuspended = results.find((result) => result.result.status === "suspended");
1503
- if (hasFailed) {
1504
- execResults = { status: "failed", error: hasFailed.result.error };
1505
- } else if (hasSuspended) {
1506
- execResults = { status: "suspended", suspendPayload: hasSuspended.result.suspendPayload };
1507
- } else {
1508
- execResults = {
1509
- status: "success",
1510
- output: results.reduce((acc, result, index) => {
1511
- if (result.result.status === "success") {
1512
- acc[stepsToRun[index].step.id] = result.output;
1513
- }
1514
- return acc;
1515
- }, {})
1516
- };
1517
- }
1518
- if (execResults.status === "failed") {
1519
- conditionalSpan?.error({
1520
- error: new Error(execResults.error)
1521
- });
1522
- } else {
1523
- conditionalSpan?.end({
1524
- output: execResults.output || execResults
1525
- });
1526
- }
1527
- return execResults;
1528
- }
1529
- };
1530
1495
 
1531
- export { InngestExecutionEngine, InngestRun, InngestWorkflow, createStep, init, serve };
1496
+ export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, _compatibilityCheck, createStep, init, serve };
1532
1497
  //# sourceMappingURL=index.js.map
1533
1498
  //# sourceMappingURL=index.js.map