@mastra/server 1.56.0 → 1.57.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.
Files changed (33) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/_types/@internal_voice/dist/_types/@internal_core/dist/request-context/index.d.ts +16 -6
  3. package/dist/_types/@mastra_schema-compat/dist/provider-compats/anthropic.d.ts +1 -0
  4. package/dist/{dist-Epz-mpJn.js → dist-DRyzA92e.js} +10 -3
  5. package/dist/dist-DRyzA92e.js.map +1 -0
  6. package/dist/{dist-CpDWlJbf.cjs → dist-DhFw0bEW.cjs} +10 -3
  7. package/dist/dist-DhFw0bEW.cjs.map +1 -0
  8. package/dist/docs/SKILL.md +1 -1
  9. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  10. package/dist/docs/references/docs-agents-a2a.md +1 -1
  11. package/dist/route-builder-CIk5k35M.js.map +1 -1
  12. package/dist/route-builder-CgLVYL1c.cjs.map +1 -1
  13. package/dist/server/handlers/agent-builder.cjs +1 -1
  14. package/dist/server/handlers/agent-builder.js +1 -1
  15. package/dist/server/handlers/error.cjs +9 -0
  16. package/dist/server/handlers/error.cjs.map +1 -1
  17. package/dist/server/handlers/error.d.ts.map +1 -1
  18. package/dist/server/handlers/error.js +9 -0
  19. package/dist/server/handlers/error.js.map +1 -1
  20. package/dist/server/handlers/workflows.cjs +14 -0
  21. package/dist/server/handlers/workflows.cjs.map +1 -1
  22. package/dist/server/handlers/workflows.d.ts.map +1 -1
  23. package/dist/server/handlers/workflows.js +14 -0
  24. package/dist/server/handlers/workflows.js.map +1 -1
  25. package/dist/server/server-adapter/index.cjs +16 -0
  26. package/dist/server/server-adapter/index.cjs.map +1 -1
  27. package/dist/server/server-adapter/index.d.ts +2 -0
  28. package/dist/server/server-adapter/index.d.ts.map +1 -1
  29. package/dist/server/server-adapter/index.js +17 -1
  30. package/dist/server/server-adapter/index.js.map +1 -1
  31. package/package.json +7 -7
  32. package/dist/dist-CpDWlJbf.cjs.map +0 -1
  33. package/dist/dist-Epz-mpJn.js.map +0 -1
@@ -30,7 +30,7 @@ var agent_builder_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll
30
30
  });
31
31
  let agentBuilderWorkflowsPromise;
32
32
  async function loadAgentBuilderWorkflows() {
33
- agentBuilderWorkflowsPromise ??= Promise.resolve().then(() => require("../../dist-CpDWlJbf.cjs")).then((mod) => mod.agentBuilderWorkflows);
33
+ agentBuilderWorkflowsPromise ??= Promise.resolve().then(() => require("../../dist-DhFw0bEW.cjs")).then((mod) => mod.agentBuilderWorkflows);
34
34
  return agentBuilderWorkflowsPromise;
35
35
  }
