@mastra/inngest 0.0.0-redis-cloud-transporter-20250508194049 → 0.0.0-scorers-api-v2-20250801171841

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,19 +1,26 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { subscribe } from '@inngest/realtime';
3
3
  import { RuntimeContext } from '@mastra/core/di';
4
- import { Run, NewWorkflow, cloneStep, createStep, DefaultExecutionEngine } from '@mastra/core/workflows/vNext';
4
+ import { ToolStream, Tool } from '@mastra/core/tools';
5
+ import { Run, Workflow, DefaultExecutionEngine } from '@mastra/core/workflows';
6
+ import { EMITTER_SYMBOL } from '@mastra/core/workflows/_constants';
5
7
  import { serve as serve$1 } from 'inngest/hono';
8
+ import { z } from 'zod';
6
9
 
7
10
  // src/index.ts
8
11
  function serve({ mastra, inngest }) {
9
- const wfs = mastra.vnext_getWorkflows();
10
- const functions = Object.values(wfs).flatMap((wf) => {
11
- if (wf instanceof InngestWorkflow) {
12
- wf.__registerMastra(mastra);
13
- return wf.getFunctions();
14
- }
15
- return [];
16
- });
12
+ const wfs = mastra.getWorkflows();
13
+ const functions = Array.from(
14
+ new Set(
15
+ Object.values(wfs).flatMap((wf) => {
16
+ if (wf instanceof InngestWorkflow) {
17
+ wf.__registerMastra(mastra);
18
+ return wf.getFunctions();
19
+ }
20
+ return [];
21
+ })
22
+ )
23
+ );
17
24
  return serve$1({
18
25
  client: inngest,
19
26
  functions
@@ -21,14 +28,16 @@ function serve({ mastra, inngest }) {
21
28
  }
22
29
  var InngestRun = class extends Run {
23
30
  inngest;
31
+ serializedStepGraph;
24
32
  #mastra;
25
33
  constructor(params, inngest) {
26
34
  super(params);
27
35
  this.inngest = inngest;
36
+ this.serializedStepGraph = params.serializedStepGraph;
28
37
  this.#mastra = params.mastra;
29
38
  }
30
39
  async getRuns(eventId) {
31
- const response = await fetch(`${this.inngest.apiBaseUrl}/v1/events/${eventId}/runs`, {
40
+ const response = await fetch(`${this.inngest.apiBaseUrl ?? "https://api.inngest.com"}/v1/events/${eventId}/runs`, {
32
41
  headers: {
33
42
  Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`
34
43
  }
@@ -38,15 +47,50 @@ var InngestRun = class extends Run {
38
47
  }
39
48
  async getRunOutput(eventId) {
40
49
  let runs = await this.getRuns(eventId);
41
- while (runs?.[0]?.status !== "Completed") {
50
+ while (runs?.[0]?.status !== "Completed" || runs?.[0]?.event_id !== eventId) {
42
51
  await new Promise((resolve) => setTimeout(resolve, 1e3));
43
52
  runs = await this.getRuns(eventId);
44
- if (runs?.[0]?.status === "Failed" || runs?.[0]?.status === "Cancelled") {
53
+ if (runs?.[0]?.status === "Failed") {
54
+ console.log("run", runs?.[0]);
45
55
  throw new Error(`Function run ${runs?.[0]?.status}`);
56
+ } else if (runs?.[0]?.status === "Cancelled") {
57
+ const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
58
+ workflowName: this.workflowId,
59
+ runId: this.runId
60
+ });
61
+ return { output: { result: { steps: snapshot?.context, status: "canceled" } } };
46
62
  }
47
63
  }
48
64
  return runs?.[0];
49
65
  }
66
+ async sendEvent(event, data) {
67
+ await this.inngest.send({
68
+ name: `user-event-${event}`,
69
+ data
70
+ });
71
+ }
72
+ async cancel() {
73
+ await this.inngest.send({
74
+ name: `cancel.workflow.${this.workflowId}`,
75
+ data: {
76
+ runId: this.runId
77
+ }
78
+ });
79
+ const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
80
+ workflowName: this.workflowId,
81
+ runId: this.runId
82
+ });
83
+ if (snapshot) {
84
+ await this.#mastra?.storage?.persistWorkflowSnapshot({
85
+ workflowName: this.workflowId,
86
+ runId: this.runId,
87
+ snapshot: {
88
+ ...snapshot,
89
+ status: "canceled"
90
+ }
91
+ });
92
+ }
93
+ }
50
94
  async start({
51
95
  inputData
52
96
  }) {
@@ -55,11 +99,13 @@ var InngestRun = class extends Run {
55
99
  runId: this.runId,
56
100
  snapshot: {
57
101
  runId: this.runId,
102
+ serializedStepGraph: this.serializedStepGraph,
58
103
  value: {},
59
104
  context: {},
60
105
  activePaths: [],
61
106
  suspendedPaths: {},
62
- timestamp: Date.now()
107
+ timestamp: Date.now(),
108
+ status: "running"
63
109
  }
64
110
  });
65
111
  const eventOutput = await this.inngest.send({
@@ -78,10 +124,23 @@ var InngestRun = class extends Run {
78
124
  if (result.status === "failed") {
79
125
  result.error = new Error(result.error);
80
126
  }
81
- this.cleanup?.();
127
+ if (result.status !== "suspended") {
128
+ this.cleanup?.();
129
+ }
82
130
  return result;
83
131
  }
84
132
  async resume(params) {
133
+ const p = this._resume(params).then((result) => {
134
+ if (result.status !== "suspended") {
135
+ this.closeStreamAction?.().catch(() => {
136
+ });
137
+ }
138
+ return result;
139
+ });
140
+ this.executionResults = p;
141
+ return p;
142
+ }
143
+ async _resume(params) {
85
144
  const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
86
145
  (step) => typeof step === "string" ? step : step?.id
87
146
  );
@@ -94,6 +153,7 @@ var InngestRun = class extends Run {
94
153
  data: {
95
154
  inputData: params.resumeData,
96
155
  runId: this.runId,
156
+ workflowId: this.workflowId,
97
157
  stepResults: snapshot?.context,
98
158
  resume: {
99
159
  steps,
@@ -115,27 +175,62 @@ var InngestRun = class extends Run {
115
175
  }
116
176
  return result;
117
177
  }
118
- watch(cb) {
178
+ watch(cb, type = "watch") {
179
+ let active = true;
119
180
  const streamPromise = subscribe(
120
181
  {
121
182
  channel: `workflow:${this.workflowId}:${this.runId}`,
122
- topics: ["watch"],
183
+ topics: [type],
123
184
  app: this.inngest
124
185
  },
125
186
  (message) => {
126
- cb(message.data);
187
+ if (active) {
188
+ cb(message.data);
189
+ }
127
190
  }
128
191
  );
129
192
  return () => {
130
- streamPromise.then((stream) => {
131
- stream.cancel();
193
+ active = false;
194
+ streamPromise.then(async (stream) => {
195
+ return stream.cancel();
132
196
  }).catch((err) => {
133
197
  console.error(err);
134
198
  });
135
199
  };
136
200
  }
201
+ stream({ inputData, runtimeContext } = {}) {
202
+ const { readable, writable } = new TransformStream();
203
+ const writer = writable.getWriter();
204
+ const unwatch = this.watch(async (event) => {
205
+ try {
206
+ await writer.write(event);
207
+ } catch {
208
+ }
209
+ }, "watch-v2");
210
+ this.closeStreamAction = async () => {
211
+ unwatch();
212
+ try {
213
+ await writer.close();
214
+ } catch (err) {
215
+ console.error("Error closing stream:", err);
216
+ } finally {
217
+ writer.releaseLock();
218
+ }
219
+ };
220
+ this.executionResults = this.start({ inputData, runtimeContext }).then((result) => {
221
+ if (result.status !== "suspended") {
222
+ this.closeStreamAction?.().catch(() => {
223
+ });
224
+ }
225
+ return result;
226
+ });
227
+ return {
228
+ stream: readable,
229
+ getWorkflowState: () => this.executionResults
230
+ };
231
+ }
137
232
  };
138
- var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
233
+ var InngestWorkflow = class _InngestWorkflow extends Workflow {
139
234
  #mastra;
140
235
  inngest;
141
236
  function;
@@ -156,11 +251,32 @@ var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
156
251
  const storage = this.#mastra?.getStorage();
157
252
  if (!storage) {
158
253
  this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
159
- return null;
254
+ return this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null;
160
255
  }
161
256
  const run = await storage.getWorkflowRunById({ runId, workflowName: this.id });
162
257
  return run ?? (this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null);
163
258
  }
259
+ async getWorkflowRunExecutionResult(runId) {
260
+ const storage = this.#mastra?.getStorage();
261
+ if (!storage) {
262
+ this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");
263
+ return null;
264
+ }
265
+ const run = await storage.getWorkflowRunById({ runId, workflowName: this.id });
266
+ if (!run?.snapshot) {
267
+ return null;
268
+ }
269
+ if (typeof run.snapshot === "string") {
270
+ return null;
271
+ }
272
+ return {
273
+ status: run.snapshot.status,
274
+ result: run.snapshot.result,
275
+ error: run.snapshot.error,
276
+ payload: run.snapshot.context?.input,
277
+ steps: run.snapshot.context
278
+ };
279
+ }
164
280
  __registerMastra(mastra) {
165
281
  this.#mastra = mastra;
166
282
  this.executionEngine.__registerMastra(mastra);
@@ -187,6 +303,7 @@ var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
187
303
  runId: runIdToUse,
188
304
  executionEngine: this.executionEngine,
189
305
  executionGraph: this.executionGraph,
306
+ serializedStepGraph: this.serializedStepGraph,
190
307
  mastra: this.#mastra,
191
308
  retryConfig: this.retryConfig,
192
309
  cleanup: () => this.runs.delete(runIdToUse)
@@ -196,13 +313,55 @@ var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
196
313
  this.runs.set(runIdToUse, run);
197
314
  return run;
198
315
  }
316
+ async createRunAsync(options) {
317
+ const runIdToUse = options?.runId || randomUUID();
318
+ const run = this.runs.get(runIdToUse) ?? new InngestRun(
319
+ {
320
+ workflowId: this.id,
321
+ runId: runIdToUse,
322
+ executionEngine: this.executionEngine,
323
+ executionGraph: this.executionGraph,
324
+ serializedStepGraph: this.serializedStepGraph,
325
+ mastra: this.#mastra,
326
+ retryConfig: this.retryConfig,
327
+ cleanup: () => this.runs.delete(runIdToUse)
328
+ },
329
+ this.inngest
330
+ );
331
+ this.runs.set(runIdToUse, run);
332
+ const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse);
333
+ if (!workflowSnapshotInStorage) {
334
+ await this.mastra?.getStorage()?.persistWorkflowSnapshot({
335
+ workflowName: this.id,
336
+ runId: runIdToUse,
337
+ snapshot: {
338
+ runId: runIdToUse,
339
+ status: "pending",
340
+ value: {},
341
+ context: {},
342
+ activePaths: [],
343
+ serializedStepGraph: this.serializedStepGraph,
344
+ suspendedPaths: {},
345
+ result: void 0,
346
+ error: void 0,
347
+ // @ts-ignore
348
+ timestamp: Date.now()
349
+ }
350
+ });
351
+ }
352
+ return run;
353
+ }
199
354
  getFunction() {
200
355
  if (this.function) {
201
356
  return this.function;
202
357
  }
203
358
  this.function = this.inngest.createFunction(
204
- // @ts-ignore
205
- { id: `workflow.${this.id}`, retries: this.retryConfig?.attempts ?? 0 },
359
+ {
360
+ id: `workflow.${this.id}`,
361
+ // @ts-ignore
362
+ retries: this.retryConfig?.attempts ?? 0,
363
+ cancelOn: [{ event: `cancel.workflow.${this.id}` }]
364
+ },
206
365
  { event: `workflow.${this.id}` },
207
366
  async ({ event, step, attempt, publish }) => {
208
367
  let { inputData, runId, resume } = event.data;
@@ -219,12 +378,18 @@ var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
219
378
  try {
220
379
  await publish({
221
380
  channel: `workflow:${this.id}:${runId}`,
222
- topic: "watch",
381
+ topic: event2,
223
382
  data
224
383
  });
225
384
  } catch (err) {
226
385
  this.logger.error("Error emitting event: " + (err?.stack ?? err?.message ?? err));
227
386
  }
387
+ },
388
+ on: (_event, _callback) => {
389
+ },
390
+ off: (_event, _callback) => {
391
+ },
392
+ once: (_event, _callback) => {
228
393
  }
229
394
  };
230
395
  const engine = new InngestExecutionEngine(this.#mastra, step, attempt);
@@ -232,12 +397,14 @@ var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
232
397
  workflowId: this.id,
233
398
  runId,
234
399
  graph: this.executionGraph,
400
+ serializedStepGraph: this.serializedStepGraph,
235
401
  input: inputData,
236
402
  emitter,
237
403
  retryConfig: this.retryConfig,
238
404
  runtimeContext: new RuntimeContext(),
239
405
  // TODO
240
- resume
406
+ resume,
407
+ abortController: new AbortController()
241
408
  });
242
409
  return { result, runId };
243
410
  }
@@ -261,20 +428,110 @@ var InngestWorkflow = class _InngestWorkflow extends NewWorkflow {
261
428
  return [this.getFunction(), ...this.getNestedFunctions(this.executionGraph.steps)];
262
429
  }
263
430
  };
264
- function cloneWorkflow(workflow, opts) {
265
- const wf = new InngestWorkflow(
266
- {
267
- id: opts.id,
268
- inputSchema: workflow.inputSchema,
269
- outputSchema: workflow.outputSchema,
270
- steps: workflow.stepDefs,
271
- mastra: workflow.mastra
272
- },
273
- workflow.inngest
274
- );
275
- wf.setStepFlow(workflow.stepGraph);
276
- wf.commit();
277
- return wf;
431
+ function isAgent(params) {
432
+ return params?.component === "AGENT";
433
+ }
434
+ function isTool(params) {
435
+ return params instanceof Tool;
436
+ }
437
+ function createStep(params) {
438
+ if (isAgent(params)) {
439
+ return {
440
+ id: params.name,
441
+ // @ts-ignore
442
+ inputSchema: z.object({
443
+ prompt: z.string()
444
+ // resourceId: z.string().optional(),
445
+ // threadId: z.string().optional(),
446
+ }),
447
+ // @ts-ignore
448
+ outputSchema: z.object({
449
+ text: z.string()
450
+ }),
451
+ execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort }) => {
452
+ let streamPromise = {};
453
+ streamPromise.promise = new Promise((resolve, reject) => {
454
+ streamPromise.resolve = resolve;
455
+ streamPromise.reject = reject;
456
+ });
457
+ const toolData = {
458
+ name: params.name,
459
+ args: inputData
460
+ };
461
+ await emitter.emit("watch-v2", {
462
+ type: "tool-call-streaming-start",
463
+ ...toolData
464
+ });
465
+ const { fullStream } = await params.stream(inputData.prompt, {
466
+ // resourceId: inputData.resourceId,
467
+ // threadId: inputData.threadId,
468
+ runtimeContext,
469
+ onFinish: (result) => {
470
+ streamPromise.resolve(result.text);
471
+ },
472
+ abortSignal
473
+ });
474
+ if (abortSignal.aborted) {
475
+ return abort();
476
+ }
477
+ for await (const chunk of fullStream) {
478
+ switch (chunk.type) {
479
+ case "text-delta":
480
+ await emitter.emit("watch-v2", {
481
+ type: "tool-call-delta",
482
+ ...toolData,
483
+ argsTextDelta: chunk.textDelta
484
+ });
485
+ break;
486
+ case "step-start":
487
+ case "step-finish":
488
+ case "finish":
489
+ break;
490
+ case "tool-call":
491
+ case "tool-result":
492
+ case "tool-call-streaming-start":
493
+ case "tool-call-delta":
494
+ case "source":
495
+ case "file":
496
+ default:
497
+ await emitter.emit("watch-v2", chunk);
498
+ break;
499
+ }
500
+ }
501
+ return {
502
+ text: await streamPromise.promise
503
+ };
504
+ }
505
+ };
506
+ }
507
+ if (isTool(params)) {
508
+ if (!params.inputSchema || !params.outputSchema) {
509
+ throw new Error("Tool must have input and output schemas defined");
510
+ }
511
+ return {
512
+ // TODO: tool probably should have strong id type
513
+ // @ts-ignore
514
+ id: params.id,
515
+ inputSchema: params.inputSchema,
516
+ outputSchema: params.outputSchema,
517
+ execute: async ({ inputData, mastra, runtimeContext }) => {
518
+ return params.execute({
519
+ context: inputData,
520
+ mastra,
521
+ runtimeContext
522
+ });
523
+ }
524
+ };
525
+ }
526
+ return {
527
+ id: params.id,
528
+ description: params.description,
529
+ inputSchema: params.inputSchema,
530
+ outputSchema: params.outputSchema,
531
+ resumeSchema: params.resumeSchema,
532
+ suspendSchema: params.suspendSchema,
533
+ execute: params.execute
534
+ };
278
535
  }
279
536
  function init(inngest) {
280
537
  return {
@@ -282,8 +539,27 @@ function init(inngest) {
282
539
  return new InngestWorkflow(params, inngest);
283
540
  },
284
541
  createStep,
285
- cloneStep,
286
- cloneWorkflow
542
+ cloneStep(step, opts) {
543
+ return {
544
+ id: opts.id,
545
+ description: step.description,
546
+ inputSchema: step.inputSchema,
547
+ outputSchema: step.outputSchema,
548
+ execute: step.execute
549
+ };
550
+ },
551
+ cloneWorkflow(workflow, opts) {
552
+ const wf = new Workflow({
553
+ id: opts.id,
554
+ inputSchema: workflow.inputSchema,
555
+ outputSchema: workflow.outputSchema,
556
+ steps: workflow.stepDefs,
557
+ mastra: workflow.mastra
558
+ });
559
+ wf.setStepFlow(workflow.stepGraph);
560
+ wf.commit();
561
+ return wf;
562
+ }
287
563
  };
288
564
  }
289
565
  var InngestExecutionEngine = class extends DefaultExecutionEngine {
@@ -294,6 +570,18 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
294
570
  this.inngestStep = inngestStep;
295
571
  this.inngestAttempts = inngestAttempts;
296
572
  }
573
+ async execute(params) {
574
+ await params.emitter.emit("watch-v2", {
575
+ type: "start",
576
+ payload: { runId: params.runId }
577
+ });
578
+ const result = await super.execute(params);
579
+ await params.emitter.emit("watch-v2", {
580
+ type: "finish",
581
+ payload: { runId: params.runId }
582
+ });
583
+ return result;
584
+ }
297
585
  async fmtReturnValue(executionSpan, emitter, stepResults, lastOutput, error) {
298
586
  const base = {
299
587
  status: lastOutput.status,
@@ -360,7 +648,9 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
360
648
  resume,
361
649
  prevOutput,
362
650
  emitter,
363
- runtimeContext
651
+ abortController,
652
+ runtimeContext,
653
+ writableStream
364
654
  }) {
365
655
  return super.executeStep({
366
656
  workflowId,
@@ -371,9 +661,143 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
371
661
  resume,
372
662
  prevOutput,
373
663
  emitter,
374
- runtimeContext
664
+ abortController,
665
+ runtimeContext,
666
+ writableStream
375
667
  });
376
668
  }
669
+ // async executeSleep({ id, duration }: { id: string; duration: number }): Promise<void> {
670
+ // await this.inngestStep.sleep(id, duration);
671
+ // }
672
+ async executeSleep({
673
+ workflowId,
674
+ runId,
675
+ entry,
676
+ prevOutput,
677
+ stepResults,
678
+ emitter,
679
+ abortController,
680
+ runtimeContext,
681
+ writableStream
682
+ }) {
683
+ let { duration, fn } = entry;
684
+ if (fn) {
685
+ const stepCallId = randomUUID();
686
+ duration = await this.inngestStep.run(`workflow.${workflowId}.sleep.${entry.id}`, async () => {
687
+ return await fn({
688
+ runId,
689
+ workflowId,
690
+ mastra: this.mastra,
691
+ runtimeContext,
692
+ inputData: prevOutput,
693
+ runCount: -1,
694
+ getInitData: () => stepResults?.input,
695
+ getStepResult: (step) => {
696
+ if (!step?.id) {
697
+ return null;
698
+ }
699
+ const result = stepResults[step.id];
700
+ if (result?.status === "success") {
701
+ return result.output;
702
+ }
703
+ return null;
704
+ },
705
+ // TODO: this function shouldn't have suspend probably?
706
+ suspend: async (_suspendPayload) => {
707
+ },
708
+ bail: () => {
709
+ },
710
+ abort: () => {
711
+ abortController?.abort();
712
+ },
713
+ [EMITTER_SYMBOL]: emitter,
714
+ engine: { step: this.inngestStep },
715
+ abortSignal: abortController?.signal,
716
+ writer: new ToolStream(
717
+ {
718
+ prefix: "step",
719
+ callId: stepCallId,
720
+ name: "sleep",
721
+ runId
722
+ },
723
+ writableStream
724
+ )
725
+ });
726
+ });
727
+ }
728
+ await this.inngestStep.sleep(entry.id, !duration || duration < 0 ? 0 : duration);
729
+ }
730
+ async executeSleepUntil({
731
+ workflowId,
732
+ runId,
733
+ entry,
734
+ prevOutput,
735
+ stepResults,
736
+ emitter,
737
+ abortController,
738
+ runtimeContext,
739
+ writableStream
740
+ }) {
741
+ let { date, fn } = entry;
742
+ if (fn) {
743
+ date = await this.inngestStep.run(`workflow.${workflowId}.sleepUntil.${entry.id}`, async () => {
744
+ const stepCallId = randomUUID();
745
+ return await fn({
746
+ runId,
747
+ workflowId,
748
+ mastra: this.mastra,
749
+ runtimeContext,
750
+ inputData: prevOutput,
751
+ runCount: -1,
752
+ getInitData: () => stepResults?.input,
753
+ getStepResult: (step) => {
754
+ if (!step?.id) {
755
+ return null;
756
+ }
757
+ const result = stepResults[step.id];
758
+ if (result?.status === "success") {
759
+ return result.output;
760
+ }
761
+ return null;
762
+ },
763
+ // TODO: this function shouldn't have suspend probably?
764
+ suspend: async (_suspendPayload) => {
765
+ },
766
+ bail: () => {
767
+ },
768
+ abort: () => {
769
+ abortController?.abort();
770
+ },
771
+ [EMITTER_SYMBOL]: emitter,
772
+ engine: { step: this.inngestStep },
773
+ abortSignal: abortController?.signal,
774
+ writer: new ToolStream(
775
+ {
776
+ prefix: "step",
777
+ callId: stepCallId,
778
+ name: "sleep",
779
+ runId
780
+ },
781
+ writableStream
782
+ )
783
+ });
784
+ });
785
+ }
786
+ if (!(date instanceof Date)) {
787
+ return;
788
+ }
789
+ await this.inngestStep.sleepUntil(entry.id, date);
790
+ }
791
+ async executeWaitForEvent({ event, timeout }) {
792
+ const eventData = await this.inngestStep.waitForEvent(`user-event-${event}`, {
793
+ event: `user-event-${event}`,
794
+ timeout: timeout ?? 5e3
795
+ });
796
+ if (eventData === null) {
797
+ throw "Timeout waiting for event";
798
+ }
799
+ return eventData?.data;
800
+ }
377
801
  async executeStep({
378
802
  step,
379
803
  stepResults,
@@ -381,11 +805,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
381
805
  resume,
382
806
  prevOutput,
383
807
  emitter,
384
- runtimeContext
808
+ abortController,
809
+ runtimeContext,
810
+ writableStream
385
811
  }) {
386
- await this.inngestStep.run(
812
+ const startedAt = await this.inngestStep.run(
387
813
  `workflow.${executionContext.workflowId}.run.${executionContext.runId}.step.${step.id}.running_ev`,
388
814
  async () => {
815
+ const startedAt2 = Date.now();
389
816
  await emitter.emit("watch", {
390
817
  type: "watch",
391
818
  payload: {
@@ -407,6 +834,16 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
407
834
  },
408
835
  eventTimestamp: Date.now()
409
836
  });
837
+ await emitter.emit("watch-v2", {
838
+ type: "step-start",
839
+ payload: {
840
+ id: step.id,
841
+ status: "running",
842
+ payload: prevOutput,
843
+ startedAt: startedAt2
844
+ }
845
+ });
846
+ return startedAt2;
410
847
  }
411
848
  );
412
849
  if (step instanceof InngestWorkflow) {
@@ -467,6 +904,15 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
467
904
  },
468
905
  eventTimestamp: Date.now()
469
906
  });
907
+ await emitter.emit("watch-v2", {
908
+ type: "step-result",
909
+ payload: {
910
+ id: step.id,
911
+ status: "failed",
912
+ error: result?.error,
913
+ payload: prevOutput
914
+ }
915
+ });
470
916
  return { executionContext, result: { status: "failed", error: result?.error } };
471
917
  } else if (result.status === "suspended") {
472
918
  const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
@@ -493,6 +939,13 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
493
939
  },
494
940
  eventTimestamp: Date.now()
495
941
  });
942
+ await emitter.emit("watch-v2", {
943
+ type: "step-suspended",
944
+ payload: {
945
+ id: step.id,
946
+ status: "suspended"
947
+ }
948
+ });
496
949
  return {
497
950
  executionContext,
498
951
  result: {
@@ -543,6 +996,21 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
543
996
  },
544
997
  eventTimestamp: Date.now()
545
998
  });
999
+ await emitter.emit("watch-v2", {
1000
+ type: "step-result",
1001
+ payload: {
1002
+ id: step.id,
1003
+ status: "success",
1004
+ output: result?.result
1005
+ }
1006
+ });
1007
+ await emitter.emit("watch-v2", {
1008
+ type: "step-finish",
1009
+ payload: {
1010
+ id: step.id,
1011
+ metadata: {}
1012
+ }
1013
+ });
546
1014
  return { executionContext, result: { status: "success", output: result?.result } };
547
1015
  }
548
1016
  );
@@ -552,10 +1020,13 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
552
1020
  const stepRes = await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}`, async () => {
553
1021
  let execResults;
554
1022
  let suspended;
1023
+ let bailed;
555
1024
  try {
556
1025
  const result = await step.execute({
1026
+ runId: executionContext.runId,
557
1027
  mastra: this.mastra,
558
1028
  runtimeContext,
1029
+ writableStream,
559
1030
  inputData: prevOutput,
560
1031
  resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
561
1032
  getInitData: () => stepResults?.input,
@@ -570,20 +1041,54 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
570
1041
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
571
1042
  suspended = { payload: suspendPayload };
572
1043
  },
1044
+ bail: (result2) => {
1045
+ bailed = { payload: result2 };
1046
+ },
573
1047
  resume: {
574
1048
  steps: resume?.steps?.slice(1) || [],
575
1049
  resumePayload: resume?.resumePayload,
576
1050
  // @ts-ignore
577
1051
  runId: stepResults[step.id]?.payload?.__workflow_meta?.runId
578
1052
  },
579
- emitter
1053
+ [EMITTER_SYMBOL]: emitter,
1054
+ engine: {
1055
+ step: this.inngestStep
1056
+ },
1057
+ abortSignal: abortController.signal
580
1058
  });
581
- execResults = { status: "success", output: result };
1059
+ const endedAt = Date.now();
1060
+ execResults = {
1061
+ status: "success",
1062
+ output: result,
1063
+ startedAt,
1064
+ endedAt,
1065
+ payload: prevOutput,
1066
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1067
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1068
+ };
582
1069
  } catch (e) {
583
- execResults = { status: "failed", error: e instanceof Error ? e.message : String(e) };
1070
+ execResults = {
1071
+ status: "failed",
1072
+ payload: prevOutput,
1073
+ error: e instanceof Error ? e.message : String(e),
1074
+ endedAt: Date.now(),
1075
+ startedAt,
1076
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1077
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1078
+ };
584
1079
  }
585
1080
  if (suspended) {
586
- execResults = { status: "suspended", payload: suspended.payload };
1081
+ execResults = {
1082
+ status: "suspended",
1083
+ suspendedPayload: suspended.payload,
1084
+ payload: prevOutput,
1085
+ suspendedAt: Date.now(),
1086
+ startedAt,
1087
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1088
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1089
+ };
1090
+ } else if (bailed) {
1091
+ execResults = { status: "bailed", output: bailed.payload, payload: prevOutput, endedAt: Date.now(), startedAt };
587
1092
  }
588
1093
  if (execResults.status === "failed") {
589
1094
  if (executionContext.retryConfig.attempts > 0 && this.inngestAttempts < executionContext.retryConfig.attempts) {
@@ -595,18 +1100,41 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
595
1100
  payload: {
596
1101
  currentStep: {
597
1102
  id: step.id,
598
- status: execResults.status,
599
- output: execResults.output
1103
+ ...execResults
600
1104
  },
601
1105
  workflowState: {
602
1106
  status: "running",
603
- steps: stepResults,
1107
+ steps: { ...stepResults, [step.id]: execResults },
604
1108
  result: null,
605
1109
  error: null
606
1110
  }
607
1111
  },
608
1112
  eventTimestamp: Date.now()
609
1113
  });
1114
+ if (execResults.status === "suspended") {
1115
+ await emitter.emit("watch-v2", {
1116
+ type: "step-suspended",
1117
+ payload: {
1118
+ id: step.id,
1119
+ ...execResults
1120
+ }
1121
+ });
1122
+ } else {
1123
+ await emitter.emit("watch-v2", {
1124
+ type: "step-result",
1125
+ payload: {
1126
+ id: step.id,
1127
+ ...execResults
1128
+ }
1129
+ });
1130
+ await emitter.emit("watch-v2", {
1131
+ type: "step-finish",
1132
+ payload: {
1133
+ id: step.id,
1134
+ metadata: {}
1135
+ }
1136
+ });
1137
+ }
610
1138
  return { result: execResults, executionContext, stepResults };
611
1139
  });
612
1140
  Object.assign(executionContext.suspendedPaths, stepRes.executionContext.suspendedPaths);
@@ -617,7 +1145,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
617
1145
  workflowId,
618
1146
  runId,
619
1147
  stepResults,
620
- executionContext
1148
+ executionContext,
1149
+ serializedStepGraph,
1150
+ workflowStatus,
1151
+ result,
1152
+ error
621
1153
  }) {
622
1154
  await this.inngestStep.run(
623
1155
  `workflow.${workflowId}.run.${runId}.path.${JSON.stringify(executionContext.executionPath)}.stepUpdate`,
@@ -631,6 +1163,10 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
631
1163
  context: stepResults,
632
1164
  activePaths: [],
633
1165
  suspendedPaths: executionContext.suspendedPaths,
1166
+ serializedStepGraph,
1167
+ status: workflowStatus,
1168
+ result,
1169
+ error,
634
1170
  // @ts-ignore
635
1171
  timestamp: Date.now()
636
1172
  }
@@ -645,10 +1181,13 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
645
1181
  prevOutput,
646
1182
  prevStep,
647
1183
  stepResults,
1184
+ serializedStepGraph,
648
1185
  resume,
649
1186
  executionContext,
650
1187
  emitter,
651
- runtimeContext
1188
+ abortController,
1189
+ runtimeContext,
1190
+ writableStream
652
1191
  }) {
653
1192
  let execResults;
654
1193
  const truthyIndexes = (await Promise.all(
@@ -656,8 +1195,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
656
1195
  (cond, index) => this.inngestStep.run(`workflow.${workflowId}.conditional.${index}`, async () => {
657
1196
  try {
658
1197
  const result = await cond({
1198
+ runId,
1199
+ workflowId,
659
1200
  mastra: this.mastra,
660
1201
  runtimeContext,
1202
+ runCount: -1,
661
1203
  inputData: prevOutput,
662
1204
  getInitData: () => stepResults?.input,
663
1205
  getStepResult: (step) => {
@@ -673,7 +1215,25 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
673
1215
  // TODO: this function shouldn't have suspend probably?
674
1216
  suspend: async (_suspendPayload) => {
675
1217
  },
676
- emitter
1218
+ bail: () => {
1219
+ },
1220
+ abort: () => {
1221
+ abortController.abort();
1222
+ },
1223
+ [EMITTER_SYMBOL]: emitter,
1224
+ engine: {
1225
+ step: this.inngestStep
1226
+ },
1227
+ abortSignal: abortController.signal,
1228
+ writer: new ToolStream(
1229
+ {
1230
+ prefix: "step",
1231
+ callId: randomUUID(),
1232
+ name: "conditional",
1233
+ runId
1234
+ },
1235
+ writableStream
1236
+ )
677
1237
  });
678
1238
  return result ? index : null;
679
1239
  } catch (e) {
@@ -692,6 +1252,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
692
1252
  prevStep,
693
1253
  stepResults,
694
1254
  resume,
1255
+ serializedStepGraph,
695
1256
  executionContext: {
696
1257
  workflowId,
697
1258
  runId,
@@ -701,21 +1262,23 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
701
1262
  executionSpan: executionContext.executionSpan
702
1263
  },
703
1264
  emitter,
704
- runtimeContext
1265
+ abortController,
1266
+ runtimeContext,
1267
+ writableStream
705
1268
  })
706
1269
  )
707
1270
  );
708
- const hasFailed = results.find((result) => result.status === "failed");
709
- const hasSuspended = results.find((result) => result.status === "suspended");
1271
+ const hasFailed = results.find((result) => result.result.status === "failed");
1272
+ const hasSuspended = results.find((result) => result.result.status === "suspended");
710
1273
  if (hasFailed) {
711
- execResults = { status: "failed", error: hasFailed.error };
1274
+ execResults = { status: "failed", error: hasFailed.result.error };
712
1275
  } else if (hasSuspended) {
713
- execResults = { status: "suspended", payload: hasSuspended.payload };
1276
+ execResults = { status: "suspended", payload: hasSuspended.result.suspendPayload };
714
1277
  } else {
715
1278
  execResults = {
716
1279
  status: "success",
717
1280
  output: results.reduce((acc, result, index) => {
718
- if (result.status === "success") {
1281
+ if (result.result.status === "success") {
719
1282
  acc[stepsToRun[index].step.id] = result.output;
720
1283
  }
721
1284
  return acc;
@@ -726,4 +1289,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
726
1289
  }
727
1290
  };
728
1291
 
729
- export { InngestExecutionEngine, InngestRun, InngestWorkflow, init, serve };
1292
+ export { InngestExecutionEngine, InngestRun, InngestWorkflow, createStep, init, serve };
1293
+ //# sourceMappingURL=index.js.map
1294
+ //# sourceMappingURL=index.js.map