@mastra/inngest 0.0.0-ai-sdk-network-text-delta-20251017172601 → 0.0.0-allow-to-pass-a-mastra-url-instance-20251105224938

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,9 +1,11 @@
1
1
  import { randomUUID } from 'crypto';
2
+ import { ReadableStream } from 'stream/web';
2
3
  import { subscribe } from '@inngest/realtime';
3
- import { wrapMastra, AISpanType } from '@mastra/core/ai-tracing';
4
- import { RuntimeContext } from '@mastra/core/di';
4
+ import { RequestContext } from '@mastra/core/di';
5
+ import { wrapMastra, SpanType } from '@mastra/core/observability';
6
+ import { ChunkFrom, WorkflowRunOutput } from '@mastra/core/stream';
5
7
  import { ToolStream, Tool } from '@mastra/core/tools';
6
- import { Run, Workflow, DefaultExecutionEngine, getStepResult, validateStepInput } from '@mastra/core/workflows';
8
+ import { Run, Workflow, DefaultExecutionEngine, createDeprecationProxy, getStepResult, runCountDeprecationMessage, validateStepInput } from '@mastra/core/workflows';
7
9
  import { EMITTER_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
8
10
  import { NonRetriableError, RetryAfterError } from 'inngest';
9
11
  import { serve as serve$1 } from 'inngest/hono';
@@ -16,7 +18,7 @@ function serve({
16
18
  functions: userFunctions = [],
17
19
  registerOptions
18
20
  }) {
19
- const wfs = mastra.getWorkflows();
21
+ const wfs = mastra.listWorkflows();
20
22
  const workflowFunctions = Array.from(
21
23
  new Set(
22
24
  Object.values(wfs).flatMap((wf) => {
@@ -55,11 +57,12 @@ var InngestRun = class extends Run {
55
57
  }
56
58
  async getRunOutput(eventId) {
57
59
  let runs = await this.getRuns(eventId);
60
+ const storage = this.#mastra?.getStorage();
58
61
  while (runs?.[0]?.status !== "Completed" || runs?.[0]?.event_id !== eventId) {
59
62
  await new Promise((resolve) => setTimeout(resolve, 1e3));
60
63
  runs = await this.getRuns(eventId);
61
64
  if (runs?.[0]?.status === "Failed") {
62
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
65
+ const snapshot = await storage?.loadWorkflowSnapshot({
63
66
  workflowName: this.workflowId,
64
67
  runId: this.runId
65
68
  });
@@ -68,7 +71,7 @@ var InngestRun = class extends Run {
68
71
  };
69
72
  }
70
73
  if (runs?.[0]?.status === "Cancelled") {
71
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
74
+ const snapshot = await storage?.loadWorkflowSnapshot({
72
75
  workflowName: this.workflowId,
73
76
  runId: this.runId
74
77
  });
@@ -77,25 +80,20 @@ var InngestRun = class extends Run {
77
80
  }
78
81
  return runs?.[0];
79
82
  }
80
- async sendEvent(event, data) {
81
- await this.inngest.send({
82
- name: `user-event-${event}`,
83
- data
84
- });
85
- }
86
83
  async cancel() {
84
+ const storage = this.#mastra?.getStorage();
87
85
  await this.inngest.send({
88
86
  name: `cancel.workflow.${this.workflowId}`,
89
87
  data: {
90
88
  runId: this.runId
91
89
  }
92
90
  });
93
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
91
+ const snapshot = await storage?.loadWorkflowSnapshot({
94
92
  workflowName: this.workflowId,
95
93
  runId: this.runId
96
94
  });
97
95
  if (snapshot) {
98
- await this.#mastra?.storage?.persistWorkflowSnapshot({
96
+ await storage?.persistWorkflowSnapshot({
99
97
  workflowName: this.workflowId,
100
98
  runId: this.runId,
101
99
  resourceId: this.resourceId,
@@ -106,9 +104,15 @@ var InngestRun = class extends Run {
106
104
  });
107
105
  }
108
106
  }
109
- async start({
107
+ async start(params) {
108
+ return this._start(params);
109
+ }
110
+ async _start({
110
111
  inputData,
111
- initialState
112
+ initialState,
113
+ outputOptions,
114
+ tracingOptions,
115
+ format
112
116
  }) {
113
117
  await this.#mastra.getStorage()?.persistWorkflowSnapshot({
114
118
  workflowName: this.workflowId,
@@ -135,7 +139,10 @@ var InngestRun = class extends Run {
135
139
  inputData: inputDataToUse,
136
140
  initialState: initialStateToUse,
137
141
  runId: this.runId,
138
- resourceId: this.resourceId
142
+ resourceId: this.resourceId,
143
+ outputOptions,
144
+ tracingOptions,
145
+ format
139
146
  }
140
147
  });
141
148
  const eventId = eventOutput.ids[0];
@@ -164,10 +171,11 @@ var InngestRun = class extends Run {
164
171
  return p;
165
172
  }
166
173
  async _resume(params) {
174
+ const storage = this.#mastra?.getStorage();
167
175
  const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
168
176
  (step) => typeof step === "string" ? step : step?.id
169
177
  );
170
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
178
+ const snapshot = await storage?.loadWorkflowSnapshot({
171
179
  workflowName: this.workflowId,
172
180
  runId: this.runId
173
181
  });
@@ -201,12 +209,12 @@ var InngestRun = class extends Run {
201
209
  }
202
210
  return result;
203
211
  }
204
- watch(cb, type = "watch") {
212
+ watch(cb) {
205
213
  let active = true;
206
214
  const streamPromise = subscribe(
207
215
  {
208
216
  channel: `workflow:${this.workflowId}:${this.runId}`,
209
- topics: [type],
217
+ topics: ["watch"],
210
218
  app: this.inngest
211
219
  },
212
220
  (message) => {
@@ -224,20 +232,35 @@ var InngestRun = class extends Run {
224
232
  });
225
233
  };
226
234
  }
227
- stream({ inputData, runtimeContext } = {}) {
235
+ streamLegacy({ inputData, requestContext } = {}) {
228
236
  const { readable, writable } = new TransformStream();
229
237
  const writer = writable.getWriter();
230
238
  const unwatch = this.watch(async (event) => {
231
239
  try {
240
+ await writer.write({
241
+ // @ts-ignore
242
+ type: "start",
243
+ // @ts-ignore
244
+ payload: { runId: this.runId }
245
+ });
232
246
  const e = {
233
247
  ...event,
234
248
  type: event.type.replace("workflow-", "")
235
249
  };
250
+ if (e.type === "step-output") {
251
+ e.type = e.payload.output.type;
252
+ e.payload = e.payload.output.payload;
253
+ }
236
254
  await writer.write(e);
237
255
  } catch {
238
256
  }
239
- }, "watch-v2");
257
+ });
240
258
  this.closeStreamAction = async () => {
259
+ await writer.write({
260
+ type: "finish",
261
+ // @ts-ignore
262
+ payload: { runId: this.runId }
263
+ });
241
264
  unwatch();
242
265
  try {
243
266
  await writer.close();
@@ -247,7 +270,7 @@ var InngestRun = class extends Run {
247
270
  writer.releaseLock();
248
271
  }
249
272
  };
250
- this.executionResults = this.start({ inputData, runtimeContext }).then((result) => {
273
+ this.executionResults = this._start({ inputData, requestContext, format: "legacy" }).then((result) => {
251
274
  if (result.status !== "suspended") {
252
275
  this.closeStreamAction?.().catch(() => {
253
276
  });
@@ -259,6 +282,82 @@ var InngestRun = class extends Run {
259
282
  getWorkflowState: () => this.executionResults
260
283
  };
261
284
  }
285
+ stream({
286
+ inputData,
287
+ requestContext,
288
+ tracingOptions,
289
+ closeOnSuspend = true,
290
+ initialState,
291
+ outputOptions
292
+ } = {}) {
293
+ if (this.closeStreamAction && this.streamOutput) {
294
+ return this.streamOutput;
295
+ }
296
+ this.closeStreamAction = async () => {
297
+ };
298
+ const self = this;
299
+ const stream = new ReadableStream({
300
+ async start(controller) {
301
+ const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {
302
+ controller.enqueue({
303
+ type,
304
+ runId: self.runId,
305
+ from,
306
+ payload: {
307
+ stepName: payload?.id,
308
+ ...payload
309
+ }
310
+ });
311
+ });
312
+ self.closeStreamAction = async () => {
313
+ unwatch();
314
+ try {
315
+ await controller.close();
316
+ } catch (err) {
317
+ console.error("Error closing stream:", err);
318
+ }
319
+ };
320
+ const executionResultsPromise = self._start({
321
+ inputData,
322
+ requestContext,
323
+ // tracingContext, // We are not able to pass a reference to a span here, what to do?
324
+ initialState,
325
+ tracingOptions,
326
+ outputOptions,
327
+ format: "vnext"
328
+ });
329
+ let executionResults;
330
+ try {
331
+ executionResults = await executionResultsPromise;
332
+ if (closeOnSuspend) {
333
+ self.closeStreamAction?.().catch(() => {
334
+ });
335
+ } else if (executionResults.status !== "suspended") {
336
+ self.closeStreamAction?.().catch(() => {
337
+ });
338
+ }
339
+ if (self.streamOutput) {
340
+ self.streamOutput.updateResults(
341
+ executionResults
342
+ );
343
+ }
344
+ } catch (err) {
345
+ self.streamOutput?.rejectResults(err);
346
+ self.closeStreamAction?.().catch(() => {
347
+ });
348
+ }
349
+ }
350
+ });
351
+ this.streamOutput = new WorkflowRunOutput({
352
+ runId: this.runId,
353
+ workflowId: this.workflowId,
354
+ stream
355
+ });
356
+ return this.streamOutput;
357
+ }
358
+ streamVNext(args = {}) {
359
+ return this.stream(args);
360
+ }
262
361
  };
263
362
  var InngestWorkflow = class _InngestWorkflow extends Workflow {
264
363
  #mastra;
@@ -275,13 +374,13 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
275
374
  this.#mastra = params.mastra;
276
375
  this.inngest = inngest;
277
376
  }
278
- async getWorkflowRuns(args) {
377
+ async listWorkflowRuns(args) {
279
378
  const storage = this.#mastra?.getStorage();
280
379
  if (!storage) {
281
380
  this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
282
381
  return { runs: [], total: 0 };
283
382
  }
284
- return storage.getWorkflowRuns({ workflowName: this.id, ...args ?? {} });
383
+ return storage.listWorkflowRuns({ workflowName: this.id, ...args ?? {} });
285
384
  }
286
385
  async getWorkflowRunById(runId) {
287
386
  const storage = this.#mastra?.getStorage();
@@ -310,16 +409,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
310
409
  }
311
410
  }
312
411
  }
313
- /**
314
- * @deprecated Use createRunAsync() instead.
315
- * @throws {Error} Always throws an error directing users to use createRunAsync()
316
- */
317
- createRun(_options) {
318
- throw new Error(
319
- "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."
320
- );
321
- }
322
- async createRunAsync(options) {
412
+ async createRun(options) {
323
413
  const runIdToUse = options?.runId || randomUUID();
324
414
  const run = this.runs.get(runIdToUse) ?? new InngestRun(
325
415
  {
@@ -381,7 +471,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
381
471
  },
382
472
  { event: `workflow.${this.id}` },
383
473
  async ({ event, step, attempt, publish }) => {
384
- let { inputData, initialState, runId, resourceId, resume, outputOptions } = event.data;
474
+ let { inputData, initialState, runId, resourceId, resume, outputOptions, format } = event.data;
385
475
  if (!runId) {
386
476
  runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
387
477
  return randomUUID();
@@ -420,13 +510,19 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
420
510
  initialState,
421
511
  emitter,
422
512
  retryConfig: this.retryConfig,
423
- runtimeContext: new RuntimeContext(),
513
+ requestContext: new RequestContext(),
424
514
  // TODO
425
515
  resume,
516
+ format,
426
517
  abortController: new AbortController(),
427
- currentSpan: void 0,
428
- // TODO: Pass actual parent AI span from workflow execution context
429
- outputOptions
518
+ // currentSpan: undefined, // TODO: Pass actual parent Span from workflow execution context
519
+ outputOptions,
520
+ writableStream: new WritableStream({
521
+ write(chunk) {
522
+ void emitter.emit("watch", chunk).catch(() => {
523
+ });
524
+ }
525
+ })
430
526
  });
431
527
  await step.run(`workflow.${this.id}.finalize`, async () => {
432
528
  if (result.status === "failed") {
@@ -464,7 +560,7 @@ function isAgent(params) {
464
560
  function isTool(params) {
465
561
  return params instanceof Tool;
466
562
  }
467
- function createStep(params) {
563
+ function createStep(params, agentOptions) {
468
564
  if (isAgent(params)) {
469
565
  return {
470
566
  id: params.name,
@@ -472,12 +568,23 @@ function createStep(params) {
472
568
  // @ts-ignore
473
569
  inputSchema: z.object({
474
570
  prompt: z.string()
571
+ // resourceId: z.string().optional(),
572
+ // threadId: z.string().optional(),
475
573
  }),
476
574
  // @ts-ignore
477
575
  outputSchema: z.object({
478
576
  text: z.string()
479
577
  }),
480
- execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort, tracingContext }) => {
578
+ execute: async ({
579
+ inputData,
580
+ [EMITTER_SYMBOL]: emitter,
581
+ [STREAM_FORMAT_SYMBOL]: streamFormat,
582
+ requestContext,
583
+ tracingContext,
584
+ abortSignal,
585
+ abort,
586
+ writer
587
+ }) => {
481
588
  let streamPromise = {};
482
589
  streamPromise.promise = new Promise((resolve, reject) => {
483
590
  streamPromise.resolve = resolve;
@@ -487,61 +594,60 @@ function createStep(params) {
487
594
  name: params.name,
488
595
  args: inputData
489
596
  };
490
- if ((await params.getLLM()).getModel().specificationVersion === `v2`) {
491
- const { fullStream } = await params.stream(inputData.prompt, {
492
- runtimeContext,
597
+ let stream;
598
+ if ((await params.getModel()).specificationVersion === "v1") {
599
+ const { fullStream } = await params.streamLegacy(inputData.prompt, {
600
+ ...agentOptions ?? {},
601
+ // resourceId: inputData.resourceId,
602
+ // threadId: inputData.threadId,
603
+ requestContext,
493
604
  tracingContext,
494
605
  onFinish: (result) => {
495
606
  streamPromise.resolve(result.text);
607
+ void agentOptions?.onFinish?.(result);
496
608
  },
497
609
  abortSignal
498
610
  });
499
- if (abortSignal.aborted) {
500
- return abort();
501
- }
502
- await emitter.emit("watch-v2", {
503
- type: "tool-call-streaming-start",
504
- ...toolData ?? {}
505
- });
506
- for await (const chunk of fullStream) {
507
- if (chunk.type === "text-delta") {
508
- await emitter.emit("watch-v2", {
509
- type: "tool-call-delta",
510
- ...toolData ?? {},
511
- argsTextDelta: chunk.payload.text
512
- });
513
- }
514
- }
611
+ stream = fullStream;
515
612
  } else {
516
- const { fullStream } = await params.streamLegacy(inputData.prompt, {
517
- runtimeContext,
613
+ const modelOutput = await params.stream(inputData.prompt, {
614
+ ...agentOptions ?? {},
615
+ requestContext,
518
616
  tracingContext,
519
617
  onFinish: (result) => {
520
618
  streamPromise.resolve(result.text);
619
+ void agentOptions?.onFinish?.(result);
521
620
  },
522
621
  abortSignal
523
622
  });
524
- if (abortSignal.aborted) {
525
- return abort();
526
- }
527
- await emitter.emit("watch-v2", {
623
+ stream = modelOutput.fullStream;
624
+ }
625
+ if (streamFormat === "legacy") {
626
+ await emitter.emit("watch", {
528
627
  type: "tool-call-streaming-start",
529
628
  ...toolData ?? {}
530
629
  });
531
- for await (const chunk of fullStream) {
630
+ for await (const chunk of stream) {
532
631
  if (chunk.type === "text-delta") {
533
- await emitter.emit("watch-v2", {
632
+ await emitter.emit("watch", {
534
633
  type: "tool-call-delta",
535
634
  ...toolData ?? {},
536
635
  argsTextDelta: chunk.textDelta
537
636
  });
538
637
  }
539
638
  }
639
+ await emitter.emit("watch", {
640
+ type: "tool-call-streaming-finish",
641
+ ...toolData ?? {}
642
+ });
643
+ } else {
644
+ for await (const chunk of stream) {
645
+ await writer.write(chunk);
646
+ }
647
+ }
648
+ if (abortSignal.aborted) {
649
+ return abort();
540
650
  }
541
- await emitter.emit("watch-v2", {
542
- type: "tool-call-streaming-finish",
543
- ...toolData ?? {}
544
- });
545
651
  return {
546
652
  text: await streamPromise.promise
547
653
  };
@@ -560,11 +666,11 @@ function createStep(params) {
560
666
  description: params.description,
561
667
  inputSchema: params.inputSchema,
562
668
  outputSchema: params.outputSchema,
563
- execute: async ({ inputData, mastra, runtimeContext, tracingContext, suspend, resumeData }) => {
669
+ execute: async ({ inputData, mastra, requestContext, tracingContext, suspend, resumeData }) => {
564
670
  return params.execute({
565
671
  context: inputData,
566
672
  mastra: wrapMastra(mastra, tracingContext),
567
- runtimeContext,
673
+ requestContext,
568
674
  tracingContext,
569
675
  suspend,
570
676
  resumeData
@@ -627,63 +733,16 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
627
733
  this.inngestStep = inngestStep;
628
734
  this.inngestAttempts = inngestAttempts;
629
735
  }
630
- async execute(params) {
631
- await params.emitter.emit("watch-v2", {
632
- type: "workflow-start",
633
- payload: { runId: params.runId }
634
- });
635
- const result = await super.execute(params);
636
- await params.emitter.emit("watch-v2", {
637
- type: "workflow-finish",
638
- payload: { runId: params.runId }
639
- });
640
- return result;
641
- }
642
- async fmtReturnValue(executionSpan, emitter, stepResults, lastOutput, error) {
736
+ async fmtReturnValue(emitter, stepResults, lastOutput, error) {
643
737
  const base = {
644
738
  status: lastOutput.status,
645
739
  steps: stepResults
646
740
  };
647
741
  if (lastOutput.status === "success") {
648
- await emitter.emit("watch", {
649
- type: "watch",
650
- payload: {
651
- workflowState: {
652
- status: lastOutput.status,
653
- steps: stepResults,
654
- result: lastOutput.output
655
- }
656
- },
657
- eventTimestamp: Date.now()
658
- });
659
742
  base.result = lastOutput.output;
660
743
  } else if (lastOutput.status === "failed") {
661
744
  base.error = error instanceof Error ? error?.stack ?? error.message : lastOutput?.error instanceof Error ? lastOutput.error.message : lastOutput.error ?? error ?? "Unknown error";
662
- await emitter.emit("watch", {
663
- type: "watch",
664
- payload: {
665
- workflowState: {
666
- status: lastOutput.status,
667
- steps: stepResults,
668
- result: null,
669
- error: base.error
670
- }
671
- },
672
- eventTimestamp: Date.now()
673
- });
674
745
  } else if (lastOutput.status === "suspended") {
675
- await emitter.emit("watch", {
676
- type: "watch",
677
- payload: {
678
- workflowState: {
679
- status: lastOutput.status,
680
- steps: stepResults,
681
- result: null,
682
- error: null
683
- }
684
- },
685
- eventTimestamp: Date.now()
686
- });
687
746
  const suspendedStepIds = Object.entries(stepResults).flatMap(([stepId, stepResult]) => {
688
747
  if (stepResult?.status === "suspended") {
689
748
  const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
@@ -693,7 +752,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
693
752
  });
694
753
  base.suspended = suspendedStepIds;
695
754
  }
696
- executionSpan?.end();
697
755
  return base;
698
756
  }
699
757
  // async executeSleep({ id, duration }: { id: string; duration: number }): Promise<void> {
@@ -707,14 +765,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
707
765
  stepResults,
708
766
  emitter,
709
767
  abortController,
710
- runtimeContext,
768
+ requestContext,
711
769
  executionContext,
712
770
  writableStream,
713
771
  tracingContext
714
772
  }) {
715
773
  let { duration, fn } = entry;
716
774
  const sleepSpan = tracingContext?.currentSpan?.createChildSpan({
717
- type: AISpanType.WORKFLOW_SLEEP,
775
+ type: SpanType.WORKFLOW_SLEEP,
718
776
  name: `sleep: ${duration ? `${duration}ms` : "dynamic"}`,
719
777
  attributes: {
720
778
  durationMs: duration,
@@ -725,45 +783,53 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
725
783
  if (fn) {
726
784
  const stepCallId = randomUUID();
727
785
  duration = await this.inngestStep.run(`workflow.${workflowId}.sleep.${entry.id}`, async () => {
728
- return await fn({
729
- runId,
730
- workflowId,
731
- mastra: this.mastra,
732
- runtimeContext,
733
- inputData: prevOutput,
734
- state: executionContext.state,
735
- setState: (state) => {
736
- executionContext.state = state;
737
- },
738
- runCount: -1,
739
- tracingContext: {
740
- currentSpan: sleepSpan
741
- },
742
- getInitData: () => stepResults?.input,
743
- getStepResult: getStepResult.bind(this, stepResults),
744
- // TODO: this function shouldn't have suspend probably?
745
- suspend: async (_suspendPayload) => {
746
- },
747
- bail: () => {
748
- },
749
- abort: () => {
750
- abortController?.abort();
751
- },
752
- [EMITTER_SYMBOL]: emitter,
753
- // TODO: add streamVNext support
754
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
755
- engine: { step: this.inngestStep },
756
- abortSignal: abortController?.signal,
757
- writer: new ToolStream(
786
+ return await fn(
787
+ createDeprecationProxy(
758
788
  {
759
- prefix: "workflow-step",
760
- callId: stepCallId,
761
- name: "sleep",
762
- runId
789
+ runId,
790
+ workflowId,
791
+ mastra: this.mastra,
792
+ requestContext,
793
+ inputData: prevOutput,
794
+ state: executionContext.state,
795
+ setState: (state) => {
796
+ executionContext.state = state;
797
+ },
798
+ retryCount: -1,
799
+ tracingContext: {
800
+ currentSpan: sleepSpan
801
+ },
802
+ getInitData: () => stepResults?.input,
803
+ getStepResult: getStepResult.bind(this, stepResults),
804
+ // TODO: this function shouldn't have suspend probably?
805
+ suspend: async (_suspendPayload) => {
806
+ },
807
+ bail: () => {
808
+ },
809
+ abort: () => {
810
+ abortController?.abort();
811
+ },
812
+ [EMITTER_SYMBOL]: emitter,
813
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
814
+ engine: { step: this.inngestStep },
815
+ abortSignal: abortController?.signal,
816
+ writer: new ToolStream(
817
+ {
818
+ prefix: "workflow-step",
819
+ callId: stepCallId,
820
+ name: "sleep",
821
+ runId
822
+ },
823
+ writableStream
824
+ )
763
825
  },
764
- writableStream
826
+ {
827
+ paramName: "runCount",
828
+ deprecationMessage: runCountDeprecationMessage,
829
+ logger: this.logger
830
+ }
765
831
  )
766
- });
832
+ );
767
833
  });
768
834
  sleepSpan?.update({
769
835
  attributes: {
@@ -787,14 +853,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
787
853
  stepResults,
788
854
  emitter,
789
855
  abortController,
790
- runtimeContext,
856
+ requestContext,
791
857
  executionContext,
792
858
  writableStream,
793
859
  tracingContext
794
860
  }) {
795
861
  let { date, fn } = entry;
796
862
  const sleepUntilSpan = tracingContext?.currentSpan?.createChildSpan({
797
- type: AISpanType.WORKFLOW_SLEEP,
863
+ type: SpanType.WORKFLOW_SLEEP,
798
864
  name: `sleepUntil: ${date ? date.toISOString() : "dynamic"}`,
799
865
  attributes: {
800
866
  untilDate: date,
@@ -806,45 +872,53 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
806
872
  if (fn) {
807
873
  date = await this.inngestStep.run(`workflow.${workflowId}.sleepUntil.${entry.id}`, async () => {
808
874
  const stepCallId = randomUUID();
809
- return await fn({
810
- runId,
811
- workflowId,
812
- mastra: this.mastra,
813
- runtimeContext,
814
- inputData: prevOutput,
815
- state: executionContext.state,
816
- setState: (state) => {
817
- executionContext.state = state;
818
- },
819
- runCount: -1,
820
- tracingContext: {
821
- currentSpan: sleepUntilSpan
822
- },
823
- getInitData: () => stepResults?.input,
824
- getStepResult: getStepResult.bind(this, stepResults),
825
- // TODO: this function shouldn't have suspend probably?
826
- suspend: async (_suspendPayload) => {
827
- },
828
- bail: () => {
829
- },
830
- abort: () => {
831
- abortController?.abort();
832
- },
833
- [EMITTER_SYMBOL]: emitter,
834
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
835
- // TODO: add streamVNext support
836
- engine: { step: this.inngestStep },
837
- abortSignal: abortController?.signal,
838
- writer: new ToolStream(
875
+ return await fn(
876
+ createDeprecationProxy(
839
877
  {
840
- prefix: "workflow-step",
841
- callId: stepCallId,
842
- name: "sleep",
843
- runId
878
+ runId,
879
+ workflowId,
880
+ mastra: this.mastra,
881
+ requestContext,
882
+ inputData: prevOutput,
883
+ state: executionContext.state,
884
+ setState: (state) => {
885
+ executionContext.state = state;
886
+ },
887
+ retryCount: -1,
888
+ tracingContext: {
889
+ currentSpan: sleepUntilSpan
890
+ },
891
+ getInitData: () => stepResults?.input,
892
+ getStepResult: getStepResult.bind(this, stepResults),
893
+ // TODO: this function shouldn't have suspend probably?
894
+ suspend: async (_suspendPayload) => {
895
+ },
896
+ bail: () => {
897
+ },
898
+ abort: () => {
899
+ abortController?.abort();
900
+ },
901
+ [EMITTER_SYMBOL]: emitter,
902
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
903
+ engine: { step: this.inngestStep },
904
+ abortSignal: abortController?.signal,
905
+ writer: new ToolStream(
906
+ {
907
+ prefix: "workflow-step",
908
+ callId: stepCallId,
909
+ name: "sleep",
910
+ runId
911
+ },
912
+ writableStream
913
+ )
844
914
  },
845
- writableStream
915
+ {
916
+ paramName: "runCount",
917
+ deprecationMessage: runCountDeprecationMessage,
918
+ logger: this.logger
919
+ }
846
920
  )
847
- });
921
+ );
848
922
  });
849
923
  if (date && !(date instanceof Date)) {
850
924
  date = new Date(date);
@@ -868,16 +942,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
868
942
  throw e;
869
943
  }
870
944
  }
871
- async executeWaitForEvent({ event, timeout }) {
872
- const eventData = await this.inngestStep.waitForEvent(`user-event-${event}`, {
873
- event: `user-event-${event}`,
874
- timeout: timeout ?? 5e3
875
- });
876
- if (eventData === null) {
877
- throw "Timeout waiting for event";
878
- }
879
- return eventData?.data;
880
- }
881
945
  async executeStep({
882
946
  step,
883
947
  stepResults,
@@ -886,14 +950,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
886
950
  prevOutput,
887
951
  emitter,
888
952
  abortController,
889
- runtimeContext,
953
+ requestContext,
890
954
  tracingContext,
891
955
  writableStream,
892
956
  disableScorers
893
957
  }) {
894
- const stepAISpan = tracingContext?.currentSpan?.createChildSpan({
958
+ const stepSpan = tracingContext?.currentSpan?.createChildSpan({
895
959
  name: `workflow step: '${step.id}'`,
896
- type: AISpanType.WORKFLOW_STEP,
960
+ type: SpanType.WORKFLOW_STEP,
897
961
  input: prevOutput,
898
962
  attributes: {
899
963
  stepId: step.id
@@ -910,27 +974,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
910
974
  async () => {
911
975
  const startedAt2 = Date.now();
912
976
  await emitter.emit("watch", {
913
- type: "watch",
914
- payload: {
915
- currentStep: {
916
- id: step.id,
917
- status: "running"
918
- },
919
- workflowState: {
920
- status: "running",
921
- steps: {
922
- ...stepResults,
923
- [step.id]: {
924
- status: "running"
925
- }
926
- },
927
- result: null,
928
- error: null
929
- }
930
- },
931
- eventTimestamp: Date.now()
932
- });
933
- await emitter.emit("watch-v2", {
934
977
  type: "workflow-step-start",
935
978
  payload: {
936
979
  id: step.id,
@@ -1006,23 +1049,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1006
1049
  async () => {
1007
1050
  if (result.status === "failed") {
1008
1051
  await emitter.emit("watch", {
1009
- type: "watch",
1010
- payload: {
1011
- currentStep: {
1012
- id: step.id,
1013
- status: "failed",
1014
- error: result?.error
1015
- },
1016
- workflowState: {
1017
- status: "running",
1018
- steps: stepResults,
1019
- result: null,
1020
- error: null
1021
- }
1022
- },
1023
- eventTimestamp: Date.now()
1024
- });
1025
- await emitter.emit("watch-v2", {
1026
1052
  type: "workflow-step-result",
1027
1053
  payload: {
1028
1054
  id: step.id,
@@ -1041,27 +1067,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1041
1067
  const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
1042
1068
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1043
1069
  await emitter.emit("watch", {
1044
- type: "watch",
1045
- payload: {
1046
- currentStep: {
1047
- id: step.id,
1048
- status: "suspended",
1049
- payload: stepResult.payload,
1050
- suspendPayload: {
1051
- ...stepResult?.suspendPayload,
1052
- __workflow_meta: { runId, path: suspendPath }
1053
- }
1054
- },
1055
- workflowState: {
1056
- status: "running",
1057
- steps: stepResults,
1058
- result: null,
1059
- error: null
1060
- }
1061
- },
1062
- eventTimestamp: Date.now()
1063
- });
1064
- await emitter.emit("watch-v2", {
1065
1070
  type: "workflow-step-suspended",
1066
1071
  payload: {
1067
1072
  id: step.id,
@@ -1080,23 +1085,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1080
1085
  }
1081
1086
  };
1082
1087
  }
1083
- await emitter.emit("watch", {
1084
- type: "watch",
1085
- payload: {
1086
- currentStep: {
1087
- id: step.id,
1088
- status: "suspended",
1089
- payload: {}
1090
- },
1091
- workflowState: {
1092
- status: "running",
1093
- steps: stepResults,
1094
- result: null,
1095
- error: null
1096
- }
1097
- },
1098
- eventTimestamp: Date.now()
1099
- });
1100
1088
  return {
1101
1089
  executionContext,
1102
1090
  result: {
@@ -1106,23 +1094,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1106
1094
  };
1107
1095
  }
1108
1096
  await emitter.emit("watch", {
1109
- type: "watch",
1110
- payload: {
1111
- currentStep: {
1112
- id: step.id,
1113
- status: "success",
1114
- output: result?.result
1115
- },
1116
- workflowState: {
1117
- status: "running",
1118
- steps: stepResults,
1119
- result: null,
1120
- error: null
1121
- }
1122
- },
1123
- eventTimestamp: Date.now()
1124
- });
1125
- await emitter.emit("watch-v2", {
1126
1097
  type: "workflow-step-result",
1127
1098
  payload: {
1128
1099
  id: step.id,
@@ -1130,7 +1101,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1130
1101
  output: result?.result
1131
1102
  }
1132
1103
  });
1133
- await emitter.emit("watch-v2", {
1104
+ await emitter.emit("watch", {
1134
1105
  type: "workflow-step-finish",
1135
1106
  payload: {
1136
1107
  id: step.id,
@@ -1150,6 +1121,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1150
1121
  resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1151
1122
  };
1152
1123
  }
1124
+ const stepCallId = randomUUID();
1153
1125
  let stepRes;
1154
1126
  try {
1155
1127
  stepRes = await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}`, async () => {
@@ -1163,8 +1135,16 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1163
1135
  const result = await step.execute({
1164
1136
  runId: executionContext.runId,
1165
1137
  mastra: this.mastra,
1166
- runtimeContext,
1167
- writableStream,
1138
+ requestContext,
1139
+ writer: new ToolStream(
1140
+ {
1141
+ prefix: "workflow-step",
1142
+ callId: stepCallId,
1143
+ name: step.id,
1144
+ runId: executionContext.runId
1145
+ },
1146
+ writableStream
1147
+ ),
1168
1148
  state: executionContext?.state ?? {},
1169
1149
  setState: (state) => {
1170
1150
  executionContext.state = state;
@@ -1172,14 +1152,20 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1172
1152
  inputData,
1173
1153
  resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
1174
1154
  tracingContext: {
1175
- currentSpan: stepAISpan
1155
+ currentSpan: stepSpan
1176
1156
  },
1177
1157
  getInitData: () => stepResults?.input,
1178
1158
  getStepResult: getStepResult.bind(this, stepResults),
1179
1159
  suspend: async (suspendPayload, suspendOptions) => {
1180
1160
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1181
1161
  if (suspendOptions?.resumeLabel) {
1182
- executionContext.resumeLabels[suspendOptions.resumeLabel] = step.id;
1162
+ const resumeLabel = Array.isArray(suspendOptions.resumeLabel) ? suspendOptions.resumeLabel : [suspendOptions.resumeLabel];
1163
+ for (const label of resumeLabel) {
1164
+ executionContext.resumeLabels[label] = {
1165
+ stepId: step.id,
1166
+ foreachIndex: executionContext.foreachIndex
1167
+ };
1168
+ }
1183
1169
  }
1184
1170
  suspended = { payload: suspendPayload };
1185
1171
  },
@@ -1193,6 +1179,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1193
1179
  runId: stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId
1194
1180
  },
1195
1181
  [EMITTER_SYMBOL]: emitter,
1182
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
1196
1183
  engine: {
1197
1184
  step: this.inngestStep
1198
1185
  },
@@ -1220,7 +1207,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1220
1207
  };
1221
1208
  execResults = stepFailure;
1222
1209
  const fallbackErrorMessage = `Step ${step.id} failed`;
1223
- stepAISpan?.error({ error: new Error(execResults.error ?? fallbackErrorMessage) });
1210
+ stepSpan?.error({ error: new Error(execResults.error ?? fallbackErrorMessage) });
1224
1211
  throw new RetryAfterError(execResults.error ?? fallbackErrorMessage, executionContext.retryConfig.delay, {
1225
1212
  cause: execResults
1226
1213
  });
@@ -1244,24 +1231,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1244
1231
  startedAt
1245
1232
  };
1246
1233
  }
1247
- await emitter.emit("watch", {
1248
- type: "watch",
1249
- payload: {
1250
- currentStep: {
1251
- id: step.id,
1252
- ...execResults
1253
- },
1254
- workflowState: {
1255
- status: "running",
1256
- steps: { ...stepResults, [step.id]: execResults },
1257
- result: null,
1258
- error: null
1259
- }
1260
- },
1261
- eventTimestamp: Date.now()
1262
- });
1263
1234
  if (execResults.status === "suspended") {
1264
- await emitter.emit("watch-v2", {
1235
+ await emitter.emit("watch", {
1265
1236
  type: "workflow-step-suspended",
1266
1237
  payload: {
1267
1238
  id: step.id,
@@ -1269,14 +1240,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1269
1240
  }
1270
1241
  });
1271
1242
  } else {
1272
- await emitter.emit("watch-v2", {
1243
+ await emitter.emit("watch", {
1273
1244
  type: "workflow-step-result",
1274
1245
  payload: {
1275
1246
  id: step.id,
1276
1247
  ...execResults
1277
1248
  }
1278
1249
  });
1279
- await emitter.emit("watch-v2", {
1250
+ await emitter.emit("watch", {
1280
1251
  type: "workflow-step-finish",
1281
1252
  payload: {
1282
1253
  id: step.id,
@@ -1284,7 +1255,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1284
1255
  }
1285
1256
  });
1286
1257
  }
1287
- stepAISpan?.end({ output: execResults });
1258
+ stepSpan?.end({ output: execResults });
1288
1259
  return { result: execResults, executionContext, stepResults };
1289
1260
  });
1290
1261
  } catch (e) {
@@ -1314,9 +1285,9 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1314
1285
  output: stepRes.result,
1315
1286
  workflowId: executionContext.workflowId,
1316
1287
  stepId: step.id,
1317
- runtimeContext,
1288
+ requestContext,
1318
1289
  disableScorers,
1319
- tracingContext: { currentSpan: stepAISpan }
1290
+ tracingContext: { currentSpan: stepSpan }
1320
1291
  });
1321
1292
  }
1322
1293
  });
@@ -1372,20 +1343,18 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1372
1343
  runId,
1373
1344
  entry,
1374
1345
  prevOutput,
1375
- prevStep,
1376
1346
  stepResults,
1377
- serializedStepGraph,
1378
1347
  resume,
1379
1348
  executionContext,
1380
1349
  emitter,
1381
1350
  abortController,
1382
- runtimeContext,
1351
+ requestContext,
1383
1352
  writableStream,
1384
1353
  disableScorers,
1385
1354
  tracingContext
1386
1355
  }) {
1387
1356
  const conditionalSpan = tracingContext?.currentSpan?.createChildSpan({
1388
- type: AISpanType.WORKFLOW_CONDITIONAL,
1357
+ type: SpanType.WORKFLOW_CONDITIONAL,
1389
1358
  name: `conditional: '${entry.conditions.length} conditions'`,
1390
1359
  input: prevOutput,
1391
1360
  attributes: {
@@ -1398,7 +1367,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1398
1367
  entry.conditions.map(
1399
1368
  (cond, index) => this.inngestStep.run(`workflow.${workflowId}.conditional.${index}`, async () => {
1400
1369
  const evalSpan = conditionalSpan?.createChildSpan({
1401
- type: AISpanType.WORKFLOW_CONDITIONAL_EVAL,
1370
+ type: SpanType.WORKFLOW_CONDITIONAL_EVAL,
1402
1371
  name: `condition: '${index}'`,
1403
1372
  input: prevOutput,
1404
1373
  attributes: {
@@ -1407,47 +1376,55 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1407
1376
  tracingPolicy: this.options?.tracingPolicy
1408
1377
  });
1409
1378
  try {
1410
- const result = await cond({
1411
- runId,
1412
- workflowId,
1413
- mastra: this.mastra,
1414
- runtimeContext,
1415
- runCount: -1,
1416
- inputData: prevOutput,
1417
- state: executionContext.state,
1418
- setState: (state) => {
1419
- executionContext.state = state;
1420
- },
1421
- tracingContext: {
1422
- currentSpan: evalSpan
1423
- },
1424
- getInitData: () => stepResults?.input,
1425
- getStepResult: getStepResult.bind(this, stepResults),
1426
- // TODO: this function shouldn't have suspend probably?
1427
- suspend: async (_suspendPayload) => {
1428
- },
1429
- bail: () => {
1430
- },
1431
- abort: () => {
1432
- abortController.abort();
1433
- },
1434
- [EMITTER_SYMBOL]: emitter,
1435
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
1436
- // TODO: add streamVNext support
1437
- engine: {
1438
- step: this.inngestStep
1439
- },
1440
- abortSignal: abortController.signal,
1441
- writer: new ToolStream(
1379
+ const result = await cond(
1380
+ createDeprecationProxy(
1442
1381
  {
1443
- prefix: "workflow-step",
1444
- callId: randomUUID(),
1445
- name: "conditional",
1446
- runId
1382
+ runId,
1383
+ workflowId,
1384
+ mastra: this.mastra,
1385
+ requestContext,
1386
+ retryCount: -1,
1387
+ inputData: prevOutput,
1388
+ state: executionContext.state,
1389
+ setState: (state) => {
1390
+ executionContext.state = state;
1391
+ },
1392
+ tracingContext: {
1393
+ currentSpan: evalSpan
1394
+ },
1395
+ getInitData: () => stepResults?.input,
1396
+ getStepResult: getStepResult.bind(this, stepResults),
1397
+ // TODO: this function shouldn't have suspend probably?
1398
+ suspend: async (_suspendPayload) => {
1399
+ },
1400
+ bail: () => {
1401
+ },
1402
+ abort: () => {
1403
+ abortController.abort();
1404
+ },
1405
+ [EMITTER_SYMBOL]: emitter,
1406
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
1407
+ engine: {
1408
+ step: this.inngestStep
1409
+ },
1410
+ abortSignal: abortController.signal,
1411
+ writer: new ToolStream(
1412
+ {
1413
+ prefix: "workflow-step",
1414
+ callId: randomUUID(),
1415
+ name: "conditional",
1416
+ runId
1417
+ },
1418
+ writableStream
1419
+ )
1447
1420
  },
1448
- writableStream
1421
+ {
1422
+ paramName: "runCount",
1423
+ deprecationMessage: runCountDeprecationMessage,
1424
+ logger: this.logger
1425
+ }
1449
1426
  )
1450
- });
1427
+ );
1451
1428
  evalSpan?.end({
1452
1429
  output: result,
1453
1430
  attributes: {
@@ -1475,13 +1452,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1475
1452
  }
1476
1453
  });
1477
1454
  const results = await Promise.all(
1478
- stepsToRun.map(
1479
- (step, index) => this.executeEntry({
1480
- workflowId,
1481
- runId,
1482
- entry: step,
1483
- serializedStepGraph,
1484
- prevStep,
1455
+ stepsToRun.map(async (step, index) => {
1456
+ const currStepResult = stepResults[step.step.id];
1457
+ if (currStepResult && currStepResult.status === "success") {
1458
+ return currStepResult;
1459
+ }
1460
+ const result = await this.executeStep({
1461
+ step: step.step,
1462
+ prevOutput,
1485
1463
  stepResults,
1486
1464
  resume,
1487
1465
  executionContext: {
@@ -1491,31 +1469,32 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1491
1469
  suspendedPaths: executionContext.suspendedPaths,
1492
1470
  resumeLabels: executionContext.resumeLabels,
1493
1471
  retryConfig: executionContext.retryConfig,
1494
- executionSpan: executionContext.executionSpan,
1495
1472
  state: executionContext.state
1496
1473
  },
1497
1474
  emitter,
1498
1475
  abortController,
1499
- runtimeContext,
1476
+ requestContext,
1500
1477
  writableStream,
1501
1478
  disableScorers,
1502
1479
  tracingContext: {
1503
1480
  currentSpan: conditionalSpan
1504
1481
  }
1505
- })
1506
- )
1482
+ });
1483
+ stepResults[step.step.id] = result;
1484
+ return result;
1485
+ })
1507
1486
  );
1508
- const hasFailed = results.find((result) => result.result.status === "failed");
1509
- const hasSuspended = results.find((result) => result.result.status === "suspended");
1487
+ const hasFailed = results.find((result) => result.status === "failed");
1488
+ const hasSuspended = results.find((result) => result.status === "suspended");
1510
1489
  if (hasFailed) {
1511
- execResults = { status: "failed", error: hasFailed.result.error };
1490
+ execResults = { status: "failed", error: hasFailed.error };
1512
1491
  } else if (hasSuspended) {
1513
- execResults = { status: "suspended", suspendPayload: hasSuspended.result.suspendPayload };
1492
+ execResults = { status: "suspended", suspendPayload: hasSuspended.suspendPayload };
1514
1493
  } else {
1515
1494
  execResults = {
1516
1495
  status: "success",
1517
1496
  output: results.reduce((acc, result, index) => {
1518
- if (result.result.status === "success") {
1497
+ if (result.status === "success") {
1519
1498
  acc[stepsToRun[index].step.id] = result.output;
1520
1499
  }
1521
1500
  return acc;