36
36
  async function registerAgentBuilderWorkflows(mastra) {
@@ -29,7 +29,7 @@ var agent_builder_exports = /* @__PURE__ */ __exportAll({
29
29
  });
30
30
  let agentBuilderWorkflowsPromise;
31
31
  async function loadAgentBuilderWorkflows() {
32
- agentBuilderWorkflowsPromise ??= import("../../dist-Epz-mpJn.js").then((mod) => mod.agentBuilderWorkflows);
32
+ agentBuilderWorkflowsPromise ??= import("../../dist-DRyzA92e.js").then((mod) => mod.agentBuilderWorkflows);
33
33
  return agentBuilderWorkflowsPromise;
34
34
  }
35
35
  async function registerAgentBuilderWorkflows(mastra) {
@@ -15,6 +15,10 @@ const MODEL_NOT_ALLOWED_CODE = "MODEL_NOT_ALLOWED";
15
15
  function isModelNotAllowedError(error) {
16
16
  return error instanceof Error && error.code === MODEL_NOT_ALLOWED_CODE;
17
17
  }
18
+ const WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE = "WORKFLOW_SCHEMA_VALIDATION_FAILED";
19
+ function isWorkflowSchemaValidationError(error) {
20
+ return error instanceof Error && error.id === WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE;
21
+ }
18
22
  /**
19
23
  * Structural check for ZodError instances.
20
24
  *
@@ -60,6 +64,11 @@ function handleError(error, defaultMessage) {
60
64
  cause: error
61
65
  });
62
66
  }
67
+ if (isWorkflowSchemaValidationError(error)) throw new require_http_exception.HTTPException(400, {
68
+ message: error.message,
69
+ stack: error.stack,
70
+ cause: error
71
+ });
63
72
  const apiError = error;
64
73
  throw new require_http_exception.HTTPException(apiError.status || apiError.details?.status || 500, {
65
74
  message: apiError.message || defaultMessage,
@@ -1 +1 @@
1
- {"version":3,"file":"error.cjs","names":["HTTPException"],"sources":["../../../src/server/handlers/error.ts"],"sourcesContent":["import type { ZodError } from 'zod';\n\nimport { HTTPException } from '../http-exception';\nimport type { StatusCode } from '../http-exception';\nimport type { ApiError } from '../types';\n\n/**\n * Duck-typed interface for ZodError-like objects.\n * Note: Zod v4 uses PropertyKey[] (string | number | symbol) for path.\n */\nexport interface ZodErrorLike {\n issues: Array<{\n path: PropertyKey[];\n message: string;\n }>;\n}\n\n/**\n * Recognition for `ModelNotAllowedError` from `@mastra/core/agent-builder/ee`.\n *\n * Inlined as a duck check rather than imported so that `handleError` (wired\n * into every route) does not force a load-time dependency on the\n * `@mastra/core/agent-builder/ee` subpath. That subpath only ships in\n * `@mastra/core >= 1.34.0`; deploys whose bundled `@mastra/server` resolves\n * against an older core would otherwise crash at startup with\n * `ERR_MODULE_NOT_FOUND` on `@mastra/core/dist/agent-builder/ee/index.js`.\n */\nconst MODEL_NOT_ALLOWED_CODE = 'MODEL_NOT_ALLOWED';\n\ninterface ModelNotAllowedErrorLike extends Error {\n code: typeof MODEL_NOT_ALLOWED_CODE;\n allowed?: unknown;\n attempted?: unknown;\n offendingLabel?: string;\n}\n\nfunction isModelNotAllowedError(error: unknown): error is ModelNotAllowedErrorLike {\n return error instanceof Error && (error as { code?: unknown }).code === MODEL_NOT_ALLOWED_CODE;\n}\n\n/**\n * Structural check for ZodError instances.\n *\n * Avoids `instanceof ZodError` because consumers can resolve `'zod'` to a\n * different package instance (e.g. `zod@^3`) than the one a server adapter is\n * bundled with (`zod@^4`). In that case `instanceof` is false and validation\n * errors fall through to a generic response that drops field-path information.\n *\n * See https://github.com/mastra-ai/mastra/issues/17167.\n */\nexport function isZodError(error: unknown): error is ZodError<any> {\n return (\n !!error &&\n typeof error === 'object' &&\n (error as { name?: unknown }).name === 'ZodError' &&\n Array.isArray((error as { issues?: unknown }).issues)\n );\n}\n\n/**\n * Formats a ZodError into a structured validation error response.\n * Returns an object with an error message and an array of field-specific issues.\n */\nexport function formatZodError(\n error: ZodErrorLike,\n context: string,\n): { error: string; issues: Array<{ field: string; message: string }> } {\n const issues = error.issues.map(e => ({\n field: e.path.length > 0 ? e.path.map(p => String(p)).join('.') : 'root',\n message: e.message,\n }));\n\n return {\n error: `Invalid ${context}`,\n issues,\n };\n}\n\n// Helper to handle errors consistently\nexport function handleError(error: unknown, defaultMessage: string): never {\n if (isModelNotAllowedError(error)) {\n const body = {\n error: {\n code: error.code,\n message: error.message,\n allowed: error.allowed,\n attempted: error.attempted,\n offendingLabel: error.offendingLabel,\n },\n };\n const res = new Response(JSON.stringify(body), {\n status: 422,\n headers: { 'content-type': 'application/json' },\n });\n throw new HTTPException(422, {\n res,\n message: error.message,\n cause: error,\n });\n }\n\n const apiError = error as ApiError;\n\n const apiErrorStatus = apiError.status || apiError.details?.status || 500;\n\n throw new HTTPException(apiErrorStatus as StatusCode, {\n message: apiError.message || defaultMessage,\n stack: apiError.stack,\n cause: apiError.cause,\n });\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAM,yBAAyB;AAS/B,SAAS,uBAAuB,OAAmD;CACjF,OAAO,iBAAiB,SAAU,MAA6B,SAAS;AAC1E;;;;;;;;;;;AAYA,SAAgB,WAAW,OAAwC;CACjE,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YAChB,MAA6B,SAAS,cACvC,MAAM,QAAS,MAA+B,MAAM;AAExD;;;;;AAMA,SAAgB,eACd,OACA,SACsE;CACtE,MAAM,SAAS,MAAM,OAAO,KAAI,OAAM;EACpC,OAAO,EAAE,KAAK,SAAS,IAAI,EAAE,KAAK,KAAI,MAAK,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI;EAClE,SAAS,EAAE;CACb,EAAE;CAEF,OAAO;EACL,OAAO,WAAW;EAClB;CACF;AACF;AAGA,SAAgB,YAAY,OAAgB,gBAA+B;CACzE,IAAI,uBAAuB,KAAK,GAAG;EACjC,MAAM,OAAO,EACX,OAAO;GACL,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,SAAS,MAAM;GACf,WAAW,MAAM;GACjB,gBAAgB,MAAM;EACxB,EACF;EAKA,MAAM,IAAIA,uBAAAA,cAAc,KAAK;GAC3B,KAAA,IALc,SAAS,KAAK,UAAU,IAAI,GAAG;IAC7C,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;GAChD,CAEI;GACF,SAAS,MAAM;GACf,OAAO;EACT,CAAC;CACH;CAEA,MAAM,WAAW;CAIjB,MAAM,IAAIA,uBAAAA,cAFa,SAAS,UAAU,SAAS,SAAS,UAAU,KAEhB;EACpD,SAAS,SAAS,WAAW;EAC7B,OAAO,SAAS;EAChB,OAAO,SAAS;CAClB,CAAC;AACH"}
1
+ {"version":3,"file":"error.cjs","names":["HTTPException"],"sources":["../../../src/server/handlers/error.ts"],"sourcesContent":["import type { ZodError } from 'zod';\n\nimport { HTTPException } from '../http-exception';\nimport type { StatusCode } from '../http-exception';\nimport type { ApiError } from '../types';\n\n/**\n * Duck-typed interface for ZodError-like objects.\n * Note: Zod v4 uses PropertyKey[] (string | number | symbol) for path.\n */\nexport interface ZodErrorLike {\n issues: Array<{\n path: PropertyKey[];\n message: string;\n }>;\n}\n\n/**\n * Recognition for `ModelNotAllowedError` from `@mastra/core/agent-builder/ee`.\n *\n * Inlined as a duck check rather than imported so that `handleError` (wired\n * into every route) does not force a load-time dependency on the\n * `@mastra/core/agent-builder/ee` subpath. That subpath only ships in\n * `@mastra/core >= 1.34.0`; deploys whose bundled `@mastra/server` resolves\n * against an older core would otherwise crash at startup with\n * `ERR_MODULE_NOT_FOUND` on `@mastra/core/dist/agent-builder/ee/index.js`.\n */\nconst MODEL_NOT_ALLOWED_CODE = 'MODEL_NOT_ALLOWED';\n\ninterface ModelNotAllowedErrorLike extends Error {\n code: typeof MODEL_NOT_ALLOWED_CODE;\n allowed?: unknown;\n attempted?: unknown;\n offendingLabel?: string;\n}\n\nfunction isModelNotAllowedError(error: unknown): error is ModelNotAllowedErrorLike {\n return error instanceof Error && (error as { code?: unknown }).code === MODEL_NOT_ALLOWED_CODE;\n}\n\nconst WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE = 'WORKFLOW_SCHEMA_VALIDATION_FAILED';\n\nfunction isWorkflowSchemaValidationError(error: unknown): error is Error {\n return error instanceof Error && (error as { id?: unknown }).id === WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE;\n}\n\n/**\n * Structural check for ZodError instances.\n *\n * Avoids `instanceof ZodError` because consumers can resolve `'zod'` to a\n * different package instance (e.g. `zod@^3`) than the one a server adapter is\n * bundled with (`zod@^4`). In that case `instanceof` is false and validation\n * errors fall through to a generic response that drops field-path information.\n *\n * See https://github.com/mastra-ai/mastra/issues/17167.\n */\nexport function isZodError(error: unknown): error is ZodError<any> {\n return (\n !!error &&\n typeof error === 'object' &&\n (error as { name?: unknown }).name === 'ZodError' &&\n Array.isArray((error as { issues?: unknown }).issues)\n );\n}\n\n/**\n * Formats a ZodError into a structured validation error response.\n * Returns an object with an error message and an array of field-specific issues.\n */\nexport function formatZodError(\n error: ZodErrorLike,\n context: string,\n): { error: string; issues: Array<{ field: string; message: string }> } {\n const issues = error.issues.map(e => ({\n field: e.path.length > 0 ? e.path.map(p => String(p)).join('.') : 'root',\n message: e.message,\n }));\n\n return {\n error: `Invalid ${context}`,\n issues,\n };\n}\n\n// Helper to handle errors consistently\nexport function handleError(error: unknown, defaultMessage: string): never {\n if (isModelNotAllowedError(error)) {\n const body = {\n error: {\n code: error.code,\n message: error.message,\n allowed: error.allowed,\n attempted: error.attempted,\n offendingLabel: error.offendingLabel,\n },\n };\n const res = new Response(JSON.stringify(body), {\n status: 422,\n headers: { 'content-type': 'application/json' },\n });\n throw new HTTPException(422, {\n res,\n message: error.message,\n cause: error,\n });\n }\n\n if (isWorkflowSchemaValidationError(error)) {\n throw new HTTPException(400, {\n message: error.message,\n stack: error.stack,\n cause: error,\n });\n }\n\n const apiError = error as ApiError;\n\n const apiErrorStatus = apiError.status || apiError.details?.status || 500;\n\n throw new HTTPException(apiErrorStatus as StatusCode, {\n message: apiError.message || defaultMessage,\n stack: apiError.stack,\n cause: apiError.cause,\n });\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAM,yBAAyB;AAS/B,SAAS,uBAAuB,OAAmD;CACjF,OAAO,iBAAiB,SAAU,MAA6B,SAAS;AAC1E;AAEA,MAAM,yCAAyC;AAE/C,SAAS,gCAAgC,OAAgC;CACvE,OAAO,iBAAiB,SAAU,MAA2B,OAAO;AACtE;;;;;;;;;;;AAYA,SAAgB,WAAW,OAAwC;CACjE,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YAChB,MAA6B,SAAS,cACvC,MAAM,QAAS,MAA+B,MAAM;AAExD;;;;;AAMA,SAAgB,eACd,OACA,SACsE;CACtE,MAAM,SAAS,MAAM,OAAO,KAAI,OAAM;EACpC,OAAO,EAAE,KAAK,SAAS,IAAI,EAAE,KAAK,KAAI,MAAK,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI;EAClE,SAAS,EAAE;CACb,EAAE;CAEF,OAAO;EACL,OAAO,WAAW;EAClB;CACF;AACF;AAGA,SAAgB,YAAY,OAAgB,gBAA+B;CACzE,IAAI,uBAAuB,KAAK,GAAG;EACjC,MAAM,OAAO,EACX,OAAO;GACL,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,SAAS,MAAM;GACf,WAAW,MAAM;GACjB,gBAAgB,MAAM;EACxB,EACF;EAKA,MAAM,IAAIA,uBAAAA,cAAc,KAAK;GAC3B,KAAA,IALc,SAAS,KAAK,UAAU,IAAI,GAAG;IAC7C,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;GAChD,CAEI;GACF,SAAS,MAAM;GACf,OAAO;EACT,CAAC;CACH;CAEA,IAAI,gCAAgC,KAAK,GACvC,MAAM,IAAIA,uBAAAA,cAAc,KAAK;EAC3B,SAAS,MAAM;EACf,OAAO,MAAM;EACb,OAAO;CACT,CAAC;CAGH,MAAM,WAAW;CAIjB,MAAM,IAAIA,uBAAAA,cAFa,SAAS,UAAU,SAAS,SAAS,UAAU,KAEhB;EACpD,SAAS,SAAS,WAAW;EAC7B,OAAO,SAAS;EAChB,OAAO,SAAS;CAClB,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../../src/server/handlers/error.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC;AAMpC;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,KAAK,CAAC;QACZ,IAAI,EAAE,WAAW,EAAE,CAAC;QACpB,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC,CAAC;CACJ;AAyBD;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAAC,GAAG,CAAC,CAOjE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,MAAM,GACd;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAUtE;AAGD,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,KAAK,CA+BzE"}
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../../src/server/handlers/error.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC;AAMpC;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,KAAK,CAAC;QACZ,IAAI,EAAE,WAAW,EAAE,CAAC;QACpB,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC,CAAC;CACJ;AA+BD;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAAC,GAAG,CAAC,CAOjE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,MAAM,GACd;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAUtE;AAGD,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,KAAK,CAuCzE"}
@@ -14,6 +14,10 @@ const MODEL_NOT_ALLOWED_CODE = "MODEL_NOT_ALLOWED";
14
14
  function isModelNotAllowedError(error) {
15
15
  return error instanceof Error && error.code === MODEL_NOT_ALLOWED_CODE;
16
16
  }
17
+ const WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE = "WORKFLOW_SCHEMA_VALIDATION_FAILED";
18
+ function isWorkflowSchemaValidationError(error) {
19
+ return error instanceof Error && error.id === WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE;
20
+ }
17
21
  /**
18
22
  * Structural check for ZodError instances.
19
23
  *
@@ -59,6 +63,11 @@ function handleError(error, defaultMessage) {
59
63
  cause: error
60
64
  });
61
65
  }
66
+ if (isWorkflowSchemaValidationError(error)) throw new HTTPException(400, {
67
+ message: error.message,
68
+ stack: error.stack,
69
+ cause: error
70
+ });
62
71
  const apiError = error;
63
72
  throw new HTTPException(apiError.status || apiError.details?.status || 500, {
64
73
  message: apiError.message || defaultMessage,
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":[],"sources":["../../../src/server/handlers/error.ts"],"sourcesContent":["import type { ZodError } from 'zod';\n\nimport { HTTPException } from '../http-exception';\nimport type { StatusCode } from '../http-exception';\nimport type { ApiError } from '../types';\n\n/**\n * Duck-typed interface for ZodError-like objects.\n * Note: Zod v4 uses PropertyKey[] (string | number | symbol) for path.\n */\nexport interface ZodErrorLike {\n issues: Array<{\n path: PropertyKey[];\n message: string;\n }>;\n}\n\n/**\n * Recognition for `ModelNotAllowedError` from `@mastra/core/agent-builder/ee`.\n *\n * Inlined as a duck check rather than imported so that `handleError` (wired\n * into every route) does not force a load-time dependency on the\n * `@mastra/core/agent-builder/ee` subpath. That subpath only ships in\n * `@mastra/core >= 1.34.0`; deploys whose bundled `@mastra/server` resolves\n * against an older core would otherwise crash at startup with\n * `ERR_MODULE_NOT_FOUND` on `@mastra/core/dist/agent-builder/ee/index.js`.\n */\nconst MODEL_NOT_ALLOWED_CODE = 'MODEL_NOT_ALLOWED';\n\ninterface ModelNotAllowedErrorLike extends Error {\n code: typeof MODEL_NOT_ALLOWED_CODE;\n allowed?: unknown;\n attempted?: unknown;\n offendingLabel?: string;\n}\n\nfunction isModelNotAllowedError(error: unknown): error is ModelNotAllowedErrorLike {\n return error instanceof Error && (error as { code?: unknown }).code === MODEL_NOT_ALLOWED_CODE;\n}\n\n/**\n * Structural check for ZodError instances.\n *\n * Avoids `instanceof ZodError` because consumers can resolve `'zod'` to a\n * different package instance (e.g. `zod@^3`) than the one a server adapter is\n * bundled with (`zod@^4`). In that case `instanceof` is false and validation\n * errors fall through to a generic response that drops field-path information.\n *\n * See https://github.com/mastra-ai/mastra/issues/17167.\n */\nexport function isZodError(error: unknown): error is ZodError<any> {\n return (\n !!error &&\n typeof error === 'object' &&\n (error as { name?: unknown }).name === 'ZodError' &&\n Array.isArray((error as { issues?: unknown }).issues)\n );\n}\n\n/**\n * Formats a ZodError into a structured validation error response.\n * Returns an object with an error message and an array of field-specific issues.\n */\nexport function formatZodError(\n error: ZodErrorLike,\n context: string,\n): { error: string; issues: Array<{ field: string; message: string }> } {\n const issues = error.issues.map(e => ({\n field: e.path.length > 0 ? e.path.map(p => String(p)).join('.') : 'root',\n message: e.message,\n }));\n\n return {\n error: `Invalid ${context}`,\n issues,\n };\n}\n\n// Helper to handle errors consistently\nexport function handleError(error: unknown, defaultMessage: string): never {\n if (isModelNotAllowedError(error)) {\n const body = {\n error: {\n code: error.code,\n message: error.message,\n allowed: error.allowed,\n attempted: error.attempted,\n offendingLabel: error.offendingLabel,\n },\n };\n const res = new Response(JSON.stringify(body), {\n status: 422,\n headers: { 'content-type': 'application/json' },\n });\n throw new HTTPException(422, {\n res,\n message: error.message,\n cause: error,\n });\n }\n\n const apiError = error as ApiError;\n\n const apiErrorStatus = apiError.status || apiError.details?.status || 500;\n\n throw new HTTPException(apiErrorStatus as StatusCode, {\n message: apiError.message || defaultMessage,\n stack: apiError.stack,\n cause: apiError.cause,\n });\n}\n"],"mappings":";;;;;;;;;;;;AA2BA,MAAM,yBAAyB;AAS/B,SAAS,uBAAuB,OAAmD;CACjF,OAAO,iBAAiB,SAAU,MAA6B,SAAS;AAC1E;;;;;;;;;;;AAYA,SAAgB,WAAW,OAAwC;CACjE,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YAChB,MAA6B,SAAS,cACvC,MAAM,QAAS,MAA+B,MAAM;AAExD;;;;;AAMA,SAAgB,eACd,OACA,SACsE;CACtE,MAAM,SAAS,MAAM,OAAO,KAAI,OAAM;EACpC,OAAO,EAAE,KAAK,SAAS,IAAI,EAAE,KAAK,KAAI,MAAK,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI;EAClE,SAAS,EAAE;CACb,EAAE;CAEF,OAAO;EACL,OAAO,WAAW;EAClB;CACF;AACF;AAGA,SAAgB,YAAY,OAAgB,gBAA+B;CACzE,IAAI,uBAAuB,KAAK,GAAG;EACjC,MAAM,OAAO,EACX,OAAO;GACL,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,SAAS,MAAM;GACf,WAAW,MAAM;GACjB,gBAAgB,MAAM;EACxB,EACF;EAKA,MAAM,IAAI,cAAc,KAAK;GAC3B,KAAA,IALc,SAAS,KAAK,UAAU,IAAI,GAAG;IAC7C,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;GAChD,CAEI;GACF,SAAS,MAAM;GACf,OAAO;EACT,CAAC;CACH;CAEA,MAAM,WAAW;CAIjB,MAAM,IAAI,cAFa,SAAS,UAAU,SAAS,SAAS,UAAU,KAEhB;EACpD,SAAS,SAAS,WAAW;EAC7B,OAAO,SAAS;EAChB,OAAO,SAAS;CAClB,CAAC;AACH"}
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../../src/server/handlers/error.ts"],"sourcesContent":["import type { ZodError } from 'zod';\n\nimport { HTTPException } from '../http-exception';\nimport type { StatusCode } from '../http-exception';\nimport type { ApiError } from '../types';\n\n/**\n * Duck-typed interface for ZodError-like objects.\n * Note: Zod v4 uses PropertyKey[] (string | number | symbol) for path.\n */\nexport interface ZodErrorLike {\n issues: Array<{\n path: PropertyKey[];\n message: string;\n }>;\n}\n\n/**\n * Recognition for `ModelNotAllowedError` from `@mastra/core/agent-builder/ee`.\n *\n * Inlined as a duck check rather than imported so that `handleError` (wired\n * into every route) does not force a load-time dependency on the\n * `@mastra/core/agent-builder/ee` subpath. That subpath only ships in\n * `@mastra/core >= 1.34.0`; deploys whose bundled `@mastra/server` resolves\n * against an older core would otherwise crash at startup with\n * `ERR_MODULE_NOT_FOUND` on `@mastra/core/dist/agent-builder/ee/index.js`.\n */\nconst MODEL_NOT_ALLOWED_CODE = 'MODEL_NOT_ALLOWED';\n\ninterface ModelNotAllowedErrorLike extends Error {\n code: typeof MODEL_NOT_ALLOWED_CODE;\n allowed?: unknown;\n attempted?: unknown;\n offendingLabel?: string;\n}\n\nfunction isModelNotAllowedError(error: unknown): error is ModelNotAllowedErrorLike {\n return error instanceof Error && (error as { code?: unknown }).code === MODEL_NOT_ALLOWED_CODE;\n}\n\nconst WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE = 'WORKFLOW_SCHEMA_VALIDATION_FAILED';\n\nfunction isWorkflowSchemaValidationError(error: unknown): error is Error {\n return error instanceof Error && (error as { id?: unknown }).id === WORKFLOW_SCHEMA_VALIDATION_FAILED_CODE;\n}\n\n/**\n * Structural check for ZodError instances.\n *\n * Avoids `instanceof ZodError` because consumers can resolve `'zod'` to a\n * different package instance (e.g. `zod@^3`) than the one a server adapter is\n * bundled with (`zod@^4`). In that case `instanceof` is false and validation\n * errors fall through to a generic response that drops field-path information.\n *\n * See https://github.com/mastra-ai/mastra/issues/17167.\n */\nexport function isZodError(error: unknown): error is ZodError<any> {\n return (\n !!error &&\n typeof error === 'object' &&\n (error as { name?: unknown }).name === 'ZodError' &&\n Array.isArray((error as { issues?: unknown }).issues)\n );\n}\n\n/**\n * Formats a ZodError into a structured validation error response.\n * Returns an object with an error message and an array of field-specific issues.\n */\nexport function formatZodError(\n error: ZodErrorLike,\n context: string,\n): { error: string; issues: Array<{ field: string; message: string }> } {\n const issues = error.issues.map(e => ({\n field: e.path.length > 0 ? e.path.map(p => String(p)).join('.') : 'root',\n message: e.message,\n }));\n\n return {\n error: `Invalid ${context}`,\n issues,\n };\n}\n\n// Helper to handle errors consistently\nexport function handleError(error: unknown, defaultMessage: string): never {\n if (isModelNotAllowedError(error)) {\n const body = {\n error: {\n code: error.code,\n message: error.message,\n allowed: error.allowed,\n attempted: error.attempted,\n offendingLabel: error.offendingLabel,\n },\n };\n const res = new Response(JSON.stringify(body), {\n status: 422,\n headers: { 'content-type': 'application/json' },\n });\n throw new HTTPException(422, {\n res,\n message: error.message,\n cause: error,\n });\n }\n\n if (isWorkflowSchemaValidationError(error)) {\n throw new HTTPException(400, {\n message: error.message,\n stack: error.stack,\n cause: error,\n });\n }\n\n const apiError = error as ApiError;\n\n const apiErrorStatus = apiError.status || apiError.details?.status || 500;\n\n throw new HTTPException(apiErrorStatus as StatusCode, {\n message: api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EACpD,SAAS,SAAS,WAAW;EAC7B,OAAO,SAAS;EAChB,OAAO,SAAS;CAClB,CAAC;AACH"}
@@ -39,6 +39,18 @@ var workflows_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
39
39
  TIME_TRAVEL_STREAM_WORKFLOW_ROUTE: () => TIME_TRAVEL_STREAM_WORKFLOW_ROUTE,
40
40
  TIME_TRAVEL_WORKFLOW_ROUTE: () => TIME_TRAVEL_WORKFLOW_ROUTE
41
41
  });
42
+ /**
43
+ * Statuses a run cannot come back from. Streaming one of these runIds again would
44
+ * start a fresh execution under the same runId and overwrite its stored snapshot —
45
+ * the in-memory de-dupe that protects concurrent streams only covers runs still held
46
+ * in the workflow's run map, and a finished run has already been dropped from it.
47
+ */
48
+ const TERMINAL_RUN_STATUSES = [
49
+ "success",
50
+ "failed",
51
+ "canceled",
52
+ "tripwire"
53
+ ];
42
54
  async function listWorkflowsFromSystem({ mastra, workflowId }) {
43
55
  const logger = mastra.getLogger();
44
56
  if (!workflowId) throw new require_http_exception.HTTPException(400, { message: "Workflow ID is required" });
@@ -283,6 +295,8 @@ const STREAM_WORKFLOW_ROUTE = require_route_builder.createRoute({
283
295
  workflowId
284
296
  });
285
297
  if (!workflow) throw new require_http_exception.HTTPException(404, { message: "Workflow not found" });
298
+ const existingRun = await workflow.getWorkflowRunById(runId, { withNestedWorkflows: false });
299
+ if (existingRun && TERMINAL_RUN_STATUSES.includes(existingRun.status)) throw new require_http_exception.HTTPException(409, { message: `Workflow run ${runId} already finished with status "${existingRun.status}". Use /observe to read its stream back, or stream a new runId.` });
286
300
  const serverCache = mastra.getServerCache();
287
301
  const result = (await workflow.createRun({
288
302
  runId,
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.cjs","names":["HTTPException","WorkflowRegistry","createRoute","z","listWorkflowsResponseSchema","getWorkflowInfo","MastraFGAPermissions","handleError","workflowIdPathParams","workflowInfoSchema","listWorkflowRunsQuerySchema","workflowRunsResponseSchema","getEffectiveResourceId","workflowRunPathParams","workflowRunResultQuerySchema","workflowRunResultSchema","validateRunOwnership","workflowControlResponseSchema","optionalRunIdSchema","createWorkflowRunBodySchema","createWorkflowRunResponseSchema","runIdSchema","streamWorkflowBodySchema","resumeBodySchema","streamResponseSchema","startAsyncWorkflowBodySchema","workflowExecutionResultSchema","observeWorkflowQuerySchema","restartBodySchema","timeTravelBodySchema"],"sources":["../../../src/server/handlers/workflows.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core';\nimport type { RequestContext } from '@mastra/core/di';\nimport type { Event } from '@mastra/core/events';\nimport { createCachingTransformStream, createReplayStream } from '@mastra/core/stream';\nimport type { WorkflowInfo, ChunkType, StreamEvent, WorkflowStateField } from '@mastra/core/workflows';\nimport { z } from 'zod/v4';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\nimport { streamResponseSchema } from '../schemas/agents';\nimport { optionalRunIdSchema, runIdSchema } from '../schemas/common';\nimport {\n createWorkflowRunBodySchema,\n createWorkflowRunResponseSchema,\n listWorkflowRunsQuerySchema,\n listWorkflowsResponseSchema,\n restartBodySchema,\n timeTravelBodySchema,\n resumeBodySchema,\n startAsyncWorkflowBodySchema,\n streamWorkflowBodySchema,\n workflowControlResponseSchema,\n workflowExecutionResultSchema,\n workflowIdPathParams,\n workflowInfoSchema,\n workflowRunPathParams,\n workflowRunsResponseSchema,\n workflowRunResultQuerySchema,\n workflowRunResultSchema,\n observeWorkflowQuerySchema,\n} from '../schemas/workflows';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport type { Context } from '../types';\nimport { getWorkflowInfo, WorkflowRegistry } from '../utils';\nimport { handleError } from './error';\nimport { getEffectiveResourceId, validateRunOwnership } from './utils';\n\nexport interface WorkflowContext extends Context {\n workflowId?: string;\n runId?: string;\n requestContext?: RequestContext;\n}\n\nasync function listWorkflowsFromSystem({ mastra, workflowId }: WorkflowContext) {\n const logger = mastra.getLogger();\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n let workflow;\n\n // First check registry for temporary workflows\n workflow = WorkflowRegistry.getWorkflow(workflowId);\n\n if (!workflow) {\n try {\n workflow = mastra.getWorkflowById(workflowId);\n } catch (error) {\n logger.debug('Error getting workflow, searching agents for workflow', error);\n }\n }\n\n if (!workflow) {\n logger.debug('Workflow not found, searching agents for workflow', { workflowId });\n const agents = mastra.listAgents();\n\n if (Object.keys(agents || {}).length) {\n for (const [_, agent] of Object.entries(agents)) {\n try {\n const workflows = await agent.listWorkflows();\n\n if (workflows[workflowId]) {\n workflow = workflows[workflowId];\n break;\n }\n } catch (error) {\n logger.debug('Error getting workflow from agent', error);\n }\n }\n }\n }\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n return { workflow };\n}\n\n// ============================================================================\n// Route Definitions (new pattern - handlers defined inline with createRoute)\n// ============================================================================\n\nexport const LIST_WORKFLOWS_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows',\n responseType: 'json',\n queryParamSchema: z.object({\n partial: z.string().optional(),\n }),\n responseSchema: listWorkflowsResponseSchema,\n summary: 'List all workflows',\n description: 'Returns a list of all available workflows in the system',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: (async ({ mastra, partial, requestContext }: any) => {\n try {\n const workflows = mastra.listWorkflows({ serialized: false });\n const isPartial = partial === 'true';\n const _workflows = Object.entries(workflows).reduce<Record<string, WorkflowInfo>>((acc, [key, workflow]) => {\n acc[key] = getWorkflowInfo(workflow as any, isPartial);\n return acc;\n }, {});\n\n // Filter workflows by FGA if configured\n const fgaProvider = mastra.getServer?.()?.fga;\n const user = requestContext?.get('user');\n if (fgaProvider) {\n if (!user) {\n return {};\n }\n const workflowList = Object.entries(_workflows).map(([id, w]) => ({ id, ...w }));\n const accessible = await fgaProvider.filterAccessible(\n user,\n workflowList,\n 'workflow',\n MastraFGAPermissions.WORKFLOWS_READ,\n );\n const accessibleSet = new Set(accessible.map((w: any) => w.id));\n for (const id of Object.keys(_workflows)) {\n if (!accessibleSet.has(id)) {\n delete _workflows[id];\n }\n }\n }\n\n return _workflows;\n } catch (error) {\n return handleError(error, 'Error getting workflows');\n }\n }) as any,\n});\n\nexport const GET_WORKFLOW_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows/:workflowId',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n responseSchema: workflowInfoSchema,\n summary: 'Get workflow by ID',\n description: 'Returns details for a specific workflow',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: (async ({ mastra, workflowId }: any) => {\n try {\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n return getWorkflowInfo(workflow, false);\n } catch (error) {\n return handleError(error, 'Error getting workflow');\n }\n }) as any,\n});\n\nexport const LIST_WORKFLOW_RUNS_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows/:workflowId/runs',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: listWorkflowRunsQuerySchema,\n responseSchema: workflowRunsResponseSchema,\n summary: 'List workflow runs',\n description: 'Returns a paginated list of execution runs for the specified workflow',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({\n mastra,\n workflowId,\n fromDate,\n toDate,\n page,\n perPage,\n limit,\n offset,\n resourceId,\n status,\n requestContext,\n }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n // Support both page/perPage and limit/offset for backwards compatibility\n // If page/perPage provided, use directly; otherwise convert from limit/offset\n let finalPage = page;\n let finalPerPage = perPage;\n\n if (finalPerPage === undefined && limit !== undefined) {\n finalPerPage = limit;\n }\n if (finalPage === undefined && offset !== undefined && finalPerPage !== undefined && finalPerPage > 0) {\n finalPage = Math.floor(offset / finalPerPage);\n }\n\n if (\n finalPerPage !== undefined &&\n (typeof finalPerPage !== 'number' || !Number.isInteger(finalPerPage) || finalPerPage <= 0)\n ) {\n throw new HTTPException(400, { message: 'perPage must be a positive integer' });\n }\n if (finalPage !== undefined && (!Number.isInteger(finalPage) || finalPage < 0)) {\n throw new HTTPException(400, { message: 'page must be a non-negative integer' });\n }\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n const workflowRuns = (await workflow.listWorkflowRuns({\n fromDate: fromDate ? (typeof fromDate === 'string' ? new Date(fromDate) : fromDate) : undefined,\n toDate: toDate ? (typeof toDate === 'string' ? new Date(toDate) : toDate) : undefined,\n perPage: finalPerPage,\n page: finalPage,\n resourceId: effectiveResourceId,\n status,\n })) || {\n runs: [],\n total: 0,\n };\n return workflowRuns;\n } catch (error) {\n return handleError(error, 'Error getting workflow runs');\n }\n },\n});\n\nexport const GET_WORKFLOW_RUN_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows/:workflowId/runs/:runId',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n queryParamSchema: workflowRunResultQuerySchema,\n responseSchema: workflowRunResultSchema,\n summary: 'Get workflow run by ID',\n description:\n 'Returns a workflow run with metadata and processed execution state. Use the fields query parameter to reduce payload size by requesting only specific fields (e.g., ?fields=status,result,metadata)',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, fields, withNestedWorkflows, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'Run ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n // Parse fields parameter (comma-separated string)\n const fieldList = fields ? (fields.split(',').map((f: string) => f.trim()) as WorkflowStateField[]) : undefined;\n\n const run = await workflow.getWorkflowRunById(runId, {\n withNestedWorkflows: withNestedWorkflows !== 'false', // Default to true unless explicitly 'false'\n fields: fieldList,\n });\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n return run;\n } catch (error) {\n return handleError(error, 'Error getting workflow run');\n }\n },\n});\n\nexport const DELETE_WORKFLOW_RUN_BY_ID_ROUTE = createRoute({\n method: 'DELETE',\n path: '/workflows/:workflowId/runs/:runId',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Delete workflow run by ID',\n description: 'Deletes a specific workflow run by ID',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'Run ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n // Validate ownership before deletion\n const run = await workflow.getWorkflowRunById(runId);\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n await validateRunOwnership(run, effectiveResourceId);\n\n await workflow.deleteWorkflowRunById(runId);\n\n return { message: 'Workflow run deleted' };\n } catch (error) {\n return handleError(error, 'Error deleting workflow run');\n }\n },\n});\n\nexport const CREATE_WORKFLOW_RUN_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/create-run',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: optionalRunIdSchema,\n bodySchema: createWorkflowRunBodySchema,\n responseSchema: createWorkflowRunResponseSchema,\n summary: 'Create workflow run',\n description: 'Creates a new workflow execution instance with an optional custom run ID',\n tags: ['Workflows'],\n requiresAuth: true,\n // Creating a run is part of the execute flow (Studio/UI calls this before\n // starting/streaming a workflow), so allow either permission. `write` is kept\n // for back-compat with roles that already grant it.\n requiresPermission: ['workflows:write', 'workflows:execute'],\n handler: async ({ mastra, workflowId, runId, resourceId, disableScorers, requestContext }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.createRun({ runId, resourceId: effectiveResourceId, disableScorers });\n\n return { runId: run.runId };\n } catch (error) {\n return handleError(error, 'Error creating workflow run');\n }\n },\n});\n\nexport const STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/stream',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: streamWorkflowBodySchema,\n summary: 'Stream workflow execution',\n description: 'Executes a workflow and streams the results in real-time',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to stream workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n const serverCache = mastra.getServerCache();\n\n const run = await workflow.createRun({ runId, resourceId: effectiveResourceId });\n const result = run.stream({ ...params, requestContext });\n\n if (serverCache) {\n const { transform } = createCachingTransformStream<ChunkType>({\n cache: serverCache,\n cacheKey: runId,\n });\n return result.fullStream.pipeThrough(transform);\n }\n\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error streaming workflow');\n }\n },\n});\n\nexport const RESUME_STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume-stream',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: streamResponseSchema,\n summary: 'Resume workflow stream',\n description: 'Resumes a suspended workflow execution and continues streaming results',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const serverCache = mastra.getServerCache();\n\n const resumeResult = _run.resumeStream({ ...params, requestContext });\n\n if (serverCache) {\n const { transform } = createCachingTransformStream<ChunkType>({\n cache: serverCache,\n cacheKey: runId,\n });\n return resumeResult.fullStream.pipeThrough(transform);\n }\n\n return resumeResult.fullStream;\n } catch (error) {\n return handleError(error, 'Error resuming workflow');\n }\n },\n});\n\nexport const START_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/start-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: optionalRunIdSchema,\n bodySchema: startAsyncWorkflowBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Start workflow asynchronously',\n description: 'Starts a workflow execution asynchronously without streaming results',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const _run = await workflow.createRun({ runId, resourceId: effectiveResourceId });\n const result = await _run.start({ ...params, requestContext });\n return result;\n } catch (error) {\n return handleError(error, 'Error starting async workflow');\n }\n },\n});\n\nexport const START_WORKFLOW_RUN_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/start',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: startAsyncWorkflowBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Start specific workflow run',\n description: 'Starts execution of a specific workflow run by ID',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to start run' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n void _run.start({\n ...params,\n requestContext,\n });\n\n return { message: 'Workflow run started' };\n } catch (e) {\n return handleError(e, 'Error starting workflow run');\n }\n },\n});\n\nexport const OBSERVE_STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/observe',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: observeWorkflowQuerySchema,\n responseSchema: streamResponseSchema,\n summary: 'Observe workflow stream',\n description:\n 'Observes and streams updates from an already running workflow execution. Supports position-based resume with offset for efficient reconnection.',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, offset, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to observe workflow stream' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const serverCache = mastra.getServerCache();\n if (!serverCache) {\n throw new HTTPException(500, { message: 'Server cache not found' });\n }\n\n // Get cached chunks from the specified index (or 0 if not specified)\n const startIndex = offset ?? 0;\n const cachedRunChunks = (await serverCache.listFromTo(runId, startIndex)) as ChunkType[];\n const liveStream = _run.observeStream();\n\n return createReplayStream<ChunkType>({\n history: cachedRunChunks,\n liveSource: liveStream,\n });\n } catch (error) {\n return handleError(error, 'Error observing workflow stream');\n }\n },\n});\n\nexport const RESUME_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Resume workflow asynchronously',\n description: 'Resumes a suspended workflow execution asynchronously without streaming',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.resume({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error resuming workflow step');\n }\n },\n});\n\n/**\n * Fire-and-forget resume: dispatches the resume and returns immediately with the runId,\n * without waiting for the workflow to complete. For Inngest-backed workflows this avoids\n * the `getRunOutput()` polling race that the awaiting `resume-async` route can hit.\n *\n * TODO(v2): in Mastra v2 this fire-and-forget behavior should become the behavior of the\n * `resume-async` route (and `Run.resumeAsync()`), and this route should be removed. It is\n * kept separate in v1 to avoid a breaking change to the existing `resume-async` response\n * contract (which returns the full workflow result).\n */\nexport const RESUME_NO_WAIT_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume-no-wait',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: createWorkflowRunResponseSchema,\n summary: 'Resume workflow without waiting',\n description:\n 'Resumes a suspended workflow execution without waiting (fire-and-forget) and returns immediately with the runId. The workflow continues executing in the background.',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.resumeAsync({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error resuming workflow step');\n }\n },\n});\n\nexport const RESUME_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Resume workflow',\n description: 'Resumes a suspended workflow execution from a specific step',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n void _run.resume({ ...params, requestContext });\n\n return { message: 'Workflow run resumed' };\n } catch (error) {\n return handleError(error, 'Error resuming workflow');\n }\n },\n});\n\nexport const RESTART_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: restartBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Restart workflow asynchronously',\n description: 'Restarts an active workflow execution asynchronously',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to restart workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.restart({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const RESTART_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: restartBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Restart workflow',\n description: 'Restarts an active workflow execution',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to restart workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n void _run.restart({ ...params, requestContext });\n\n return { message: 'Workflow run restarted' };\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart-all-active-workflow-runs-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Restart all active workflow runs asynchronously',\n description: 'Restarts all active workflow runs asynchronously',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId }) => {\n try {\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n await workflow.restartAllActiveWorkflowRuns();\n\n return { message: 'All active workflow runs restarted' };\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart-all-active-workflow-runs',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Restart all active workflow runs',\n description: 'Restarts all active workflow runs',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId }) => {\n try {\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n void workflow.restartAllActiveWorkflowRuns().catch(error => {\n mastra.getLogger().error('Failed to restart active workflow runs', { error, workflowId });\n });\n\n return { message: 'All active workflow runs restarted' };\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/time-travel-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: timeTravelBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Time travel workflow asynchronously',\n description: 'Time travels a workflow run asynchronously without streaming',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to time travel workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.timeTravel({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error time traveling workflow');\n }\n },\n});\n\nexport const TIME_TRAVEL_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/time-travel',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: timeTravelBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Time travel workflow',\n description: 'Time travels a workflow run, starting from a specific step',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to time travel workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n void _run.timeTravel({ ...params, requestContext });\n\n return { message: 'Workflow run time travel started' };\n } catch (error) {\n return handleError(error, 'Error time traveling workflow');\n }\n },\n});\n\nexport const TIME_TRAVEL_STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/time-travel-stream',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: timeTravelBodySchema,\n summary: 'Time travel workflow stream',\n description: 'Time travels a workflow run, starting from a specific step, and streams the results in real-time',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to time travel workflow stream' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n // Validate ownership of existing run before time traveling\n const existingRun = await workflow.getWorkflowRunById(runId);\n if (!existingRun) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n await validateRunOwnership(existingRun, effectiveResourceId);\n\n const serverCache = mastra.getServerCache();\n\n const run = await workflow.createRun({ runId, resourceId: existingRun.resourceId });\n const result = run.timeTravelStream({ ...params, requestContext });\n\n if (serverCache) {\n const { transform } = createCachingTransformStream<ChunkType>({\n cache: serverCache,\n cacheKey: runId,\n });\n return result.fullStream.pipeThrough(transform);\n }\n\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error time traveling workflow stream');\n }\n },\n});\n\nexport const CANCEL_WORKFLOW_RUN_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/runs/:runId/cancel',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Cancel workflow run',\n description: 'Cancels an in-progress workflow execution',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to cancel workflow run' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n await _run.cancel();\n\n return { message: 'Workflow run cancelled' };\n } catch (error) {\n return handleError(error, 'Error canceling workflow run');\n }\n },\n});\n\n// Legacy routes (deprecated)\nexport const STREAM_LEGACY_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/stream-legacy',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: streamWorkflowBodySchema,\n responseSchema: streamResponseSchema,\n summary: '[DEPRECATED] Stream workflow with legacy format',\n description: 'Legacy endpoint for streaming workflow execution. Use /workflows/:workflowId/stream instead.',\n tags: ['Workflows', 'Legacy'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const serverCache = mastra.getServerCache();\n\n const run = await workflow.createRun({ runId, resourceId: effectiveResourceId });\n const result = run.streamLegacy({\n ...params,\n requestContext,\n onChunk: async chunk => {\n if (serverCache) {\n const cacheKey = runId;\n await serverCache.listPush(cacheKey, chunk);\n }\n },\n });\n\n return result.stream;\n } catch (error) {\n return handleError(error, 'Error executing workflow');\n }\n },\n});\n\nexport const OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/observe-stream-legacy',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n responseSchema: streamResponseSchema,\n summary: '[DEPRECATED] Observe workflow stream with legacy format',\n description: 'Legacy endpoint for observing workflow stream. Use /workflows/:workflowId/observe instead.',\n tags: ['Workflows', 'Legacy'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to observe workflow stream' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const serverCache = mastra.getServerCache();\n if (!serverCache) {\n throw new HTTPException(500, { message: 'Server cache not found' });\n }\n\n // Get cached chunks and create replay stream\n const cachedRunChunks = (await serverCache.listFromTo(runId, 0)) as StreamEvent[];\n const result = _run.observeStreamLegacy();\n\n if (!result.stream) {\n throw new HTTPException(500, { message: 'Failed to create observe stream' });\n }\n\n return createReplayStream<StreamEvent>({\n history: cachedRunChunks,\n liveSource: result.stream,\n });\n } catch (error) {\n return handleError(error, 'Error observing workflow stream');\n }\n },\n});\n\n// ============================================================================\n// Worker Step Execution Endpoint\n// Used by standalone OrchestrationWorker instances with HttpRemoteStrategy.\n// ============================================================================\n\n// `workflowId` and `runId` are taken from path params (single source of\n// truth); they are intentionally omitted from the request body schema.\nconst stepExecutionBodySchema = z.object({\n stepId: z.string(),\n executionPath: z.array(z.number().int().nonnegative()),\n stepResults: z.record(z.string(), z.unknown()),\n state: z.record(z.string(), z.unknown()),\n requestContext: z.record(z.string(), z.unknown()),\n input: z.unknown().optional(),\n resumeData: z.unknown().optional(),\n retryCount: z.number().int().nonnegative().optional(),\n foreachIdx: z.number().int().nonnegative().optional(),\n format: z.enum(['legacy', 'vnext']).optional(),\n perStep: z.boolean().optional(),\n validateInputs: z.boolean().optional(),\n});\n\ntype StepExecutionBody = z.infer<typeof stepExecutionBodySchema>;\n\ninterface StepExecutionHandlerArgs extends StepExecutionBody {\n mastra: Mastra;\n workflowId: string;\n runId: string;\n}\n\n// Reuse the InProcessStrategy across requests for a given Mastra instance.\n// The strategy is stateless beyond its mastra reference, but allocating it\n// per request triggers a dynamic import on the hot path.\n//\n// The dynamic import is required by `pnpm --filter ./packages/server\n// check:core-imports`: `@mastra/core/worker` is a new subpath that older\n// peer-dep floors don't expose, so a static import would fail the check.\n// Once the floor is bumped, this can become a static import.\ntype StepStrategy = { executeStep: (p: unknown) => Promise<unknown> };\nconst strategyByMastra = new WeakMap<Mastra, StepStrategy>();\n\nasync function getStepStrategy(mastra: Mastra): Promise<StepStrategy> {\n let cached = strategyByMastra.get(mastra);\n if (!cached) {\n const { InProcessStrategy } = await import('@mastra/core/worker');\n cached = new InProcessStrategy({ mastra }) as unknown as StepStrategy;\n strategyByMastra.set(mastra, cached);\n }\n return cached;\n}\n\n// Step execution returns the worker's StepResult. Its shape is dynamic\n// and depends on the step's output schema.\nconst stepExecutionResponseSchema = z.unknown();\n\nexport const EXECUTE_WORKFLOW_STEP_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/runs/:runId/steps/execute',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n bodySchema: stepExecutionBodySchema,\n responseSchema: stepExecutionResponseSchema,\n summary: 'Execute a workflow step',\n description:\n 'Internal endpoint used by standalone OrchestrationWorker instances to execute workflow steps remotely via HttpRemoteStrategy.',\n tags: ['Workflows', 'Worker'],\n requiresAuth: true,\n handler: (async ({ mastra, workflowId, runId, ...body }: StepExecutionHandlerArgs) => {\n try {\n // Auth is enforced by the framework via `requiresAuth: true` and the\n // deployer's `authenticateToken` provider. Note that when NO auth\n // provider is configured, the framework currently treats the route\n // as public (see ServerAdapter.checkRouteAuth). Operators deploying\n // standalone workers must configure an auth provider to gate this\n // endpoint — there is no implicit fail-closed.\n const strategy = await getStepStrategy(mastra);\n const result = await strategy.executeStep({\n workflowId,\n runId,\n stepId: body.stepId,\n executionPath: body.executionPath,\n stepResults: body.stepResults,\n state: body.state,\n requestContext: body.requestContext,\n input: body.input,\n resumeData: body.resumeData,\n retryCount: body.retryCount,\n foreachIdx: body.foreachIdx,\n format: body.format,\n perStep: body.perStep,\n validateInputs: body.validateInputs,\n });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error executing workflow step');\n }\n }) as any,\n});\n\n// Wire shape of an Event delivered through a push-mode broker. Validates the\n// fields `WorkflowEventProcessor` depends on; broker envelopes routinely carry\n// extra metadata that isn't part of `Event` itself, so we passthrough the rest.\n// `createdAt` is an ISO timestamp on the wire — the handler converts it to a\n// `Date` before forwarding to `Mastra.handleWorkflowEvent`.\nconst workflowEventSchema = z.object({\n id: z.string(),\n type: z.string(),\n data: z.unknown(),\n runId: z.string(),\n createdAt: z.string(),\n index: z.number().optional(),\n deliveryAttempt: z.number().optional(),\n});\n\nconst receiveWorkflowEventBodySchema = z.object({\n event: workflowEventSchema.passthrough(),\n});\n\nconst receiveWorkflowEventResponseSchema = z.object({\n ok: z.boolean(),\n retry: z.boolean().optional(),\n});\n\ninterface ReceiveWorkflowEventHandlerArgs {\n mastra: Mastra;\n event: Event;\n}\n\n/**\n * Generic push receive endpoint for workflow events. A push-mode broker\n * (GCP Pub/Sub push subscription, SNS, EventBridge) — or a per-broker adapter\n * that decodes the broker's envelope first — POSTs each event here and the\n * response code tells the broker whether to retry:\n *\n * - 200/204 → ack\n * - 5xx → transient, retry with backoff\n * - 4xx → poison, drop / send to DLQ\n *\n * Auth is enforced through the framework's standard `requiresAuth` flow.\n * Operators MUST configure an `authenticateToken` provider that recognizes\n * whatever credential the broker attaches (e.g. a Google-signed OIDC token\n * for GCP Pub/Sub push). Without an auth provider the endpoint is effectively\n * public — same caveat as `EXECUTE_WORKFLOW_STEP_ROUTE`.\n */\nexport const RECEIVE_WORKFLOW_EVENT_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/events',\n responseType: 'json',\n bodySchema: receiveWorkflowEventBodySchema,\n responseSchema: receiveWorkflowEventResponseSchema,\n summary: 'Receive a workflow event from a push-mode broker',\n description:\n 'Push-mode entry point for workflow events. Brokers (GCP Pub/Sub push, SNS, EventBridge) POST each event here; Mastra processes it through the same pipeline as pull-mode workers.',\n tags: ['Workflows', 'Worker'],\n requiresAuth: true,\n // Broker push endpoint: it advances runtime state rather than editing\n // definitions, so `workflows:execute` is the more accurate fit. `write` is\n // kept for back-compat with service principals that already grant it.\n requiresPermission: ['workflows:write', 'workflows:execute'],\n handler: (async ({ mastra, event }: ReceiveWorkflowEventHandlerArgs) => {\n try {\n // The wire schema carries `createdAt` as a string; coerce to Date here\n // before handing off to the in-process pipeline, which expects an `Event`.\n const rawCreatedAt = (event as unknown as { createdAt: unknown }).createdAt;\n const createdAt = rawCreatedAt instanceof Date ? rawCreatedAt : new Date(rawCreatedAt as string);\n if (Number.isNaN(createdAt.getTime())) {\n throw new HTTPException(400, { message: 'Invalid createdAt' });\n }\n return await mastra.handleWorkflowEvent({ ...event, createdAt });\n } catch (error) {\n return handleError(error, 'Error receiving workflow event');\n }\n }) as any,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,eAAe,wBAAwB,EAAE,QAAQ,cAA+B;CAC9E,MAAM,SAAS,OAAO,UAAU;CAEhC,IAAI,CAAC,YACH,MAAM,IAAIA,uBAAAA,cAAc,KAAK,EAAE,SAAS,0BAA0B,CAAC;CAGrE,IAAI;CAGJ,WAAWC,cAAAA,iBAAiB,YAAY,UAAU;CAElD,IAAI,CAAC,UACH,IAAI;EACF,WAAW,OAAO,gBAAgB,UAAU;CAC9C,SAAS,OAAO;EACd,OAAO,MAAM,yDAAyD,KAAK;CAC7E;CAGF,IAAI,CAAC,UAAU;EACb,OAAO,MAAM,qDAAqD,EAAE,WAAW,CAAC;EAChF,MAAM,SAAS,OAAO,WAAW;EAEjC,IAAI,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,CAAC,QAC5B,KAAK,MAAM,CAAC,GAAG,UAAU,OAAO,QAAQ,MAAM,GAC5C,IAAI;GACF,MAAM,YAAY,MAAM,MAAM,cAAc;GAE5C,IAAI,UAAU,aAAa;IACzB,WAAW,UAAU;IACrB;GACF;EACF,SAAS,OAAO;GACd,OAAO,MAAM,qCAAqC,KAAK;EACzD;CAGN;CAEA,IAAI,CAAC,UACH,MAAM,IAAID,uBAAAA,cAAc,KAAK,EAAE,SAAS,qBAAqB,CAAC;CAGhE,OAAO,EAAE,SAAS;AACpB;AAMA,MAAa,uBAAuBE,sBAAAA,YAAY;CAC9C,QAAQ;CACR,MAAM;CACN,cAAc;CACd,kBAAkBC,OAAAA,EAAE,OAAO,EACzB,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,CAAC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,MAAM,eAAgB,MAA4C;GAClE,MAAM,YAAY,wBAAwB,OAAO,eAAe,IAAI,KAAK,YAAsB;GAC/F,IAAI,OAAO,MAAM,UAAU,QAAQ,CAAC,GAClC,MAAM,IAAIF,uBAAAA,cAAc,KAAK,EAAE,SAAS,oBAAoB,CAAC;GAE/D,OAAO,MAAM,OAAO,oBAAoB;IAAE,GAAG;IAAO;GAAU,CAAC;EACjE,SAAS,OAAO;GACd,OAAOO,8BAAAA,YAAY,OAAO,gCAAgC;EAC5D;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"workflows.cjs","names":["HTTPException","WorkflowRegistry","createRoute","z","listWorkflowsResponseSchema","getWorkflowInfo","MastraFGAPermissions","handleError","workflowIdPathParams","workflowInfoSchema","listWorkflowRunsQuerySchema","workflowRunsResponseSchema","getEffectiveResourceId","workflowRunPathParams","workflowRunResultQuerySchema","workflowRunResultSchema","validateRunOwnership","workflowControlResponseSchema","optionalRunIdSchema","createWorkflowRunBodySchema","createWorkflowRunResponseSchema","runIdSchema","streamWorkflowBodySchema","resumeBodySchema","streamResponseSchema","startAsyncWorkflowBodySchema","workflowExecutionResultSchema","observeWorkflowQuerySchema","restartBodySchema","timeTravelBodySchema"],"sources":["../../../src/server/handlers/workflows.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core';\nimport type { RequestContext } from '@mastra/core/di';\nimport type { Event } from '@mastra/core/events';\nimport { createCachingTransformStream, createReplayStream } from '@mastra/core/stream';\nimport type {\n WorkflowInfo,\n ChunkType,\n StreamEvent,\n WorkflowStateField,\n WorkflowRunStatus,\n} from '@mastra/core/workflows';\nimport { z } from 'zod/v4';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\nimport { streamResponseSchema } from '../schemas/agents';\nimport { optionalRunIdSchema, runIdSchema } from '../schemas/common';\nimport {\n createWorkflowRunBodySchema,\n createWorkflowRunResponseSchema,\n listWorkflowRunsQuerySchema,\n listWorkflowsResponseSchema,\n restartBodySchema,\n timeTravelBodySchema,\n resumeBodySchema,\n startAsyncWorkflowBodySchema,\n streamWorkflowBodySchema,\n workflowControlResponseSchema,\n workflowExecutionResultSchema,\n workflowIdPathParams,\n workflowInfoSchema,\n workflowRunPathParams,\n workflowRunsResponseSchema,\n workflowRunResultQuerySchema,\n workflowRunResultSchema,\n observeWorkflowQuerySchema,\n} from '../schemas/workflows';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport type { Context } from '../types';\nimport { getWorkflowInfo, WorkflowRegistry } from '../utils';\nimport { handleError } from './error';\nimport { getEffectiveResourceId, validateRunOwnership } from './utils';\n\n/**\n * Statuses a run cannot come back from. Streaming one of these runIds again would\n * start a fresh execution under the same runId and overwrite its stored snapshot —\n * the in-memory de-dupe that protects concurrent streams only covers runs still held\n * in the workflow's run map, and a finished run has already been dropped from it.\n */\nconst TERMINAL_RUN_STATUSES: WorkflowRunStatus[] = ['success', 'failed', 'canceled', 'tripwire'];\n\nexport interface WorkflowContext extends Context {\n workflowId?: string;\n runId?: string;\n requestContext?: RequestContext;\n}\n\nasync function listWorkflowsFromSystem({ mastra, workflowId }: WorkflowContext) {\n const logger = mastra.getLogger();\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n let workflow;\n\n // First check registry for temporary workflows\n workflow = WorkflowRegistry.getWorkflow(workflowId);\n\n if (!workflow) {\n try {\n workflow = mastra.getWorkflowById(workflowId);\n } catch (error) {\n logger.debug('Error getting workflow, searching agents for workflow', error);\n }\n }\n\n if (!workflow) {\n logger.debug('Workflow not found, searching agents for workflow', { workflowId });\n const agents = mastra.listAgents();\n\n if (Object.keys(agents || {}).length) {\n for (const [_, agent] of Object.entries(agents)) {\n try {\n const workflows = await agent.listWorkflows();\n\n if (workflows[workflowId]) {\n workflow = workflows[workflowId];\n break;\n }\n } catch (error) {\n logger.debug('Error getting workflow from agent', error);\n }\n }\n }\n }\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n return { workflow };\n}\n\n// ============================================================================\n// Route Definitions (new pattern - handlers defined inline with createRoute)\n// ============================================================================\n\nexport const LIST_WORKFLOWS_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows',\n responseType: 'json',\n queryParamSchema: z.object({\n partial: z.string().optional(),\n }),\n responseSchema: listWorkflowsResponseSchema,\n summary: 'List all workflows',\n description: 'Returns a list of all available workflows in the system',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: (async ({ mastra, partial, requestContext }: any) => {\n try {\n const workflows = mastra.listWorkflows({ serialized: false });\n const isPartial = partial === 'true';\n const _workflows = Object.entries(workflows).reduce<Record<string, WorkflowInfo>>((acc, [key, workflow]) => {\n acc[key] = getWorkflowInfo(workflow as any, isPartial);\n return acc;\n }, {});\n\n // Filter workflows by FGA if configured\n const fgaProvider = mastra.getServer?.()?.fga;\n const user = requestContext?.get('user');\n if (fgaProvider) {\n if (!user) {\n return {};\n }\n const workflowList = Object.entries(_workflows).map(([id, w]) => ({ id, ...w }));\n const accessible = await fgaProvider.filterAccessible(\n user,\n workflowList,\n 'workflow',\n MastraFGAPermissions.WORKFLOWS_READ,\n );\n const accessibleSet = new Set(accessible.map((w: any) => w.id));\n for (const id of Object.keys(_workflows)) {\n if (!accessibleSet.has(id)) {\n delete _workflows[id];\n }\n }\n }\n\n return _workflows;\n } catch (error) {\n return handleError(error, 'Error getting workflows');\n }\n }) as any,\n});\n\nexport const GET_WORKFLOW_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows/:workflowId',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n responseSchema: workflowInfoSchema,\n summary: 'Get workflow by ID',\n description: 'Returns details for a specific workflow',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: (async ({ mastra, workflowId }: any) => {\n try {\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n return getWorkflowInfo(workflow, false);\n } catch (error) {\n return handleError(error, 'Error getting workflow');\n }\n }) as any,\n});\n\nexport const LIST_WORKFLOW_RUNS_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows/:workflowId/runs',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: listWorkflowRunsQuerySchema,\n responseSchema: workflowRunsResponseSchema,\n summary: 'List workflow runs',\n description: 'Returns a paginated list of execution runs for the specified workflow',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({\n mastra,\n workflowId,\n fromDate,\n toDate,\n page,\n perPage,\n limit,\n offset,\n resourceId,\n status,\n requestContext,\n }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n // Support both page/perPage and limit/offset for backwards compatibility\n // If page/perPage provided, use directly; otherwise convert from limit/offset\n let finalPage = page;\n let finalPerPage = perPage;\n\n if (finalPerPage === undefined && limit !== undefined) {\n finalPerPage = limit;\n }\n if (finalPage === undefined && offset !== undefined && finalPerPage !== undefined && finalPerPage > 0) {\n finalPage = Math.floor(offset / finalPerPage);\n }\n\n if (\n finalPerPage !== undefined &&\n (typeof finalPerPage !== 'number' || !Number.isInteger(finalPerPage) || finalPerPage <= 0)\n ) {\n throw new HTTPException(400, { message: 'perPage must be a positive integer' });\n }\n if (finalPage !== undefined && (!Number.isInteger(finalPage) || finalPage < 0)) {\n throw new HTTPException(400, { message: 'page must be a non-negative integer' });\n }\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n const workflowRuns = (await workflow.listWorkflowRuns({\n fromDate: fromDate ? (typeof fromDate === 'string' ? new Date(fromDate) : fromDate) : undefined,\n toDate: toDate ? (typeof toDate === 'string' ? new Date(toDate) : toDate) : undefined,\n perPage: finalPerPage,\n page: finalPage,\n resourceId: effectiveResourceId,\n status,\n })) || {\n runs: [],\n total: 0,\n };\n return workflowRuns;\n } catch (error) {\n return handleError(error, 'Error getting workflow runs');\n }\n },\n});\n\nexport const GET_WORKFLOW_RUN_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/workflows/:workflowId/runs/:runId',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n queryParamSchema: workflowRunResultQuerySchema,\n responseSchema: workflowRunResultSchema,\n summary: 'Get workflow run by ID',\n description:\n 'Returns a workflow run with metadata and processed execution state. Use the fields query parameter to reduce payload size by requesting only specific fields (e.g., ?fields=status,result,metadata)',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, fields, withNestedWorkflows, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'Run ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n // Parse fields parameter (comma-separated string)\n const fieldList = fields ? (fields.split(',').map((f: string) => f.trim()) as WorkflowStateField[]) : undefined;\n\n const run = await workflow.getWorkflowRunById(runId, {\n withNestedWorkflows: withNestedWorkflows !== 'false', // Default to true unless explicitly 'false'\n fields: fieldList,\n });\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n return run;\n } catch (error) {\n return handleError(error, 'Error getting workflow run');\n }\n },\n});\n\nexport const DELETE_WORKFLOW_RUN_BY_ID_ROUTE = createRoute({\n method: 'DELETE',\n path: '/workflows/:workflowId/runs/:runId',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Delete workflow run by ID',\n description: 'Deletes a specific workflow run by ID',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'Run ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n // Validate ownership before deletion\n const run = await workflow.getWorkflowRunById(runId);\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n await validateRunOwnership(run, effectiveResourceId);\n\n await workflow.deleteWorkflowRunById(runId);\n\n return { message: 'Workflow run deleted' };\n } catch (error) {\n return handleError(error, 'Error deleting workflow run');\n }\n },\n});\n\nexport const CREATE_WORKFLOW_RUN_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/create-run',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: optionalRunIdSchema,\n bodySchema: createWorkflowRunBodySchema,\n responseSchema: createWorkflowRunResponseSchema,\n summary: 'Create workflow run',\n description: 'Creates a new workflow execution instance with an optional custom run ID',\n tags: ['Workflows'],\n requiresAuth: true,\n // Creating a run is part of the execute flow (Studio/UI calls this before\n // starting/streaming a workflow), so allow either permission. `write` is kept\n // for back-compat with roles that already grant it.\n requiresPermission: ['workflows:write', 'workflows:execute'],\n handler: async ({ mastra, workflowId, runId, resourceId, disableScorers, requestContext }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.createRun({ runId, resourceId: effectiveResourceId, disableScorers });\n\n return { runId: run.runId };\n } catch (error) {\n return handleError(error, 'Error creating workflow run');\n }\n },\n});\n\nexport const STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/stream',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: streamWorkflowBodySchema,\n summary: 'Stream workflow execution',\n description: 'Executes a workflow and streams the results in real-time',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to stream workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const existingRun = await workflow.getWorkflowRunById(runId, { withNestedWorkflows: false });\n\n if (existingRun && TERMINAL_RUN_STATUSES.includes(existingRun.status)) {\n throw new HTTPException(409, {\n message:\n `Workflow run ${runId} already finished with status \"${existingRun.status}\". ` +\n `Use /observe to read its stream back, or stream a new runId.`,\n });\n }\n\n const serverCache = mastra.getServerCache();\n\n const run = await workflow.createRun({ runId, resourceId: effectiveResourceId });\n const result = run.stream({ ...params, requestContext });\n\n if (serverCache) {\n const { transform } = createCachingTransformStream<ChunkType>({\n cache: serverCache,\n cacheKey: runId,\n });\n return result.fullStream.pipeThrough(transform);\n }\n\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error streaming workflow');\n }\n },\n});\n\nexport const RESUME_STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume-stream',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: streamResponseSchema,\n summary: 'Resume workflow stream',\n description: 'Resumes a suspended workflow execution and continues streaming results',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const serverCache = mastra.getServerCache();\n\n const resumeResult = _run.resumeStream({ ...params, requestContext });\n\n if (serverCache) {\n const { transform } = createCachingTransformStream<ChunkType>({\n cache: serverCache,\n cacheKey: runId,\n });\n return resumeResult.fullStream.pipeThrough(transform);\n }\n\n return resumeResult.fullStream;\n } catch (error) {\n return handleError(error, 'Error resuming workflow');\n }\n },\n});\n\nexport const START_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/start-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: optionalRunIdSchema,\n bodySchema: startAsyncWorkflowBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Start workflow asynchronously',\n description: 'Starts a workflow execution asynchronously without streaming results',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {\n try {\n // Use effective resourceId (context key takes precedence over client-provided value)\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const _run = await workflow.createRun({ runId, resourceId: effectiveResourceId });\n const result = await _run.start({ ...params, requestContext });\n return result;\n } catch (error) {\n return handleError(error, 'Error starting async workflow');\n }\n },\n});\n\nexport const START_WORKFLOW_RUN_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/start',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: startAsyncWorkflowBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Start specific workflow run',\n description: 'Starts execution of a specific workflow run by ID',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to start run' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n void _run.start({\n ...params,\n requestContext,\n });\n\n return { message: 'Workflow run started' };\n } catch (e) {\n return handleError(e, 'Error starting workflow run');\n }\n },\n});\n\nexport const OBSERVE_STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/observe',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: observeWorkflowQuerySchema,\n responseSchema: streamResponseSchema,\n summary: 'Observe workflow stream',\n description:\n 'Observes and streams updates from an already running workflow execution. Supports position-based resume with offset for efficient reconnection.',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, offset, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to observe workflow stream' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const serverCache = mastra.getServerCache();\n if (!serverCache) {\n throw new HTTPException(500, { message: 'Server cache not found' });\n }\n\n // Get cached chunks from the specified index (or 0 if not specified)\n const startIndex = offset ?? 0;\n const cachedRunChunks = (await serverCache.listFromTo(runId, startIndex)) as ChunkType[];\n const liveStream = _run.observeStream();\n\n return createReplayStream<ChunkType>({\n history: cachedRunChunks,\n liveSource: liveStream,\n });\n } catch (error) {\n return handleError(error, 'Error observing workflow stream');\n }\n },\n});\n\nexport const RESUME_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Resume workflow asynchronously',\n description: 'Resumes a suspended workflow execution asynchronously without streaming',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.resume({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error resuming workflow step');\n }\n },\n});\n\n/**\n * Fire-and-forget resume: dispatches the resume and returns immediately with the runId,\n * without waiting for the workflow to complete. For Inngest-backed workflows this avoids\n * the `getRunOutput()` polling race that the awaiting `resume-async` route can hit.\n *\n * TODO(v2): in Mastra v2 this fire-and-forget behavior should become the behavior of the\n * `resume-async` route (and `Run.resumeAsync()`), and this route should be removed. It is\n * kept separate in v1 to avoid a breaking change to the existing `resume-async` response\n * contract (which returns the full workflow result).\n */\nexport const RESUME_NO_WAIT_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume-no-wait',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: createWorkflowRunResponseSchema,\n summary: 'Resume workflow without waiting',\n description:\n 'Resumes a suspended workflow execution without waiting (fire-and-forget) and returns immediately with the runId. The workflow continues executing in the background.',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.resumeAsync({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error resuming workflow step');\n }\n },\n});\n\nexport const RESUME_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/resume',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: resumeBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Resume workflow',\n description: 'Resumes a suspended workflow execution from a specific step',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n void _run.resume({ ...params, requestContext });\n\n return { message: 'Workflow run resumed' };\n } catch (error) {\n return handleError(error, 'Error resuming workflow');\n }\n },\n});\n\nexport const RESTART_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: restartBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Restart workflow asynchronously',\n description: 'Restarts an active workflow execution asynchronously',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to restart workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.restart({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const RESTART_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: restartBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Restart workflow',\n description: 'Restarts an active workflow execution',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to restart workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n void _run.restart({ ...params, requestContext });\n\n return { message: 'Workflow run restarted' };\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart-all-active-workflow-runs-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Restart all active workflow runs asynchronously',\n description: 'Restarts all active workflow runs asynchronously',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId }) => {\n try {\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n await workflow.restartAllActiveWorkflowRuns();\n\n return { message: 'All active workflow runs restarted' };\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/restart-all-active-workflow-runs',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Restart all active workflow runs',\n description: 'Restarts all active workflow runs',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId }) => {\n try {\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n void workflow.restartAllActiveWorkflowRuns().catch(error => {\n mastra.getLogger().error('Failed to restart active workflow runs', { error, workflowId });\n });\n\n return { message: 'All active workflow runs restarted' };\n } catch (error) {\n return handleError(error, 'Error restarting workflow');\n }\n },\n});\n\nexport const TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/time-travel-async',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: timeTravelBodySchema,\n responseSchema: workflowExecutionResultSchema,\n summary: 'Time travel workflow asynchronously',\n description: 'Time travels a workflow run asynchronously without streaming',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to time travel workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const result = await _run.timeTravel({ ...params, requestContext });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error time traveling workflow');\n }\n },\n});\n\nexport const TIME_TRAVEL_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/time-travel',\n responseType: 'json',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: timeTravelBodySchema,\n responseSchema: workflowControlResponseSchema,\n summary: 'Time travel workflow',\n description: 'Time travels a workflow run, starting from a specific step',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to time travel workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n void _run.timeTravel({ ...params, requestContext });\n\n return { message: 'Workflow run time travel started' };\n } catch (error) {\n return handleError(error, 'Error time traveling workflow');\n }\n },\n});\n\nexport const TIME_TRAVEL_STREAM_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/time-travel-stream',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: timeTravelBodySchema,\n summary: 'Time travel workflow stream',\n description: 'Time travels a workflow run, starting from a specific step, and streams the results in real-time',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to time travel workflow stream' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n // Validate ownership of existing run before time traveling\n const existingRun = await workflow.getWorkflowRunById(runId);\n if (!existingRun) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n await validateRunOwnership(existingRun, effectiveResourceId);\n\n const serverCache = mastra.getServerCache();\n\n const run = await workflow.createRun({ runId, resourceId: existingRun.resourceId });\n const result = run.timeTravelStream({ ...params, requestContext });\n\n if (serverCache) {\n const { transform } = createCachingTransformStream<ChunkType>({\n cache: serverCache,\n cacheKey: runId,\n });\n return result.fullStream.pipeThrough(transform);\n }\n\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error time traveling workflow stream');\n }\n },\n});\n\nexport const CANCEL_WORKFLOW_RUN_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/runs/:runId/cancel',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n responseSchema: workflowControlResponseSchema,\n summary: 'Cancel workflow run',\n description: 'Cancels an in-progress workflow execution',\n tags: ['Workflows'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to cancel workflow run' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n\n await _run.cancel();\n\n return { message: 'Workflow run cancelled' };\n } catch (error) {\n return handleError(error, 'Error canceling workflow run');\n }\n },\n});\n\n// Legacy routes (deprecated)\nexport const STREAM_LEGACY_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/stream-legacy',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n bodySchema: streamWorkflowBodySchema,\n responseSchema: streamResponseSchema,\n summary: '[DEPRECATED] Stream workflow with legacy format',\n description: 'Legacy endpoint for streaming workflow execution. Use /workflows/:workflowId/stream instead.',\n tags: ['Workflows', 'Legacy'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to resume workflow' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const serverCache = mastra.getServerCache();\n\n const run = await workflow.createRun({ runId, resourceId: effectiveResourceId });\n const result = run.streamLegacy({\n ...params,\n requestContext,\n onChunk: async chunk => {\n if (serverCache) {\n const cacheKey = runId;\n await serverCache.listPush(cacheKey, chunk);\n }\n },\n });\n\n return result.stream;\n } catch (error) {\n return handleError(error, 'Error executing workflow');\n }\n },\n});\n\nexport const OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/observe-stream-legacy',\n responseType: 'stream',\n pathParamSchema: workflowIdPathParams,\n queryParamSchema: runIdSchema,\n responseSchema: streamResponseSchema,\n summary: '[DEPRECATED] Observe workflow stream with legacy format',\n description: 'Legacy endpoint for observing workflow stream. Use /workflows/:workflowId/observe instead.',\n tags: ['Workflows', 'Legacy'],\n requiresAuth: true,\n handler: async ({ mastra, workflowId, runId, requestContext }) => {\n try {\n const effectiveResourceId = getEffectiveResourceId(requestContext, undefined);\n\n if (!workflowId) {\n throw new HTTPException(400, { message: 'Workflow ID is required' });\n }\n\n if (!runId) {\n throw new HTTPException(400, { message: 'runId required to observe workflow stream' });\n }\n\n const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });\n\n if (!workflow) {\n throw new HTTPException(404, { message: 'Workflow not found' });\n }\n\n const run = await workflow.getWorkflowRunById(runId);\n\n if (!run) {\n throw new HTTPException(404, { message: 'Workflow run not found' });\n }\n\n await validateRunOwnership(run, effectiveResourceId);\n\n const _run = await workflow.createRun({ runId, resourceId: run.resourceId });\n const serverCache = mastra.getServerCache();\n if (!serverCache) {\n throw new HTTPException(500, { message: 'Server cache not found' });\n }\n\n // Get cached chunks and create replay stream\n const cachedRunChunks = (await serverCache.listFromTo(runId, 0)) as StreamEvent[];\n const result = _run.observeStreamLegacy();\n\n if (!result.stream) {\n throw new HTTPException(500, { message: 'Failed to create observe stream' });\n }\n\n return createReplayStream<StreamEvent>({\n history: cachedRunChunks,\n liveSource: result.stream,\n });\n } catch (error) {\n return handleError(error, 'Error observing workflow stream');\n }\n },\n});\n\n// ============================================================================\n// Worker Step Execution Endpoint\n// Used by standalone OrchestrationWorker instances with HttpRemoteStrategy.\n// ============================================================================\n\n// `workflowId` and `runId` are taken from path params (single source of\n// truth); they are intentionally omitted from the request body schema.\nconst stepExecutionBodySchema = z.object({\n stepId: z.string(),\n executionPath: z.array(z.number().int().nonnegative()),\n stepResults: z.record(z.string(), z.unknown()),\n state: z.record(z.string(), z.unknown()),\n requestContext: z.record(z.string(), z.unknown()),\n input: z.unknown().optional(),\n resumeData: z.unknown().optional(),\n retryCount: z.number().int().nonnegative().optional(),\n foreachIdx: z.number().int().nonnegative().optional(),\n format: z.enum(['legacy', 'vnext']).optional(),\n perStep: z.boolean().optional(),\n validateInputs: z.boolean().optional(),\n});\n\ntype StepExecutionBody = z.infer<typeof stepExecutionBodySchema>;\n\ninterface StepExecutionHandlerArgs extends StepExecutionBody {\n mastra: Mastra;\n workflowId: string;\n runId: string;\n}\n\n// Reuse the InProcessStrategy across requests for a given Mastra instance.\n// The strategy is stateless beyond its mastra reference, but allocating it\n// per request triggers a dynamic import on the hot path.\n//\n// The dynamic import is required by `pnpm --filter ./packages/server\n// check:core-imports`: `@mastra/core/worker` is a new subpath that older\n// peer-dep floors don't expose, so a static import would fail the check.\n// Once the floor is bumped, this can become a static import.\ntype StepStrategy = { executeStep: (p: unknown) => Promise<unknown> };\nconst strategyByMastra = new WeakMap<Mastra, StepStrategy>();\n\nasync function getStepStrategy(mastra: Mastra): Promise<StepStrategy> {\n let cached = strategyByMastra.get(mastra);\n if (!cached) {\n const { InProcessStrategy } = await import('@mastra/core/worker');\n cached = new InProcessStrategy({ mastra }) as unknown as StepStrategy;\n strategyByMastra.set(mastra, cached);\n }\n return cached;\n}\n\n// Step execution returns the worker's StepResult. Its shape is dynamic\n// and depends on the step's output schema.\nconst stepExecutionResponseSchema = z.unknown();\n\nexport const EXECUTE_WORKFLOW_STEP_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/:workflowId/runs/:runId/steps/execute',\n responseType: 'json',\n pathParamSchema: workflowRunPathParams,\n bodySchema: stepExecutionBodySchema,\n responseSchema: stepExecutionResponseSchema,\n summary: 'Execute a workflow step',\n description:\n 'Internal endpoint used by standalone OrchestrationWorker instances to execute workflow steps remotely via HttpRemoteStrategy.',\n tags: ['Workflows', 'Worker'],\n requiresAuth: true,\n handler: (async ({ mastra, workflowId, runId, ...body }: StepExecutionHandlerArgs) => {\n try {\n // Auth is enforced by the framework via `requiresAuth: true` and the\n // deployer's `authenticateToken` provider. Note that when NO auth\n // provider is configured, the framework currently treats the route\n // as public (see ServerAdapter.checkRouteAuth). Operators deploying\n // standalone workers must configure an auth provider to gate this\n // endpoint — there is no implicit fail-closed.\n const strategy = await getStepStrategy(mastra);\n const result = await strategy.executeStep({\n workflowId,\n runId,\n stepId: body.stepId,\n executionPath: body.executionPath,\n stepResults: body.stepResults,\n state: body.state,\n requestContext: body.requestContext,\n input: body.input,\n resumeData: body.resumeData,\n retryCount: body.retryCount,\n foreachIdx: body.foreachIdx,\n format: body.format,\n perStep: body.perStep,\n validateInputs: body.validateInputs,\n });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error executing workflow step');\n }\n }) as any,\n});\n\n// Wire shape of an Event delivered through a push-mode broker. Validates the\n// fields `WorkflowEventProcessor` depends on; broker envelopes routinely carry\n// extra metadata that isn't part of `Event` itself, so we passthrough the rest.\n// `createdAt` is an ISO timestamp on the wire — the handler converts it to a\n// `Date` before forwarding to `Mastra.handleWorkflowEvent`.\nconst workflowEventSchema = z.object({\n id: z.string(),\n type: z.string(),\n data: z.unknown(),\n runId: z.string(),\n createdAt: z.string(),\n index: z.number().optional(),\n deliveryAttempt: z.number().optional(),\n});\n\nconst receiveWorkflowEventBodySchema = z.object({\n event: workflowEventSchema.passthrough(),\n});\n\nconst receiveWorkflowEventResponseSchema = z.object({\n ok: z.boolean(),\n retry: z.boolean().optional(),\n});\n\ninterface ReceiveWorkflowEventHandlerArgs {\n mastra: Mastra;\n event: Event;\n}\n\n/**\n * Generic push receive endpoint for workflow events. A push-mode broker\n * (GCP Pub/Sub push subscription, SNS, EventBridge) — or a per-broker adapter\n * that decodes the broker's envelope first — POSTs each event here and the\n * response code tells the broker whether to retry:\n *\n * - 200/204 → ack\n * - 5xx → transient, retry with backoff\n * - 4xx → poison, drop / send to DLQ\n *\n * Auth is enforced through the framework's standard `requiresAuth` flow.\n * Operators MUST configure an `authenticateToken` provider that recognizes\n * whatever credential the broker attaches (e.g. a Google-signed OIDC token\n * for GCP Pub/Sub push). Without an auth provider the endpoint is effectively\n * public — same caveat as `EXECUTE_WORKFLOW_STEP_ROUTE`.\n */\nexport const RECEIVE_WORKFLOW_EVENT_ROUTE = createRoute({\n method: 'POST',\n path: '/workflows/events',\n responseType: 'json',\n bodySchema: receiveWorkflowEventBodySchema,\n responseSchema: receiveWorkflowEventResponseSchema,\n summary: 'Receive a workflow event from a push-mode broker',\n description:\n 'Push-mode entry point for workflow events. Brokers (GCP Pub/Sub push, SNS, EventBridge) POST each event here; Mastra processes it through the same pipeline as pull-mode workers.',\n tags: ['Workflows', 'Worker'],\n requiresAuth: true,\n // Broker push endpoint: it advances runtime state rather than editing\n // definitions, so `workflows:execute` is the more accurate fit. `write` is\n // kept for back-compat with service principals that already grant it.\n requiresPermission: ['workflows:write', 'workflows:execute'],\n handler: (async ({ mastra, event }: ReceiveWorkflowEventHandlerArgs) => {\n try {\n // The wire schema carries `createdAt` as a string; coerce to Date here\n // before handing off to the in-process pipeline, which expects an `Event`.\n const rawCreatedAt = (event as unknown as { createdAt: unknown }).createdAt;\n const createdAt = rawCreatedAt instanceof Date ? rawCreatedAt : new Date(rawCreatedAt as string);\n if (Number.isNaN(createdAt.getTime())) {\n throw new HTTPException(400, { message: 'Invalid createdAt' });\n }\n return await mastra.handleWorkflowEvent({ ...event, createdAt });\n } catch (error) {\n return handleError(error, 'Error receiving workflow event');\n }\n }) as any,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,wBAA6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;;;;;;;;;;;;;;;;;;;;gDA6BvC,CAAC"}
@@ -38,6 +38,18 @@ var workflows_exports = /* @__PURE__ */ __exportAll({
38
38
  TIME_TRAVEL_STREAM_WORKFLOW_ROUTE: () => TIME_TRAVEL_STREAM_WORKFLOW_ROUTE,
39
39
  TIME_TRAVEL_WORKFLOW_ROUTE: () => TIME_TRAVEL_WORKFLOW_ROUTE
40
40
  });
41
+ /**
42
+ * Statuses a run cannot come back from. Streaming one of these runIds again would
43
+ * start a fresh execution under the same runId and overwrite its stored snapshot —
44
+ * the in-memory de-dupe that protects concurrent streams only covers runs still held
45
+ * in the workflow's run map, and a finished run has already been dropped from it.
46
+ */
47
+ const TERMINAL_RUN_STATUSES = [
48
+ "success",
49
+ "failed",
50
+ "canceled",
51
+ "tripwire"
52
+ ];
41
53
  async function listWorkflowsFromSystem({ mastra, workflowId }) {
42
54
  const logger = mastra.getLogger();
43
55
  if (!workflowId) throw new HTTPException(400, { message: "Workflow ID is required" });
@@ -282,6 +294,8 @@ const STREAM_WORKFLOW_ROUTE = createRoute({
282
294
  workflowId
283
295
  });
284
296
  if (!workflow) throw new HTTPException(404, { message: "Workflow not found" });
297
+ const existingRun = await workflow.getWorkflowRunById(runId, { withNestedWorkflows: false });
298
+ if (existingRun && TERMINAL_RUN_STATUSES.includes(existingRun.status)) throw new HTTPException(409, { message: `Workflow run ${runId} already finished with status "${existingRun.status}". Use /observe to read its stream back, or stream a new runId.` });
285
299
  const serverCache = mastra.getServerCache();
286
300
  const result = (await workflow.createRun({
287
301
  runId,