@mastra/temporal 0.5.0 → 0.6.0-alpha.1

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/worker.js CHANGED
@@ -2,13 +2,13 @@ import { t as toWorkflowType } from "./utils-R6cB86BM.js";
2
2
  import { builtinModules } from "module";
3
3
  import { validateStepInput, validateStepRequestContext } from "@mastra/core/workflows";
4
4
  import { RequestContext } from "@mastra/core/di";
5
+ import { MastraError, getErrorFromUnknown } from "@mastra/core/error";
5
6
  import { readFileSync } from "fs";
6
7
  import { writeFile } from "fs/promises";
7
8
  import path, { basename, join } from "path";
8
9
  import { fileURLToPath, pathToFileURL } from "url";
9
- import { MastraError } from "@mastra/core/error";
10
10
  import { toStandardSchema } from "@mastra/core/schema";
11
- import { ApplicationFailure } from "@temporalio/activity";
11
+ import { ApplicationFailure, CancelledFailure } from "@temporalio/activity";
12
12
  import { generate } from "@babel/generator";
13
13
  import { parse } from "@babel/parser";
14
14
  import * as t from "@babel/types";
@@ -403,24 +403,55 @@ function hasLocalMastraBinding(ast) {
403
403
  }
404
404
  function createTemporalActivitiesHelperStatements(mastraImportPath, hasMastraBinding, requestContextClassName) {
405
405
  const helperSource = `
406
- function withRequestContext(params) {
406
+ function withRequestContext(params, args) {
407
407
  const { requestContext, initData, ...rest } = params;
408
+ let suspended;
408
409
  return {
409
410
  ...rest,
410
411
  requestContext: new ${requestContextClassName}(requestContext),
411
412
  getInitData: () => initData,
413
+ suspend: async (suspendPayload, options) => {
414
+ const parsedSuspendPayload = await parseWithSchema(args.suspendSchema, suspendPayload, 'Suspend payload');
415
+ suspended = {
416
+ __temporalSuspension: true,
417
+ suspendPayload: parsedSuspendPayload,
418
+ ...(options?.resumeLabel !== undefined && { resumeLabel: options.resumeLabel }),
419
+ };
420
+ },
421
+ __getTemporalSuspension: () => suspended,
412
422
  };
413
423
  }
414
424
 
425
+ async function parseWithSchema(schema, value, label) {
426
+ if (!schema) return value;
427
+ if (schema['~standard']?.validate) {
428
+ const result = await schema['~standard'].validate(value);
429
+ if ('issues' in result && result.issues?.length) {
430
+ throw new Error(label + ' validation failed: ' + result.issues.map(issue => issue.message).join(', '));
431
+ }
432
+ return result.value;
433
+ }
434
+ if (typeof schema.parseAsync === 'function') return schema.parseAsync(value);
435
+ if (typeof schema.parse === 'function') return schema.parse(value);
436
+ return value;
437
+ }
438
+
439
+ async function executeTemporalStep(args, context) {
440
+ const result = await args.execute(context);
441
+ return context.__getTemporalSuspension() ?? result;
442
+ }
443
+
415
444
  function createStep(args) {
416
445
  return {
417
446
  inputSchema: args.inputSchema,
418
447
  requestContextSchema: args.requestContextSchema,
448
+ suspendSchema: args.suspendSchema,
449
+ resumeSchema: args.resumeSchema,
419
450
  execute: async (params) => {
420
451
  ${mastraImportPath ? `
421
452
  const { mastra } = await import(${JSON.stringify(mastraImportPath)});
422
- return args.execute({ ...withRequestContext(params), mastra });
423
- ` : hasMastraBinding ? "return args.execute({ ...withRequestContext(params), mastra });" : "return args.execute(withRequestContext(params));"}
453
+ return executeTemporalStep(args, { ...withRequestContext(params, args), mastra });
454
+ ` : hasMastraBinding ? "return executeTemporalStep(args, { ...withRequestContext(params, args), mastra });" : "return executeTemporalStep(args, withRequestContext(params, args));"}
424
455
  },
425
456
  };
426
457
  }
@@ -1157,6 +1188,44 @@ function getActivityBindingsPath(outputDir) {
1157
1188
  return path.join(outputDir, ACTIVITY_BINDINGS_FILE_NAME);
1158
1189
  }
1159
1190
  /**
1191
+ * Temporal reduces a thrown error to its class name and message, so the step's own fields go in
1192
+ * the failure's `details` for start() to rebuild the result a local run returns.
1193
+ */
1194
+ function toStepFailureDetails(error) {
1195
+ const serialized = getErrorFromUnknown(error, { serializeStack: false }).toJSON();
1196
+ let details;
1197
+ try {
1198
+ details = JSON.parse(JSON.stringify(serialized));
1199
+ } catch {
1200
+ details = {
1201
+ name: serialized.name,
1202
+ message: serialized.message
1203
+ };
1204
+ }
1205
+ if (error instanceof Error && error.name === "TripWire") {
1206
+ const { options, processorId } = error;
1207
+ return {
1208
+ error: details,
1209
+ tripwire: {
1210
+ reason: error.message,
1211
+ retry: options?.retry,
1212
+ metadata: options?.metadata,
1213
+ processorId
1214
+ }
1215
+ };
1216
+ }
1217
+ return { error: details };
1218
+ }
1219
+ /** Fails as Temporal's own conversion would (same type, message and retries), plus the details. */
1220
+ async function runStep(execute) {
1221
+ try {
1222
+ return await execute();
1223
+ } catch (error) {
1224
+ if (error instanceof ApplicationFailure || error instanceof CancelledFailure) throw error;
1225
+ throw ApplicationFailure.fromError(error, { details: [toStepFailureDetails(error)] });
1226
+ }
1227
+ }
1228
+ /**
1160
1229
  * Activities queued by a Workflow built before `validateInputs` existed carry no flag and run
1161
1230
  * unchecked. A mismatch is non-retryable because a retry gets the same input.
1162
1231
  */
@@ -1179,7 +1248,8 @@ async function checkStepParams(stepId, { inputSchema, requestContextSchema }, {
1179
1248
  type: error instanceof MastraError ? error.id : error.name,
1180
1249
  message: error.message,
1181
1250
  nonRetryable: true,
1182
- cause: error
1251
+ cause: error,
1252
+ details: [toStepFailureDetails(error)]
1183
1253
  });
1184
1254
  return {
1185
1255
  ...params,
@@ -1243,9 +1313,10 @@ var MastraPlugin = class {
1243
1313
  if (generatedActivities[binding.stepId]) continue;
1244
1314
  generatedActivities[binding.stepId] = async (params) => {
1245
1315
  const activity = (await this.#loadCompiledActivitiesModule(compiledActivitiesPath))[binding.exportName];
1246
- if (typeof activity === "function") return activity(params);
1316
+ if (typeof activity === "function") return runStep(() => activity(params));
1247
1317
  if (typeof activity?.execute !== "function") throw new Error(`Unable to load activity '${binding.exportName}' from ${compiledActivitiesPath}`);
1248
- return activity.execute(await checkStepParams(binding.stepId, activity, params));
1318
+ const checkedParams = await checkStepParams(binding.stepId, activity, params);
1319
+ return runStep(() => activity.execute(checkedParams));
1249
1320
  };
1250
1321
  }
1251
1322
  return generatedActivities;