@mastra/inngest 0.0.0-fix-generate-title-20250616171351 → 0.0.0-fix-fetching-workflow-snapshots-20250625000954

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.cjs CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  var crypto = require('crypto');
4
4
  var realtime = require('@inngest/realtime');
5
- var core = require('@mastra/core');
6
5
  var di = require('@mastra/core/di');
6
+ var tools = require('@mastra/core/tools');
7
7
  var workflows = require('@mastra/core/workflows');
8
8
  var _constants = require('@mastra/core/workflows/_constants');
9
9
  var hono = require('inngest/hono');
@@ -45,7 +45,7 @@ var InngestRun = class extends workflows.Run {
45
45
  }
46
46
  async getRunOutput(eventId) {
47
47
  let runs = await this.getRuns(eventId);
48
- while (runs?.[0]?.status !== "Completed") {
48
+ while (runs?.[0]?.status !== "Completed" || runs?.[0]?.event_id !== eventId) {
49
49
  await new Promise((resolve) => setTimeout(resolve, 1e3));
50
50
  runs = await this.getRuns(eventId);
51
51
  if (runs?.[0]?.status === "Failed" || runs?.[0]?.status === "Cancelled") {
@@ -54,6 +54,12 @@ var InngestRun = class extends workflows.Run {
54
54
  }
55
55
  return runs?.[0];
56
56
  }
57
+ async sendEvent(event, data) {
58
+ await this.inngest.send({
59
+ name: `user-event-${event}`,
60
+ data
61
+ });
62
+ }
57
63
  async start({
58
64
  inputData
59
65
  }) {
@@ -91,6 +97,17 @@ var InngestRun = class extends workflows.Run {
91
97
  return result;
92
98
  }
93
99
  async resume(params) {
100
+ const p = this._resume(params).then((result) => {
101
+ if (result.status !== "suspended") {
102
+ this.closeStreamAction?.().catch(() => {
103
+ });
104
+ }
105
+ return result;
106
+ });
107
+ this.executionResults = p;
108
+ return p;
109
+ }
110
+ async _resume(params) {
94
111
  const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
95
112
  (step) => typeof step === "string" ? step : step?.id
96
113
  );
@@ -124,25 +141,60 @@ var InngestRun = class extends workflows.Run {
124
141
  }
125
142
  return result;
126
143
  }
127
- watch(cb) {
144
+ watch(cb, type = "watch") {
145
+ let active = true;
128
146
  const streamPromise = realtime.subscribe(
129
147
  {
130
148
  channel: `workflow:${this.workflowId}:${this.runId}`,
131
- topics: ["watch"],
149
+ topics: [type],
132
150
  app: this.inngest
133
151
  },
134
152
  (message) => {
135
- cb(message.data);
153
+ if (active) {
154
+ cb(message.data);
155
+ }
136
156
  }
137
157
  );
138
158
  return () => {
139
- streamPromise.then((stream) => {
140
- stream.cancel();
159
+ active = false;
160
+ streamPromise.then(async (stream) => {
161
+ return stream.cancel();
141
162
  }).catch((err) => {
142
163
  console.error(err);
143
164
  });
144
165
  };
145
166
  }
167
+ stream({ inputData, runtimeContext } = {}) {
168
+ const { readable, writable } = new TransformStream();
169
+ const writer = writable.getWriter();
170
+ const unwatch = this.watch(async (event) => {
171
+ try {
172
+ await writer.write(event);
173
+ } catch {
174
+ }
175
+ }, "watch-v2");
176
+ this.closeStreamAction = async () => {
177
+ unwatch();
178
+ try {
179
+ await writer.close();
180
+ } catch (err) {
181
+ console.error("Error closing stream:", err);
182
+ } finally {
183
+ writer.releaseLock();
184
+ }
185
+ };
186
+ this.executionResults = this.start({ inputData, runtimeContext }).then((result) => {
187
+ if (result.status !== "suspended") {
188
+ this.closeStreamAction?.().catch(() => {
189
+ });
190
+ }
191
+ return result;
192
+ });
193
+ return {
194
+ stream: readable,
195
+ getWorkflowState: () => this.executionResults
196
+ };
197
+ }
146
198
  };
147
199
  var InngestWorkflow = class _InngestWorkflow extends workflows.Workflow {
148
200
  #mastra;
@@ -227,6 +279,41 @@ var InngestWorkflow = class _InngestWorkflow extends workflows.Workflow {
227
279
  this.runs.set(runIdToUse, run);
228
280
  return run;
229
281
  }
282
+ async createRunAsync(options) {
283
+ const runIdToUse = options?.runId || crypto.randomUUID();
284
+ const run = this.runs.get(runIdToUse) ?? new InngestRun(
285
+ {
286
+ workflowId: this.id,
287
+ runId: runIdToUse,
288
+ executionEngine: this.executionEngine,
289
+ executionGraph: this.executionGraph,
290
+ serializedStepGraph: this.serializedStepGraph,
291
+ mastra: this.#mastra,
292
+ retryConfig: this.retryConfig,
293
+ cleanup: () => this.runs.delete(runIdToUse)
294
+ },
295
+ this.inngest
296
+ );
297
+ this.runs.set(runIdToUse, run);
298
+ await this.mastra?.getStorage()?.persistWorkflowSnapshot({
299
+ workflowName: this.id,
300
+ runId: runIdToUse,
301
+ snapshot: {
302
+ runId: runIdToUse,
303
+ status: "pending",
304
+ value: {},
305
+ context: {},
306
+ activePaths: [],
307
+ serializedStepGraph: this.serializedStepGraph,
308
+ suspendedPaths: {},
309
+ result: void 0,
310
+ error: void 0,
311
+ // @ts-ignore
312
+ timestamp: Date.now()
313
+ }
314
+ });
315
+ return run;
316
+ }
230
317
  getFunction() {
231
318
  if (this.function) {
232
319
  return this.function;
@@ -250,12 +337,18 @@ var InngestWorkflow = class _InngestWorkflow extends workflows.Workflow {
250
337
  try {
251
338
  await publish({
252
339
  channel: `workflow:${this.id}:${runId}`,
253
- topic: "watch",
340
+ topic: event2,
254
341
  data
255
342
  });
256
343
  } catch (err) {
257
344
  this.logger.error("Error emitting event: " + (err?.stack ?? err?.message ?? err));
258
345
  }
346
+ },
347
+ on: (_event, _callback) => {
348
+ },
349
+ off: (_event, _callback) => {
350
+ },
351
+ once: (_event, _callback) => {
259
352
  }
260
353
  };
261
354
  const engine = new InngestExecutionEngine(this.#mastra, step, attempt);
@@ -293,8 +386,14 @@ var InngestWorkflow = class _InngestWorkflow extends workflows.Workflow {
293
386
  return [this.getFunction(), ...this.getNestedFunctions(this.executionGraph.steps)];
294
387
  }
295
388
  };
389
+ function isAgent(params) {
390
+ return params?.component === "AGENT";
391
+ }
392
+ function isTool(params) {
393
+ return params instanceof tools.Tool;
394
+ }
296
395
  function createStep(params) {
297
- if (params instanceof core.Agent) {
396
+ if (isAgent(params)) {
298
397
  return {
299
398
  id: params.name,
300
399
  // @ts-ignore
@@ -359,7 +458,7 @@ function createStep(params) {
359
458
  }
360
459
  };
361
460
  }
362
- if (params instanceof core.Tool) {
461
+ if (isTool(params)) {
363
462
  if (!params.inputSchema || !params.outputSchema) {
364
463
  throw new Error("Tool must have input and output schemas defined");
365
464
  }
@@ -425,6 +524,18 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
425
524
  this.inngestStep = inngestStep;
426
525
  this.inngestAttempts = inngestAttempts;
427
526
  }
527
+ async execute(params) {
528
+ await params.emitter.emit("watch-v2", {
529
+ type: "start",
530
+ payload: { runId: params.runId }
531
+ });
532
+ const result = await super.execute(params);
533
+ await params.emitter.emit("watch-v2", {
534
+ type: "finish",
535
+ payload: { runId: params.runId }
536
+ });
537
+ return result;
538
+ }
428
539
  async fmtReturnValue(executionSpan, emitter, stepResults, lastOutput, error) {
429
540
  const base = {
430
541
  status: lastOutput.status,
@@ -508,6 +619,16 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
508
619
  async executeSleep({ id, duration }) {
509
620
  await this.inngestStep.sleep(id, duration);
510
621
  }
622
+ async executeWaitForEvent({ event, timeout }) {
623
+ const eventData = await this.inngestStep.waitForEvent(`user-event-${event}`, {
624
+ event: `user-event-${event}`,
625
+ timeout: timeout ?? 5e3
626
+ });
627
+ if (eventData === null) {
628
+ throw "Timeout waiting for event";
629
+ }
630
+ return eventData?.data;
631
+ }
511
632
  async executeStep({
512
633
  step,
513
634
  stepResults,
@@ -517,9 +638,10 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
517
638
  emitter,
518
639
  runtimeContext
519
640
  }) {
520
- await this.inngestStep.run(
641
+ const startedAt = await this.inngestStep.run(
521
642
  `workflow.${executionContext.workflowId}.run.${executionContext.runId}.step.${step.id}.running_ev`,
522
643
  async () => {
644
+ const startedAt2 = Date.now();
523
645
  await emitter.emit("watch", {
524
646
  type: "watch",
525
647
  payload: {
@@ -541,6 +663,13 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
541
663
  },
542
664
  eventTimestamp: Date.now()
543
665
  });
666
+ await emitter.emit("watch-v2", {
667
+ type: "step-start",
668
+ payload: {
669
+ id: step.id
670
+ }
671
+ });
672
+ return startedAt2;
544
673
  }
545
674
  );
546
675
  if (step instanceof InngestWorkflow) {
@@ -601,6 +730,13 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
601
730
  },
602
731
  eventTimestamp: Date.now()
603
732
  });
733
+ await emitter.emit("watch-v2", {
734
+ type: "step-result",
735
+ payload: {
736
+ id: step.id,
737
+ status: "failed"
738
+ }
739
+ });
604
740
  return { executionContext, result: { status: "failed", error: result?.error } };
605
741
  } else if (result.status === "suspended") {
606
742
  const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
@@ -627,6 +763,12 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
627
763
  },
628
764
  eventTimestamp: Date.now()
629
765
  });
766
+ await emitter.emit("watch-v2", {
767
+ type: "step-suspended",
768
+ payload: {
769
+ id: step.id
770
+ }
771
+ });
630
772
  return {
631
773
  executionContext,
632
774
  result: {
@@ -677,6 +819,13 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
677
819
  },
678
820
  eventTimestamp: Date.now()
679
821
  });
822
+ await emitter.emit("watch-v2", {
823
+ type: "step-finish",
824
+ payload: {
825
+ id: step.id,
826
+ metadata: {}
827
+ }
828
+ });
680
829
  return { executionContext, result: { status: "success", output: result?.result } };
681
830
  }
682
831
  );
@@ -686,6 +835,7 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
686
835
  const stepRes = await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}`, async () => {
687
836
  let execResults;
688
837
  let suspended;
838
+ let bailed;
689
839
  try {
690
840
  const result = await step.execute({
691
841
  runId: executionContext.runId,
@@ -705,6 +855,9 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
705
855
  executionContext.suspendedPaths[step.id] = executionContext.executionPath;
706
856
  suspended = { payload: suspendPayload };
707
857
  },
858
+ bail: (result2) => {
859
+ bailed = { payload: result2 };
860
+ },
708
861
  resume: {
709
862
  steps: resume?.steps?.slice(1) || [],
710
863
  resumePayload: resume?.resumePayload,
@@ -716,12 +869,39 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
716
869
  step: this.inngestStep
717
870
  }
718
871
  });
719
- execResults = { status: "success", output: result };
872
+ const endedAt = Date.now();
873
+ execResults = {
874
+ status: "success",
875
+ output: result,
876
+ startedAt,
877
+ endedAt,
878
+ payload: prevOutput,
879
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
880
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
881
+ };
720
882
  } catch (e) {
721
- execResults = { status: "failed", error: e instanceof Error ? e.message : String(e) };
883
+ execResults = {
884
+ status: "failed",
885
+ payload: prevOutput,
886
+ error: e instanceof Error ? e.message : String(e),
887
+ endedAt: Date.now(),
888
+ startedAt,
889
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
890
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
891
+ };
722
892
  }
723
893
  if (suspended) {
724
- execResults = { status: "suspended", payload: suspended.payload };
894
+ execResults = {
895
+ status: "suspended",
896
+ suspendedPayload: suspended.payload,
897
+ payload: prevOutput,
898
+ suspendedAt: Date.now(),
899
+ startedAt,
900
+ resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
901
+ resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
902
+ };
903
+ } else if (bailed) {
904
+ execResults = { status: "bailed", output: bailed.payload, payload: prevOutput, endedAt: Date.now(), startedAt };
725
905
  }
726
906
  if (execResults.status === "failed") {
727
907
  if (executionContext.retryConfig.attempts > 0 && this.inngestAttempts < executionContext.retryConfig.attempts) {
@@ -733,18 +913,43 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
733
913
  payload: {
734
914
  currentStep: {
735
915
  id: step.id,
736
- status: execResults.status,
737
- output: execResults.output
916
+ ...execResults
738
917
  },
739
918
  workflowState: {
740
919
  status: "running",
741
- steps: stepResults,
920
+ steps: { ...stepResults, [step.id]: execResults },
742
921
  result: null,
743
922
  error: null
744
923
  }
745
924
  },
746
925
  eventTimestamp: Date.now()
747
926
  });
927
+ if (execResults.status === "suspended") {
928
+ await emitter.emit("watch-v2", {
929
+ type: "step-suspended",
930
+ payload: {
931
+ id: step.id,
932
+ status: execResults.status,
933
+ output: execResults.status === "success" ? execResults?.output : void 0
934
+ }
935
+ });
936
+ } else {
937
+ await emitter.emit("watch-v2", {
938
+ type: "step-result",
939
+ payload: {
940
+ id: step.id,
941
+ status: execResults.status,
942
+ output: execResults.status === "success" ? execResults?.output : void 0
943
+ }
944
+ });
945
+ await emitter.emit("watch-v2", {
946
+ type: "step-finish",
947
+ payload: {
948
+ id: step.id,
949
+ metadata: {}
950
+ }
951
+ });
952
+ }
748
953
  return { result: execResults, executionContext, stepResults };
749
954
  });
750
955
  Object.assign(executionContext.suspendedPaths, stepRes.executionContext.suspendedPaths);
@@ -821,6 +1026,8 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
821
1026
  // TODO: this function shouldn't have suspend probably?
822
1027
  suspend: async (_suspendPayload) => {
823
1028
  },
1029
+ bail: () => {
1030
+ },
824
1031
  [_constants.EMITTER_SYMBOL]: emitter,
825
1032
  engine: {
826
1033
  step: this.inngestStep
@@ -862,7 +1069,7 @@ var InngestExecutionEngine = class extends workflows.DefaultExecutionEngine {
862
1069
  if (hasFailed) {
863
1070
  execResults = { status: "failed", error: hasFailed.result.error };
864
1071
  } else if (hasSuspended) {
865
- execResults = { status: "suspended", payload: hasSuspended.result.payload };
1072
+ execResults = { status: "suspended", payload: hasSuspended.result.suspendPayload };
866
1073
  } else {
867
1074
  execResults = {
868
1075
  status: "success",