@mastra/inngest 0.0.0-new-scorer-api-20250801075530 → 0.0.0-rag-chunk-extract-llm-option-20250926183645

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,16 +1,22 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { subscribe } from '@inngest/realtime';
3
+ import { wrapMastra, AISpanType } from '@mastra/core/ai-tracing';
3
4
  import { RuntimeContext } from '@mastra/core/di';
4
5
  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';
6
+ import { Run, Workflow, DefaultExecutionEngine, getStepResult, validateStepInput } from '@mastra/core/workflows';
7
+ import { EMITTER_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
7
8
  import { serve as serve$1 } from 'inngest/hono';
8
9
  import { z } from 'zod';
9
10
 
10
11
  // src/index.ts
11
- function serve({ mastra, inngest }) {
12
+ function serve({
13
+ mastra,
14
+ inngest,
15
+ functions: userFunctions = [],
16
+ registerOptions
17
+ }) {
12
18
  const wfs = mastra.getWorkflows();
13
- const functions = Array.from(
19
+ const workflowFunctions = Array.from(
14
20
  new Set(
15
21
  Object.values(wfs).flatMap((wf) => {
16
22
  if (wf instanceof InngestWorkflow) {
@@ -22,8 +28,9 @@ function serve({ mastra, inngest }) {
22
28
  )
23
29
  );
24
30
  return serve$1({
31
+ ...registerOptions,
25
32
  client: inngest,
26
- functions
33
+ functions: [...workflowFunctions, ...userFunctions]
27
34
  });
28
35
  }
29
36
  var InngestRun = class extends Run {
@@ -51,7 +58,6 @@ var InngestRun = class extends Run {
51
58
  await new Promise((resolve) => setTimeout(resolve, 1e3));
52
59
  runs = await this.getRuns(eventId);
53
60
  if (runs?.[0]?.status === "Failed") {
54
- console.log("run", runs?.[0]);
55
61
  throw new Error(`Function run ${runs?.[0]?.status}`);
56
62
  } else if (runs?.[0]?.status === "Cancelled") {
57
63
  const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
@@ -84,6 +90,7 @@ var InngestRun = class extends Run {
84
90
  await this.#mastra?.storage?.persistWorkflowSnapshot({
85
91
  workflowName: this.workflowId,
86
92
  runId: this.runId,
93
+ resourceId: this.resourceId,
87
94
  snapshot: {
88
95
  ...snapshot,
89
96
  status: "canceled"
@@ -97,6 +104,7 @@ var InngestRun = class extends Run {
97
104
  await this.#mastra.getStorage()?.persistWorkflowSnapshot({
98
105
  workflowName: this.workflowId,
99
106
  runId: this.runId,
107
+ resourceId: this.resourceId,
100
108
  snapshot: {
101
109
  runId: this.runId,
102
110
  serializedStepGraph: this.serializedStepGraph,
@@ -104,15 +112,18 @@ var InngestRun = class extends Run {
104
112
  context: {},
105
113
  activePaths: [],
106
114
  suspendedPaths: {},
115
+ waitingPaths: {},
107
116
  timestamp: Date.now(),
108
117
  status: "running"
109
118
  }
110
119
  });
120
+ const inputDataToUse = await this._validateInput(inputData);
111
121
  const eventOutput = await this.inngest.send({
112
122
  name: `workflow.${this.workflowId}`,
113
123
  data: {
114
- inputData,
115
- runId: this.runId
124
+ inputData: inputDataToUse,
125
+ runId: this.runId,
126
+ resourceId: this.resourceId
116
127
  }
117
128
  });
118
129
  const eventId = eventOutput.ids[0];
@@ -148,17 +159,19 @@ var InngestRun = class extends Run {
148
159
  workflowName: this.workflowId,
149
160
  runId: this.runId
150
161
  });
162
+ const suspendedStep = this.workflowSteps[steps?.[0] ?? ""];
163
+ const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);
151
164
  const eventOutput = await this.inngest.send({
152
165
  name: `workflow.${this.workflowId}`,
153
166
  data: {
154
- inputData: params.resumeData,
167
+ inputData: resumeDataToUse,
155
168
  runId: this.runId,
156
169
  workflowId: this.workflowId,
157
170
  stepResults: snapshot?.context,
158
171
  resume: {
159
172
  steps,
160
173
  stepResults: snapshot?.context,
161
- resumePayload: params.resumeData,
174
+ resumePayload: resumeDataToUse,
162
175
  // @ts-ignore
163
176
  resumePath: snapshot?.suspendedPaths?.[steps?.[0]]
164
177
  }
@@ -203,7 +216,11 @@ var InngestRun = class extends Run {
203
216
  const writer = writable.getWriter();
204
217
  const unwatch = this.watch(async (event) => {
205
218
  try {
206
- await writer.write(event);
219
+ const e = {
220
+ ...event,
221
+ type: event.type.replace("workflow-", "")
222
+ };
223
+ await writer.write(e);
207
224
  } catch {
208
225
  }
209
226
  }, "watch-v2");
@@ -234,8 +251,14 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
234
251
  #mastra;
235
252
  inngest;
236
253
  function;
254
+ flowControlConfig;
237
255
  constructor(params, inngest) {
238
- super(params);
256
+ const { concurrency, rateLimit, throttle, debounce, priority, ...workflowParams } = params;
257
+ super(workflowParams);
258
+ const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(
259
+ ([_, value]) => value !== void 0
260
+ );
261
+ this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : void 0;
239
262
  this.#mastra = params.mastra;
240
263
  this.inngest = inngest;
241
264
  }
@@ -256,27 +279,6 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
256
279
  const run = await storage.getWorkflowRunById({ runId, workflowName: this.id });
257
280
  return run ?? (this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null);
258
281
  }
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
- }
280
282
  __registerMastra(mastra) {
281
283
  this.#mastra = mastra;
282
284
  this.executionEngine.__registerMastra(mastra);
@@ -295,23 +297,14 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
295
297
  }
296
298
  }
297
299
  }
298
- createRun(options) {
299
- const runIdToUse = options?.runId || randomUUID();
300
- const run = this.runs.get(runIdToUse) ?? new InngestRun(
301
- {
302
- workflowId: this.id,
303
- runId: runIdToUse,
304
- executionEngine: this.executionEngine,
305
- executionGraph: this.executionGraph,
306
- serializedStepGraph: this.serializedStepGraph,
307
- mastra: this.#mastra,
308
- retryConfig: this.retryConfig,
309
- cleanup: () => this.runs.delete(runIdToUse)
310
- },
311
- this.inngest
300
+ /**
301
+ * @deprecated Use createRunAsync() instead.
302
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
303
+ */
304
+ createRun(_options) {
305
+ throw new Error(
306
+ "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."
312
307
  );
313
- this.runs.set(runIdToUse, run);
314
- return run;
315
308
  }
316
309
  async createRunAsync(options) {
317
310
  const runIdToUse = options?.runId || randomUUID();
@@ -319,27 +312,31 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
319
312
  {
320
313
  workflowId: this.id,
321
314
  runId: runIdToUse,
315
+ resourceId: options?.resourceId,
322
316
  executionEngine: this.executionEngine,
323
317
  executionGraph: this.executionGraph,
324
318
  serializedStepGraph: this.serializedStepGraph,
325
319
  mastra: this.#mastra,
326
320
  retryConfig: this.retryConfig,
327
- cleanup: () => this.runs.delete(runIdToUse)
321
+ cleanup: () => this.runs.delete(runIdToUse),
322
+ workflowSteps: this.steps
328
323
  },
329
324
  this.inngest
330
325
  );
331
326
  this.runs.set(runIdToUse, run);
332
- const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse);
327
+ const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse, false);
333
328
  if (!workflowSnapshotInStorage) {
334
329
  await this.mastra?.getStorage()?.persistWorkflowSnapshot({
335
330
  workflowName: this.id,
336
331
  runId: runIdToUse,
332
+ resourceId: options?.resourceId,
337
333
  snapshot: {
338
334
  runId: runIdToUse,
339
335
  status: "pending",
340
336
  value: {},
341
337
  context: {},
342
338
  activePaths: [],
339
+ waitingPaths: {},
343
340
  serializedStepGraph: this.serializedStepGraph,
344
341
  suspendedPaths: {},
345
342
  result: void 0,
@@ -360,11 +357,13 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
360
357
  id: `workflow.${this.id}`,
361
358
  // @ts-ignore
362
359
  retries: this.retryConfig?.attempts ?? 0,
363
- cancelOn: [{ event: `cancel.workflow.${this.id}` }]
360
+ cancelOn: [{ event: `cancel.workflow.${this.id}` }],
361
+ // Spread flow control configuration
362
+ ...this.flowControlConfig
364
363
  },
365
364
  { event: `workflow.${this.id}` },
366
365
  async ({ event, step, attempt, publish }) => {
367
- let { inputData, runId, resume } = event.data;
366
+ let { inputData, runId, resourceId, resume } = event.data;
368
367
  if (!runId) {
369
368
  runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
370
369
  return randomUUID();
@@ -396,6 +395,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
396
395
  const result = await engine.execute({
397
396
  workflowId: this.id,
398
397
  runId,
398
+ resourceId,
399
399
  graph: this.executionGraph,
400
400
  serializedStepGraph: this.serializedStepGraph,
401
401
  input: inputData,
@@ -404,7 +404,9 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
404
404
  runtimeContext: new RuntimeContext(),
405
405
  // TODO
406
406
  resume,
407
- abortController: new AbortController()
407
+ abortController: new AbortController(),
408
+ currentSpan: void 0
409
+ // TODO: Pass actual parent AI span from workflow execution context
408
410
  });
409
411
  return { result, runId };
410
412
  }
@@ -438,17 +440,16 @@ function createStep(params) {
438
440
  if (isAgent(params)) {
439
441
  return {
440
442
  id: params.name,
443
+ description: params.getDescription(),
441
444
  // @ts-ignore
442
445
  inputSchema: z.object({
443
446
  prompt: z.string()
444
- // resourceId: z.string().optional(),
445
- // threadId: z.string().optional(),
446
447
  }),
447
448
  // @ts-ignore
448
449
  outputSchema: z.object({
449
450
  text: z.string()
450
451
  }),
451
- execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort }) => {
452
+ execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort, tracingContext }) => {
452
453
  let streamPromise = {};
453
454
  streamPromise.promise = new Promise((resolve, reject) => {
454
455
  streamPromise.resolve = resolve;
@@ -458,14 +459,9 @@ function createStep(params) {
458
459
  name: params.name,
459
460
  args: inputData
460
461
  };
461
- await emitter.emit("watch-v2", {
462
- type: "tool-call-streaming-start",
463
- ...toolData
464
- });
465
462
  const { fullStream } = await params.stream(inputData.prompt, {
466
- // resourceId: inputData.resourceId,
467
- // threadId: inputData.threadId,
468
463
  runtimeContext,
464
+ tracingContext,
469
465
  onFinish: (result) => {
470
466
  streamPromise.resolve(result.text);
471
467
  },
@@ -474,34 +470,28 @@ function createStep(params) {
474
470
  if (abortSignal.aborted) {
475
471
  return abort();
476
472
  }
473
+ await emitter.emit("watch-v2", {
474
+ type: "tool-call-streaming-start",
475
+ ...toolData ?? {}
476
+ });
477
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;
478
+ if (chunk.type === "text-delta") {
479
+ await emitter.emit("watch-v2", {
480
+ type: "tool-call-delta",
481
+ ...toolData ?? {},
482
+ argsTextDelta: chunk.textDelta
483
+ });
499
484
  }
500
485
  }
486
+ await emitter.emit("watch-v2", {
487
+ type: "tool-call-streaming-finish",
488
+ ...toolData ?? {}
489
+ });
501
490
  return {
502
491
  text: await streamPromise.promise
503
492
  };
504
- }
493
+ },
494
+ component: params.component
505
495
  };
506
496
  }
507
497
  if (isTool(params)) {
@@ -512,15 +502,20 @@ function createStep(params) {
512
502
  // TODO: tool probably should have strong id type
513
503
  // @ts-ignore
514
504
  id: params.id,
505
+ description: params.description,
515
506
  inputSchema: params.inputSchema,
516
507
  outputSchema: params.outputSchema,
517
- execute: async ({ inputData, mastra, runtimeContext }) => {
508
+ execute: async ({ inputData, mastra, runtimeContext, tracingContext, suspend, resumeData }) => {
518
509
  return params.execute({
519
510
  context: inputData,
520
- mastra,
521
- runtimeContext
511
+ mastra: wrapMastra(mastra, tracingContext),
512
+ runtimeContext,
513
+ tracingContext,
514
+ suspend,
515
+ resumeData
522
516
  });
523
- }
517
+ },
518
+ component: "TOOL"
524
519
  };
525
520
  }
526
521
  return {
@@ -545,7 +540,8 @@ function init(inngest) {
545
540
  description: step.description,
546
541
  inputSchema: step.inputSchema,
547
542
  outputSchema: step.outputSchema,
548
- execute: step.execute
543
+ execute: step.execute,
544
+ component: step.component
549
545
  };
550
546
  },
551
547
  cloneWorkflow(workflow, opts) {
@@ -565,19 +561,19 @@ function init(inngest) {
565
561
  var InngestExecutionEngine = class extends DefaultExecutionEngine {
566
562
  inngestStep;
567
563
  inngestAttempts;
568
- constructor(mastra, inngestStep, inngestAttempts = 0) {
569
- super({ mastra });
564
+ constructor(mastra, inngestStep, inngestAttempts = 0, options) {
565
+ super({ mastra, options });
570
566
  this.inngestStep = inngestStep;
571
567
  this.inngestAttempts = inngestAttempts;
572
568
  }
573
569
  async execute(params) {
574
570
  await params.emitter.emit("watch-v2", {
575
- type: "start",
571
+ type: "workflow-start",
576
572
  payload: { runId: params.runId }
577
573
  });
578
574
  const result = await super.execute(params);
579
575
  await params.emitter.emit("watch-v2", {
580
- type: "finish",
576
+ type: "workflow-finish",
581
577
  payload: { runId: params.runId }
582
578
  });
583
579
  return result;
@@ -639,33 +635,6 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
639
635
  executionSpan?.end();
640
636
  return base;
641
637
  }
642
- async superExecuteStep({
643
- workflowId,
644
- runId,
645
- step,
646
- stepResults,
647
- executionContext,
648
- resume,
649
- prevOutput,
650
- emitter,
651
- abortController,
652
- runtimeContext,
653
- writableStream
654
- }) {
655
- return super.executeStep({
656
- workflowId,
657
- runId,
658
- step,
659
- stepResults,
660
- executionContext,
661
- resume,
662
- prevOutput,
663
- emitter,
664
- abortController,
665
- runtimeContext,
666
- writableStream
667
- });
668
- }
669
638
  // async executeSleep({ id, duration }: { id: string; duration: number }): Promise<void> {
670
639
  // await this.inngestStep.sleep(id, duration);
671
640
  // }
@@ -678,9 +647,20 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
678
647
  emitter,
679
648
  abortController,
680
649
  runtimeContext,
681
- writableStream
650
+ executionContext,
651
+ writableStream,
652
+ tracingContext
682
653
  }) {
683
654
  let { duration, fn } = entry;
655
+ const sleepSpan = tracingContext?.currentSpan?.createChildSpan({
656
+ type: AISpanType.WORKFLOW_SLEEP,
657
+ name: `sleep: ${duration ? `${duration}ms` : "dynamic"}`,
658
+ attributes: {
659
+ durationMs: duration,
660
+ sleepType: fn ? "dynamic" : "fixed"
661
+ },
662
+ tracingPolicy: this.options?.tracingPolicy
663
+ });
684
664
  if (fn) {
685
665
  const stepCallId = randomUUID();
686
666
  duration = await this.inngestStep.run(`workflow.${workflowId}.sleep.${entry.id}`, async () => {
@@ -691,17 +671,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
691
671
  runtimeContext,
692
672
  inputData: prevOutput,
693
673
  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;
674
+ tracingContext: {
675
+ currentSpan: sleepSpan
704
676
  },
677
+ getInitData: () => stepResults?.input,
678
+ getStepResult: getStepResult.bind(this, stepResults),
705
679
  // TODO: this function shouldn't have suspend probably?
706
680
  suspend: async (_suspendPayload) => {
707
681
  },
@@ -711,11 +685,13 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
711
685
  abortController?.abort();
712
686
  },
713
687
  [EMITTER_SYMBOL]: emitter,
688
+ // TODO: add streamVNext support
689
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
714
690
  engine: { step: this.inngestStep },
715
691
  abortSignal: abortController?.signal,
716
692
  writer: new ToolStream(
717
693
  {
718
- prefix: "step",
694
+ prefix: "workflow-step",
719
695
  callId: stepCallId,
720
696
  name: "sleep",
721
697
  runId
@@ -724,8 +700,19 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
724
700
  )
725
701
  });
726
702
  });
703
+ sleepSpan?.update({
704
+ attributes: {
705
+ durationMs: duration
706
+ }
707
+ });
708
+ }
709
+ try {
710
+ await this.inngestStep.sleep(entry.id, !duration || duration < 0 ? 0 : duration);
711
+ sleepSpan?.end();
712
+ } catch (e) {
713
+ sleepSpan?.error({ error: e });
714
+ throw e;
727
715
  }
728
- await this.inngestStep.sleep(entry.id, !duration || duration < 0 ? 0 : duration);
729
716
  }
730
717
  async executeSleepUntil({
731
718
  workflowId,
@@ -736,9 +723,21 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
736
723
  emitter,
737
724
  abortController,
738
725
  runtimeContext,
739
- writableStream
726
+ executionContext,
727
+ writableStream,
728
+ tracingContext
740
729
  }) {
741
730
  let { date, fn } = entry;
731
+ const sleepUntilSpan = tracingContext?.currentSpan?.createChildSpan({
732
+ type: AISpanType.WORKFLOW_SLEEP,
733
+ name: `sleepUntil: ${date ? date.toISOString() : "dynamic"}`,
734
+ attributes: {
735
+ untilDate: date,
736
+ durationMs: date ? Math.max(0, date.getTime() - Date.now()) : void 0,
737
+ sleepType: fn ? "dynamic" : "fixed"
738
+ },
739
+ tracingPolicy: this.options?.tracingPolicy
740
+ });
742
741
  if (fn) {
743
742
  date = await this.inngestStep.run(`workflow.${workflowId}.sleepUntil.${entry.id}`, async () => {
744
743
  const stepCallId = randomUUID();
@@ -749,17 +748,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
749
748
  runtimeContext,
750
749
  inputData: prevOutput,
751
750
  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;
751
+ tracingContext: {
752
+ currentSpan: sleepUntilSpan
762
753
  },
754
+ getInitData: () => stepResults?.input,
755
+ getStepResult: getStepResult.bind(this, stepResults),
763
756
  // TODO: this function shouldn't have suspend probably?
764
757
  suspend: async (_suspendPayload) => {
765
758
  },
@@ -769,11 +762,13 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
769
762
  abortController?.abort();
770
763
  },
771
764
  [EMITTER_SYMBOL]: emitter,
765
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
766
+ // TODO: add streamVNext support
772
767
  engine: { step: this.inngestStep },
773
768
  abortSignal: abortController?.signal,
774
769
  writer: new ToolStream(
775
770
  {
776
- prefix: "step",
771
+ prefix: "workflow-step",
777
772
  callId: stepCallId,
778
773
  name: "sleep",
779
774
  runId
@@ -782,11 +777,27 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
782
777
  )
783
778
  });
784
779
  });
780
+ if (date && !(date instanceof Date)) {
781
+ date = new Date(date);
782
+ }
783
+ const time = !date ? 0 : date.getTime() - Date.now();
784
+ sleepUntilSpan?.update({
785
+ attributes: {
786
+ durationMs: Math.max(0, time)
787
+ }
788
+ });
785
789
  }
786
790
  if (!(date instanceof Date)) {
791
+ sleepUntilSpan?.end();
787
792
  return;
788
793
  }
789
- await this.inngestStep.sleepUntil(entry.id, date);
794
+ try {
795
+ await this.inngestStep.sleepUntil(entry.id, date);
796
+ sleepUntilSpan?.end();
797
+ } catch (e) {
798
+ sleepUntilSpan?.error({ error: e });
799
+ throw e;
800
+ }
790
801
  }
791
802
  async executeWaitForEvent({ event, timeout }) {
792
803
  const eventData = await this.inngestStep.waitForEvent(`user-event-${event}`, {
@@ -807,8 +818,24 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
807
818
  emitter,
808
819
  abortController,
809
820
  runtimeContext,
810
- writableStream
821
+ tracingContext,
822
+ writableStream,
823
+ disableScorers
811
824
  }) {
825
+ const stepAISpan = tracingContext?.currentSpan?.createChildSpan({
826
+ name: `workflow step: '${step.id}'`,
827
+ type: AISpanType.WORKFLOW_STEP,
828
+ input: prevOutput,
829
+ attributes: {
830
+ stepId: step.id
831
+ },
832
+ tracingPolicy: this.options?.tracingPolicy
833
+ });
834
+ const { inputData, validationError } = await validateStepInput({
835
+ prevOutput,
836
+ step,
837
+ validateInputs: this.options?.validateInputs ?? false
838
+ });
812
839
  const startedAt = await this.inngestStep.run(
813
840
  `workflow.${executionContext.workflowId}.run.${executionContext.runId}.step.${step.id}.running_ev`,
814
841
  async () => {
@@ -835,11 +862,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
835
862
  eventTimestamp: Date.now()
836
863
  });
837
864
  await emitter.emit("watch-v2", {
838
- type: "step-start",
865
+ type: "workflow-step-start",
839
866
  payload: {
840
867
  id: step.id,
841
868
  status: "running",
842
- payload: prevOutput,
869
+ payload: inputData,
843
870
  startedAt: startedAt2
844
871
  }
845
872
  });
@@ -859,7 +886,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
859
886
  const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
860
887
  function: step.getFunction(),
861
888
  data: {
862
- inputData: prevOutput,
889
+ inputData,
863
890
  runId,
864
891
  resume: {
865
892
  runId,
@@ -877,7 +904,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
877
904
  const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
878
905
  function: step.getFunction(),
879
906
  data: {
880
- inputData: prevOutput
907
+ inputData
881
908
  }
882
909
  });
883
910
  result = invokeResp.result;
@@ -905,7 +932,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
905
932
  eventTimestamp: Date.now()
906
933
  });
907
934
  await emitter.emit("watch-v2", {
908
- type: "step-result",
935
+ type: "workflow-step-result",
909
936
  payload: {
910
937
  id: step.id,
911
938
  status: "failed",
@@ -940,7 +967,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
940
967
  eventTimestamp: Date.now()
941
968
  });
942
969
  await emitter.emit("watch-v2", {
943
- type: "step-suspended",
970
+ type: "workflow-step-suspended",
944
971
  payload: {
945
972
  id: step.id,
946
973
  status: "suspended"
@@ -997,7 +1024,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
997
1024
  eventTimestamp: Date.now()
998
1025
  });
999
1026
  await emitter.emit("watch-v2", {
1000
- type: "step-result",
1027
+ type: "workflow-step-result",
1001
1028
  payload: {
1002
1029
  id: step.id,
1003
1030
  status: "success",
@@ -1005,7 +1032,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1005
1032
  }
1006
1033
  });
1007
1034
  await emitter.emit("watch-v2", {
1008
- type: "step-finish",
1035
+ type: "workflow-step-finish",
1009
1036
  payload: {
1010
1037
  id: step.id,
1011
1038
  metadata: {}
@@ -1022,21 +1049,21 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1022
1049
  let suspended;
1023
1050
  let bailed;
1024
1051
  try {
1052
+ if (validationError) {
1053
+ throw validationError;
1054
+ }
1025
1055
  const result = await step.execute({
1026
1056
  runId: executionContext.runId,
1027
1057
  mastra: this.mastra,
1028
1058
  runtimeContext,
1029
1059
  writableStream,
1030
- inputData: prevOutput,
1060
+ inputData,
1031
1061
  resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
1032
- getInitData: () => stepResults?.input,
1033
- getStepResult: (step2) => {
1034
- const result2 = stepResults[step2.id];
1035
- if (result2?.status === "success") {
1036
- return result2.output;
1037
- }
1038
- return null;
1062
+ tracingContext: {
1063
+ currentSpan: stepAISpan
1039
1064
  },
1065
+ getInitData: () => stepResults?.input,
1066
+ getStepResult: getStepResult.bind(this, stepResults),
1040
1067
  suspend: async (suspendPayload) => {
1041
1068
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1042
1069
  suspended = { payload: suspendPayload };
@@ -1062,14 +1089,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1062
1089
  output: result,
1063
1090
  startedAt,
1064
1091
  endedAt,
1065
- payload: prevOutput,
1092
+ payload: inputData,
1066
1093
  resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1067
1094
  resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1068
1095
  };
1069
1096
  } catch (e) {
1070
1097
  execResults = {
1071
1098
  status: "failed",
1072
- payload: prevOutput,
1099
+ payload: inputData,
1073
1100
  error: e instanceof Error ? e.message : String(e),
1074
1101
  endedAt: Date.now(),
1075
1102
  startedAt,
@@ -1081,18 +1108,20 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1081
1108
  execResults = {
1082
1109
  status: "suspended",
1083
1110
  suspendedPayload: suspended.payload,
1084
- payload: prevOutput,
1111
+ payload: inputData,
1085
1112
  suspendedAt: Date.now(),
1086
1113
  startedAt,
1087
1114
  resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1088
1115
  resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1089
1116
  };
1090
1117
  } else if (bailed) {
1091
- execResults = { status: "bailed", output: bailed.payload, payload: prevOutput, endedAt: Date.now(), startedAt };
1118
+ execResults = { status: "bailed", output: bailed.payload, payload: inputData, endedAt: Date.now(), startedAt };
1092
1119
  }
1093
1120
  if (execResults.status === "failed") {
1094
1121
  if (executionContext.retryConfig.attempts > 0 && this.inngestAttempts < executionContext.retryConfig.attempts) {
1095
- throw execResults.error;
1122
+ const error = new Error(execResults.error);
1123
+ stepAISpan?.error({ error });
1124
+ throw error;
1096
1125
  }
1097
1126
  }
1098
1127
  await emitter.emit("watch", {
@@ -1113,7 +1142,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1113
1142
  });
1114
1143
  if (execResults.status === "suspended") {
1115
1144
  await emitter.emit("watch-v2", {
1116
- type: "step-suspended",
1145
+ type: "workflow-step-suspended",
1117
1146
  payload: {
1118
1147
  id: step.id,
1119
1148
  ...execResults
@@ -1121,22 +1150,40 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1121
1150
  });
1122
1151
  } else {
1123
1152
  await emitter.emit("watch-v2", {
1124
- type: "step-result",
1153
+ type: "workflow-step-result",
1125
1154
  payload: {
1126
1155
  id: step.id,
1127
1156
  ...execResults
1128
1157
  }
1129
1158
  });
1130
1159
  await emitter.emit("watch-v2", {
1131
- type: "step-finish",
1160
+ type: "workflow-step-finish",
1132
1161
  payload: {
1133
1162
  id: step.id,
1134
1163
  metadata: {}
1135
1164
  }
1136
1165
  });
1137
1166
  }
1167
+ stepAISpan?.end({ output: execResults });
1138
1168
  return { result: execResults, executionContext, stepResults };
1139
1169
  });
1170
+ if (disableScorers !== false) {
1171
+ await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}.score`, async () => {
1172
+ if (step.scorers) {
1173
+ await this.runScorers({
1174
+ scorers: step.scorers,
1175
+ runId: executionContext.runId,
1176
+ input: inputData,
1177
+ output: stepRes.result,
1178
+ workflowId: executionContext.workflowId,
1179
+ stepId: step.id,
1180
+ runtimeContext,
1181
+ disableScorers,
1182
+ tracingContext: { currentSpan: stepAISpan }
1183
+ });
1184
+ }
1185
+ });
1186
+ }
1140
1187
  Object.assign(executionContext.suspendedPaths, stepRes.executionContext.suspendedPaths);
1141
1188
  Object.assign(stepResults, stepRes.stepResults);
1142
1189
  return stepRes.result;
@@ -1145,6 +1192,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1145
1192
  workflowId,
1146
1193
  runId,
1147
1194
  stepResults,
1195
+ resourceId,
1148
1196
  executionContext,
1149
1197
  serializedStepGraph,
1150
1198
  workflowStatus,
@@ -1157,12 +1205,14 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1157
1205
  await this.mastra?.getStorage()?.persistWorkflowSnapshot({
1158
1206
  workflowName: workflowId,
1159
1207
  runId,
1208
+ resourceId,
1160
1209
  snapshot: {
1161
1210
  runId,
1162
1211
  value: {},
1163
1212
  context: stepResults,
1164
1213
  activePaths: [],
1165
1214
  suspendedPaths: executionContext.suspendedPaths,
1215
+ waitingPaths: {},
1166
1216
  serializedStepGraph,
1167
1217
  status: workflowStatus,
1168
1218
  result,
@@ -1187,12 +1237,32 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1187
1237
  emitter,
1188
1238
  abortController,
1189
1239
  runtimeContext,
1190
- writableStream
1240
+ writableStream,
1241
+ disableScorers,
1242
+ tracingContext
1191
1243
  }) {
1244
+ const conditionalSpan = tracingContext?.currentSpan?.createChildSpan({
1245
+ type: AISpanType.WORKFLOW_CONDITIONAL,
1246
+ name: `conditional: '${entry.conditions.length} conditions'`,
1247
+ input: prevOutput,
1248
+ attributes: {
1249
+ conditionCount: entry.conditions.length
1250
+ },
1251
+ tracingPolicy: this.options?.tracingPolicy
1252
+ });
1192
1253
  let execResults;
1193
1254
  const truthyIndexes = (await Promise.all(
1194
1255
  entry.conditions.map(
1195
1256
  (cond, index) => this.inngestStep.run(`workflow.${workflowId}.conditional.${index}`, async () => {
1257
+ const evalSpan = conditionalSpan?.createChildSpan({
1258
+ type: AISpanType.WORKFLOW_CONDITIONAL_EVAL,
1259
+ name: `condition: '${index}'`,
1260
+ input: prevOutput,
1261
+ attributes: {
1262
+ conditionIndex: index
1263
+ },
1264
+ tracingPolicy: this.options?.tracingPolicy
1265
+ });
1196
1266
  try {
1197
1267
  const result = await cond({
1198
1268
  runId,
@@ -1201,17 +1271,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1201
1271
  runtimeContext,
1202
1272
  runCount: -1,
1203
1273
  inputData: prevOutput,
1204
- getInitData: () => stepResults?.input,
1205
- getStepResult: (step) => {
1206
- if (!step?.id) {
1207
- return null;
1208
- }
1209
- const result2 = stepResults[step.id];
1210
- if (result2?.status === "success") {
1211
- return result2.output;
1212
- }
1213
- return null;
1274
+ tracingContext: {
1275
+ currentSpan: evalSpan
1214
1276
  },
1277
+ getInitData: () => stepResults?.input,
1278
+ getStepResult: getStepResult.bind(this, stepResults),
1215
1279
  // TODO: this function shouldn't have suspend probably?
1216
1280
  suspend: async (_suspendPayload) => {
1217
1281
  },
@@ -1221,13 +1285,15 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1221
1285
  abortController.abort();
1222
1286
  },
1223
1287
  [EMITTER_SYMBOL]: emitter,
1288
+ [STREAM_FORMAT_SYMBOL]: executionContext.format,
1289
+ // TODO: add streamVNext support
1224
1290
  engine: {
1225
1291
  step: this.inngestStep
1226
1292
  },
1227
1293
  abortSignal: abortController.signal,
1228
1294
  writer: new ToolStream(
1229
1295
  {
1230
- prefix: "step",
1296
+ prefix: "workflow-step",
1231
1297
  callId: randomUUID(),
1232
1298
  name: "conditional",
1233
1299
  runId
@@ -1235,24 +1301,42 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1235
1301
  writableStream
1236
1302
  )
1237
1303
  });
1304
+ evalSpan?.end({
1305
+ output: result,
1306
+ attributes: {
1307
+ result: !!result
1308
+ }
1309
+ });
1238
1310
  return result ? index : null;
1239
1311
  } catch (e) {
1312
+ evalSpan?.error({
1313
+ error: e instanceof Error ? e : new Error(String(e)),
1314
+ attributes: {
1315
+ result: false
1316
+ }
1317
+ });
1240
1318
  return null;
1241
1319
  }
1242
1320
  })
1243
1321
  )
1244
1322
  )).filter((index) => index !== null);
1245
1323
  const stepsToRun = entry.steps.filter((_, index) => truthyIndexes.includes(index));
1324
+ conditionalSpan?.update({
1325
+ attributes: {
1326
+ truthyIndexes,
1327
+ selectedSteps: stepsToRun.map((s) => s.type === "step" ? s.step.id : `control-${s.type}`)
1328
+ }
1329
+ });
1246
1330
  const results = await Promise.all(
1247
1331
  stepsToRun.map(
1248
1332
  (step, index) => this.executeEntry({
1249
1333
  workflowId,
1250
1334
  runId,
1251
1335
  entry: step,
1336
+ serializedStepGraph,
1252
1337
  prevStep,
1253
1338
  stepResults,
1254
1339
  resume,
1255
- serializedStepGraph,
1256
1340
  executionContext: {
1257
1341
  workflowId,
1258
1342
  runId,
@@ -1264,7 +1348,11 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1264
1348
  emitter,
1265
1349
  abortController,
1266
1350
  runtimeContext,
1267
- writableStream
1351
+ writableStream,
1352
+ disableScorers,
1353
+ tracingContext: {
1354
+ currentSpan: conditionalSpan
1355
+ }
1268
1356
  })
1269
1357
  )
1270
1358
  );
@@ -1285,6 +1373,15 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
1285
1373
  }, {})
1286
1374
  };
1287
1375
  }
1376
+ if (execResults.status === "failed") {
1377
+ conditionalSpan?.error({
1378
+ error: new Error(execResults.error)
1379
+ });
1380
+ } else {
1381
+ conditionalSpan?.end({
1382
+ output: execResults.output || execResults
1383
+ });
1384
+ }
1288
1385
  return execResults;
1289
1386
  }
1290
1387
  };