@mastra/server 1.77.0-alpha.3 → 1.77.0

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 (74) hide show
  1. package/dist/_types/@mastra_schema-compat/dist/schema.types.d.ts +4 -4
  2. package/dist/{api-schema-manifest-CJFJVu6Q.js → api-schema-manifest-BQOonczJ.js} +2 -2
  3. package/dist/{api-schema-manifest-CJFJVu6Q.js.map → api-schema-manifest-BQOonczJ.js.map} +1 -1
  4. package/dist/{api-schema-manifest-D8uhDn9F.cjs → api-schema-manifest-DC45FBI7.cjs} +2 -2
  5. package/dist/{api-schema-manifest-D8uhDn9F.cjs.map → api-schema-manifest-DC45FBI7.cjs.map} +1 -1
  6. package/dist/{dist-D0yst49-.cjs → dist-Cfv3ewR4.cjs} +7 -4
  7. package/dist/{dist-D0yst49-.cjs.map → dist-Cfv3ewR4.cjs.map} +1 -1
  8. package/dist/{dist-C6Y74AMV.js → dist-aAfueiQI.js} +7 -4
  9. package/dist/{dist-C6Y74AMV.js.map → dist-aAfueiQI.js.map} +1 -1
  10. package/dist/docs/SKILL.md +1 -1
  11. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  12. package/dist/{routes-IIMXw7Iv.js → routes-DhwMARHw.js} +3 -3
  13. package/dist/{routes-IIMXw7Iv.js.map → routes-DhwMARHw.js.map} +1 -1
  14. package/dist/{routes-DCDI9nh-.cjs → routes-Dl6lzZIQ.cjs} +3 -3
  15. package/dist/{routes-DCDI9nh-.cjs.map → routes-Dl6lzZIQ.cjs.map} +1 -1
  16. package/dist/{schedules-OiPV0jLY.js → schedules-C4uNWRwW.js} +7 -3
  17. package/dist/schedules-C4uNWRwW.js.map +1 -0
  18. package/dist/{schedules-Buunf_MT.cjs → schedules-QNH7CUxG.cjs} +7 -3
  19. package/dist/schedules-QNH7CUxG.cjs.map +1 -0
  20. package/dist/server/handlers/agent-builder.cjs +1 -1
  21. package/dist/server/handlers/agent-builder.js +1 -1
  22. package/dist/server/handlers/agent-controller.cjs +15 -10
  23. package/dist/server/handlers/agent-controller.cjs.map +1 -1
  24. package/dist/server/handlers/agent-controller.d.ts +20 -0
  25. package/dist/server/handlers/agent-controller.d.ts.map +1 -1
  26. package/dist/server/handlers/agent-controller.js +15 -10
  27. package/dist/server/handlers/agent-controller.js.map +1 -1
  28. package/dist/server/handlers/agents.cjs +1 -1
  29. package/dist/server/handlers/agents.js +1 -1
  30. package/dist/server/handlers/conversations.cjs +1 -1
  31. package/dist/server/handlers/conversations.js +1 -1
  32. package/dist/server/handlers/logs.cjs +1 -1
  33. package/dist/server/handlers/logs.js +1 -1
  34. package/dist/server/handlers/memory.cjs +1 -1
  35. package/dist/server/handlers/memory.js +1 -1
  36. package/dist/server/handlers/plans.cjs +1 -1
  37. package/dist/server/handlers/plans.js +1 -1
  38. package/dist/server/handlers/responses.cjs +1 -1
  39. package/dist/server/handlers/responses.js +1 -1
  40. package/dist/server/handlers/responses.storage.cjs +1 -1
  41. package/dist/server/handlers/responses.storage.js +1 -1
  42. package/dist/server/handlers/schedules.cjs +1 -1
  43. package/dist/server/handlers/schedules.d.ts.map +1 -1
  44. package/dist/server/handlers/schedules.js +1 -1
  45. package/dist/server/handlers/system.cjs +1 -1
  46. package/dist/server/handlers/system.js +1 -1
  47. package/dist/server/handlers/tools.cjs +1 -1
  48. package/dist/server/handlers/tools.js +1 -1
  49. package/dist/server/handlers/utils.cjs +2 -1
  50. package/dist/server/handlers/utils.d.ts +9 -0
  51. package/dist/server/handlers/utils.d.ts.map +1 -1
  52. package/dist/server/handlers/utils.js +2 -2
  53. package/dist/server/handlers/workflow-builder.cjs +1 -1
  54. package/dist/server/handlers/workflow-builder.js +1 -1
  55. package/dist/server/handlers/workflows.cjs +2 -6
  56. package/dist/server/handlers/workflows.cjs.map +1 -1
  57. package/dist/server/handlers/workflows.d.ts.map +1 -1
  58. package/dist/server/handlers/workflows.js +2 -6
  59. package/dist/server/handlers/workflows.js.map +1 -1
  60. package/dist/server/server-adapter/index.cjs +1 -1
  61. package/dist/server/server-adapter/index.js +1 -1
  62. package/dist/{utils-BQA09BCt.cjs → utils-BD7aRZ1o.cjs} +17 -1
  63. package/dist/utils-BD7aRZ1o.cjs.map +1 -0
  64. package/dist/{utils-kaP2cyIO.js → utils-UwDFLi8y.js} +12 -2
  65. package/dist/utils-UwDFLi8y.js.map +1 -0
  66. package/dist/{workflow-builder-8Rcql7QH.cjs → workflow-builder-DPTDL6sn.cjs} +2 -2
  67. package/dist/{workflow-builder-8Rcql7QH.cjs.map → workflow-builder-DPTDL6sn.cjs.map} +1 -1
  68. package/dist/{workflow-builder-DMTslavM.js → workflow-builder-DwApMkS3.js} +2 -2
  69. package/dist/{workflow-builder-DMTslavM.js.map → workflow-builder-DwApMkS3.js.map} +1 -1
  70. package/package.json +9 -9
  71. package/dist/schedules-Buunf_MT.cjs.map +0 -1
  72. package/dist/schedules-OiPV0jLY.js.map +0 -1
  73. package/dist/utils-BQA09BCt.cjs.map +0 -1
  74. package/dist/utils-kaP2cyIO.js.map +0 -1
@@ -2,7 +2,7 @@ const require_http_exception = require("./http-exception-CKDHupKw.cjs");
2
2
  const require_agents = require("./agents-CKSEPpk1.cjs");
3
3
  const require_route_builder = require("./route-builder-2yrD15TL.cjs");
4
4
  const require_server_handlers_error = require("./server/handlers/error.cjs");
5
- const require_utils = require("./utils-BQA09BCt.cjs");
5
+ const require_utils = require("./utils-BD7aRZ1o.cjs");
6
6
  const require_editor_builder = require("./editor-builder-BtcTQbAC.cjs");
7
7
  let zod_v4 = require("zod/v4");
8
8
  //#region src/server/schemas/workflow-builder.ts
@@ -112,4 +112,4 @@ Object.defineProperty(exports, "STREAM_WORKFLOW_BUILDER_ROUTE", {
112
112
  }
113
113
  });
114
114
 
115
- //# sourceMappingURL=workflow-builder-8Rcql7QH.cjs.map
115
+ //# sourceMappingURL=workflow-builder-DPTDL6sn.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-builder-8Rcql7QH.cjs","names":["z","builderModelPolicySchema","createRoute","handleError","agentExecutionBodySchema","streamResponseSchema","HTTPException","getEffectiveResourceId","getEffectiveThreadId","enforceThreadAccess"],"sources":["../src/server/schemas/workflow-builder.ts","../src/server/handlers/workflow-builder.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { builderModelPolicySchema } from './editor-builder';\n\nexport const workflowBuilderSettingsResponseSchema = z.object({\n enabled: z.boolean(),\n modelPolicy: builderModelPolicySchema.optional(),\n});\n\nexport type WorkflowBuilderSettingsResponse = z.infer<typeof workflowBuilderSettingsResponseSchema>;\n","import { HTTPException } from '../http-exception';\nimport { agentExecutionBodySchema, streamResponseSchema } from '../schemas/agents';\nimport { workflowBuilderSettingsResponseSchema } from '../schemas/workflow-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\nimport {\n enforceThreadAccess,\n getEffectiveResourceId,\n getEffectiveThreadId,\n mergeBodyRequestContext,\n requireEffectiveResourceId,\n validateBody,\n} from './utils';\n\nexport const GET_WORKFLOW_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/workflow-builder/settings',\n responseType: 'json',\n responseSchema: workflowBuilderSettingsResponseSchema,\n summary: 'Get persisted workflow builder settings',\n description: 'Returns whether the editor-owned persisted workflow builder is available',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveWorkflowBuilder !== 'function') return { enabled: false };\n if (!editor.hasEnabledWorkflowBuilderConfig?.()) return { enabled: false };\n\n const builder = await editor.resolveWorkflowBuilder();\n return {\n enabled: builder?.enabled === true,\n modelPolicy: builder?.getModelPolicy(),\n };\n } catch (error) {\n return handleError(error, 'Error getting workflow builder settings');\n }\n },\n});\n\nexport const STREAM_WORKFLOW_BUILDER_ROUTE = createRoute({\n method: 'POST',\n path: '/editor/workflow-builder/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n bodySchema: agentExecutionBodySchema,\n responseSchema: streamResponseSchema,\n summary: 'Stream persisted workflow builder response',\n description: 'Streams from the hidden editor-owned workflow builder agent',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({ mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor?.hasEnabledWorkflowBuilderConfig?.() || typeof editor.resolveWorkflowBuilder !== 'function') {\n throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n }\n\n const builder = await editor.resolveWorkflowBuilder();\n if (!builder?.enabled) throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n const agent = builder.getAgent();\n\n const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;\n validateBody({ messages });\n\n mergeBodyRequestContext(serverRequestContext, bodyRequestContext);\n\n let authorizedMemoryOption = memoryOption;\n if (memoryOption) {\n const clientThreadId = typeof memoryOption.thread === 'string' ? memoryOption.thread : memoryOption.thread?.id;\n const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);\n requireEffectiveResourceId(effectiveResourceId);\n const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);\n\n if (effectiveThreadId) {\n const memory = await agent.getMemory({ requestContext: serverRequestContext });\n const thread = await memory?.getThreadById({ threadId: effectiveThreadId });\n if (thread) {\n await enforceThreadAccess({\n mastra,\n requestContext: serverRequestContext,\n threadId: effectiveThreadId,\n thread,\n effectiveResourceId,\n permission: 'memory:write',\n });\n }\n }\n\n authorizedMemoryOption = {\n ...memoryOption,\n resource: effectiveResourceId ?? memoryOption.resource,\n thread: effectiveThreadId ?? memoryOption.thread,\n };\n }\n\n const { structuredOutput, ...streamOptions } = rest;\n const options: Record<string, any> = {\n ...streamOptions,\n requestContext: serverRequestContext,\n memory: authorizedMemoryOption,\n abortSignal,\n };\n const result = structuredOutput\n ? await agent.stream(messages, { ...options, structuredOutput })\n : await agent.stream(messages, options);\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error streaming workflow builder response');\n }\n },\n});\n"],"mappings":";;;;;;;;AAGA,MAAa,wCAAwCA,OAAAA,EAAE,OAAO;CAC5D,SAASA,OAAAA,EAAE,QAAQ;CACnB,aAAaC,uBAAAA,yBAAyB,SAAS;AACjD,CAAC;;;ACQD,MAAa,sCAAsCC,sBAAAA,YAAY;CAC7D,QAAQ;CACR,MAAM;CACN,cAAc;CACd,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,QAAQ;CACf,cAAc;CACd,oBAAoB;CACpB,SAAS,OAAO,EAAE,aAAa;EAC7B,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI,CAAC,UAAU,OAAO,OAAO,2BAA2B,YAAY,OAAO,EAAE,SAAS,MAAM;GAC5F,IAAI,CAAC,OAAO,kCAAkC,GAAG,OAAO,EAAE,SAAS,MAAM;GAEzE,MAAM,UAAU,MAAM,OAAO,uBAAuB;GACpD,OAAO;IACL,SAAS,SAAS,YAAY;IAC9B,aAAa,SAAS,eAAe;GACvC;EACF,SAAS,OAAO;GACd,OAAOC,8BAAAA,YAAY,OAAO,yCAAyC;EACrE;CACF;AACF,CAAC;AAED,MAAa,gCAAgCD,sBAAAA,YAAY;CACvD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,cAAc;CACd,YAAYE,eAAAA;CACZ,gBAAgBC,eAAAA;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,QAAQ;CACf,cAAc;CACd,oBAAoB;CACpB,SAAS,OAAO,EAAE,QAAQ,aAAa,gBAAgB,sBAAsB,GAAG,aAAa;EAC3F,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI,CAAC,QAAQ,kCAAkC,KAAK,OAAO,OAAO,2BAA2B,YAC3F,MAAM,IAAIC,uBAAAA,cAAc,KAAK,EAAE,SAAS,kCAAkC,CAAC;GAG7E,MAAM,UAAU,MAAM,OAAO,uBAAuB;GACpD,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handleError","agentExecutionBodySchema","streamResponseSchema","HTTPException","getEffectiveResourceId","getEffectiveThreadId","enforceThreadAccess"],"sources":["../src/server/schemas/workflow-builder.ts","../src/server/handlers/workflow-builder.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { builderModelPolicySchema } from './editor-builder';\n\nexport const workflowBuilderSettingsResponseSchema = z.object({\n enabled: z.boolean(),\n modelPolicy: builderModelPolicySchema.optional(),\n});\n\nexport type WorkflowBuilderSettingsResponse = z.infer<typeof workflowBuilderSettingsResponseSchema>;\n","import { HTTPException } from '../http-exception';\nimport { agentExecutionBodySchema, streamResponseSchema } from '../schemas/agents';\nimport { workflowBuilderSettingsResponseSchema } from '../schemas/workflow-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\nimport {\n enforceThreadAccess,\n getEffectiveResourceId,\n getEffectiveThreadId,\n mergeBodyRequestContext,\n requireEffectiveResourceId,\n validateBody,\n} from './utils';\n\nexport const GET_WORKFLOW_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/workflow-builder/settings',\n responseType: 'json',\n responseSchema: workflowBuilderSettingsResponseSchema,\n summary: 'Get persisted workflow builder settings',\n description: 'Returns whether the editor-owned persisted workflow builder is available',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveWorkflowBuilder !== 'function') return { enabled: false };\n if (!editor.hasEnabledWorkflowBuilderConfig?.()) return { enabled: false };\n\n const builder = await editor.resolveWorkflowBuilder();\n return {\n enabled: builder?.enabled === true,\n modelPolicy: builder?.getModelPolicy(),\n };\n } catch (error) {\n return handleError(error, 'Error getting workflow builder settings');\n }\n },\n});\n\nexport const STREAM_WORKFLOW_BUILDER_ROUTE = createRoute({\n method: 'POST',\n path: '/editor/workflow-builder/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n bodySchema: agentExecutionBodySchema,\n responseSchema: streamResponseSchema,\n summary: 'Stream persisted workflow builder response',\n description: 'Streams from the hidden editor-owned workflow builder agent',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({ mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor?.hasEnabledWorkflowBuilderConfig?.() || typeof editor.resolveWorkflowBuilder !== 'function') {\n throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n }\n\n const builder = await editor.resolveWorkflowBuilder();\n if (!builder?.enabled) throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n const agent = builder.getAgent();\n\n const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;\n validateBody({ messages });\n\n mergeBodyRequestContext(serverRequestContext, bodyRequestContext);\n\n let authorizedMemoryOption = memoryOption;\n if (memoryOption) {\n const clientThreadId = typeof memoryOption.thread === 'string' ? memoryOption.thread : memoryOption.thread?.id;\n const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);\n requireEffectiveResourceId(effectiveResourceId);\n const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);\n\n if (effectiveThreadId) {\n const memory = await agent.getMemory({ requestContext: serverRequestContext });\n const thread = await memory?.getThreadById({ threadId: effectiveThreadId });\n if (thread) {\n await enforceThreadAccess({\n mastra,\n requestContext: serverRequestContext,\n threadId: effectiveThreadId,\n thread,\n effectiveResourceId,\n permission: 'memory:write',\n });\n }\n }\n\n authorizedMemoryOption = {\n ...memoryOption,\n resource: effectiveResourceId ?? memoryOption.resource,\n thread: effectiveThreadId ?? memoryOption.thread,\n };\n }\n\n const { structuredOutput, ...streamOptions } = rest;\n const options: Record<string, any> = {\n ...streamOptions,\n requestContext: serverRequestContext,\n memory: authorizedMemoryOption,\n abortSignal,\n };\n const result = structuredOutput\n ? await agent.stream(messages, { ...options, structuredOutput })\n : await agent.stream(messages, options);\n return result.fullStream;\n } catch (error) {\n return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chema } from "./agents-CW_JJZOf.js";
3
3
  import { n as createRoute } from "./route-builder-lBil8Cvo.js";
4
4
  import { handleError } from "./server/handlers/error.js";
5
- import { a as mergeBodyRequestContext, c as requireEffectiveResourceId, d as validateBody, i as getEffectiveThreadId, r as getEffectiveResourceId, t as enforceThreadAccess } from "./utils-kaP2cyIO.js";
5
+ import { f as validateBody, i as getEffectiveThreadId, l as requireEffectiveResourceId, o as mergeBodyRequestContext, r as getEffectiveResourceId, t as enforceThreadAccess } from "./utils-UwDFLi8y.js";
6
6
  import { a as builderModelPolicySchema } from "./editor-builder-CYkaYf6-.js";
7
7
  import { z } from "zod/v4";
8
8
  //#endregion
@@ -99,4 +99,4 @@ const STREAM_WORKFLOW_BUILDER_ROUTE = createRoute({
99
99
  //#endregion
100
100
  export { STREAM_WORKFLOW_BUILDER_ROUTE as n, GET_WORKFLOW_BUILDER_SETTINGS_ROUTE as t };
101
101
 
102
- //# sourceMappingURL=workflow-builder-DMTslavM.js.map
102
+ //# sourceMappingURL=workflow-builder-DwApMkS3.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-builder-DMTslavM.js","names":[],"sources":["../src/server/schemas/workflow-builder.ts","../src/server/handlers/workflow-builder.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { builderModelPolicySchema } from './editor-builder';\n\nexport const workflowBuilderSettingsResponseSchema = z.object({\n enabled: z.boolean(),\n modelPolicy: builderModelPolicySchema.optional(),\n});\n\nexport type WorkflowBuilderSettingsResponse = z.infer<typeof workflowBuilderSettingsResponseSchema>;\n","import { HTTPException } from '../http-exception';\nimport { agentExecutionBodySchema, streamResponseSchema } from '../schemas/agents';\nimport { workflowBuilderSettingsResponseSchema } from '../schemas/workflow-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\nimport {\n enforceThreadAccess,\n getEffectiveResourceId,\n getEffectiveThreadId,\n mergeBodyRequestContext,\n requireEffectiveResourceId,\n validateBody,\n} from './utils';\n\nexport const GET_WORKFLOW_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/workflow-builder/settings',\n responseType: 'json',\n responseSchema: workflowBuilderSettingsResponseSchema,\n summary: 'Get persisted workflow builder settings',\n description: 'Returns whether the editor-owned persisted workflow builder is available',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveWorkflowBuilder !== 'function') return { enabled: false };\n if (!editor.hasEnabledWorkflowBuilderConfig?.()) return { enabled: false };\n\n const builder = await editor.resolveWorkflowBuilder();\n return {\n enabled: builder?.enabled === true,\n modelPolicy: builder?.getModelPolicy(),\n };\n } catch (error) {\n return handleError(error, 'Error getting workflow builder settings');\n }\n },\n});\n\nexport const STREAM_WORKFLOW_BUILDER_ROUTE = createRoute({\n method: 'POST',\n path: '/editor/workflow-builder/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n bodySchema: agentExecutionBodySchema,\n responseSchema: streamResponseSchema,\n summary: 'Stream persisted workflow builder response',\n description: 'Streams from the hidden editor-owned workflow builder agent',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({ mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor?.hasEnabledWorkflowBuilderConfig?.() || typeof editor.resolveWorkflowBuilder !== 'function') {\n throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n }\n\n const builder = await editor.resolveWorkflowBuilder();\n if (!builder?.enabled) throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n const agent = builder.getAgent();\n\n const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;\n validateBody({ messages });\n\n mergeBodyRequestContext(serverRequestContext, bodyRequestContext);\n\n let authorizedMemoryOption = memoryOption;\n if (memoryOption) {\n const clientThreadId = typeof memoryOption.thread === 'string' ? memoryOption.thread : memoryOption.thread?.id;\n const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);\n requireEffectiveResourceId(effectiveResourceId);\n const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);\n\n if (effectiveThreadId) {\n const memory = await agent.getMemory({ requestContext: serverRequestContext });\n const thread = await memory?.getThreadById({ threadId: effectiveThreadId });\n if (thread) {\n await enforceThreadAccess({\n mastra,\n requestContext: serverRequestContext,\n threadId: effectiveThreadId,\n thread,\n effectiveResourceId,\n permission: 'memory:write',\n });\n }\n }\n\n authorizedMemoryOption = {\n ...memoryOption,\n resource: effectiveResourceId ?? memoryOption.resource,\n thread: effectiveThreadId ?? memoryOption.thread,\n };\n }\n\n const { structuredOutput, ...streamOptions } = rest;\n const options: Record<string, any> = {\n ...streamOptions,\n requestContext: serverRequestContext,\n memory: authorizedMemoryOption,\n abortSignal,\n };\n const result = structuredOutput\n ? await agent.stream(messages, { ...options, structuredOutput })\n : await agent.stream(messages, options);\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error streaming workflow builder response');\n }\n },\n});\n"],"mappings":";;;;;;;;;ACcA,MAAa,sCAAsC,YAAY;CAC7D,QAAQ;CACR,MAAM;CACN,cAAc;CACd,gBDfmD,EAAE,OAAO;EAC5D,SAAS,EAAE,QAAQ;EACnB,aAAa,yBAAyB,SAAS;CACjD,CCYkB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,QAAQ;CACf,cAAc;CACd,oBAAoB;CACpB,SAAS,OAAO,EAAE,aAAa;EAC7B,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI,CAAC,UAAU,OAAO,OAAO,2BAA2B,YAAY,OAAO,EAAE,SAAS,MAAM;GAC5F,IAAI,CAAC,OAAO,kCAAkC,GAAG,OAAO,EAAE,SAAS,MAAM;GAEzE,MAAM,UAAU,MAAM,OAAO,uBAAuB;GACpD,OAAO;IACL,SAAS,SAAS,YAAY;IAC9B,aAAa,SAAS,eAAe;GACvC;EACF,S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G;KACH,UAAU,uBAAuB,aAAa;KAC9C,QAAQ,qBAAqB,aAAa;IAC5C;GACF;GAEA,MAAM,EAAE,kBAAkB,GAAG,kBAAkB;GAC/C,MAAM,UAA+B;IACnC,GAAG;IACH,gBAAgB;IAChB,QAAQ;IACR;GACF;GAIA,QAHe,mBACX,MAAM,MAAM,OAAO,UAAU;IAAE,GAAG;IAAS;GAAiB,CAAC,IAC7D,MAAM,MAAM,OAAO,UAAU,OAAO,EAAA,CAC1B;EAChB,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,2CAA2C;EACvE;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"workflow-builder-DwApMkS3.js","names":[],"sources":["../src/server/schemas/workflow-builder.ts","../src/server/handlers/workflow-builder.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { builderModelPolicySchema } from './editor-builder';\n\nexport const workflowBuilderSettingsResponseSchema = z.object({\n enabled: z.boolean(),\n modelPolicy: builderModelPolicySchema.optional(),\n});\n\nexport type WorkflowBuilderSettingsResponse = z.infer<typeof workflowBuilderSettingsResponseSchema>;\n","import { HTTPException } from '../http-exception';\nimport { agentExecutionBodySchema, streamResponseSchema } from '../schemas/agents';\nimport { workflowBuilderSettingsResponseSchema } from '../schemas/workflow-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\nimport {\n enforceThreadAccess,\n getEffectiveResourceId,\n getEffectiveThreadId,\n mergeBodyRequestContext,\n requireEffectiveResourceId,\n validateBody,\n} from './utils';\n\nexport const GET_WORKFLOW_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/workflow-builder/settings',\n responseType: 'json',\n responseSchema: workflowBuilderSettingsResponseSchema,\n summary: 'Get persisted workflow builder settings',\n description: 'Returns whether the editor-owned persisted workflow builder is available',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveWorkflowBuilder !== 'function') return { enabled: false };\n if (!editor.hasEnabledWorkflowBuilderConfig?.()) return { enabled: false };\n\n const builder = await editor.resolveWorkflowBuilder();\n return {\n enabled: builder?.enabled === true,\n modelPolicy: builder?.getModelPolicy(),\n };\n } catch (error) {\n return handleError(error, 'Error getting workflow builder settings');\n }\n },\n});\n\nexport const STREAM_WORKFLOW_BUILDER_ROUTE = createRoute({\n method: 'POST',\n path: '/editor/workflow-builder/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n bodySchema: agentExecutionBodySchema,\n responseSchema: streamResponseSchema,\n summary: 'Stream persisted workflow builder response',\n description: 'Streams from the hidden editor-owned workflow builder agent',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({ mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {\n try {\n const editor = mastra.getEditor();\n if (!editor?.hasEnabledWorkflowBuilderConfig?.() || typeof editor.resolveWorkflowBuilder !== 'function') {\n throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n }\n\n const builder = await editor.resolveWorkflowBuilder();\n if (!builder?.enabled) throw new HTTPException(404, { message: 'Workflow builder is not enabled' });\n const agent = builder.getAgent();\n\n const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;\n validateBody({ messages });\n\n mergeBodyRequestContext(serverRequestContext, bodyRequestContext);\n\n let authorizedMemoryOption = memoryOption;\n if (memoryOption) {\n const clientThreadId = typeof memoryOption.thread === 'string' ? memoryOption.thread : memoryOption.thread?.id;\n const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);\n requireEffectiveResourceId(effectiveResourceId);\n const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);\n\n if (effectiveThreadId) {\n const memory = await agent.getMemory({ requestContext: serverRequestContext });\n const thread = await memory?.getThreadById({ threadId: effectiveThreadId });\n if (thread) {\n await enforceThreadAccess({\n mastra,\n requestContext: serverRequestContext,\n threadId: effectiveThreadId,\n thread,\n effectiveResourceId,\n permission: 'memory:write',\n });\n }\n }\n\n authorizedMemoryOption = {\n ...memoryOption,\n resource: effectiveResourceId ?? memoryOption.resource,\n thread: effectiveThreadId ?? memoryOption.thread,\n };\n }\n\n const { structuredOutput, ...streamOptions } = rest;\n const options: Record<string, any> = {\n ...streamOptions,\n requestContext: serverRequestContext,\n memory: authorizedMemoryOption,\n abortSignal,\n };\n const result = structuredOutput\n ? await agent.stream(messages, { ...options, structuredOutput })\n : await agent.stream(messages, options);\n return result.fullStream;\n } catch (error) {\n return handleError(error, 'Error streaming workflow builder response');\n }\n },\n});\n"],"mappings":";;;;;;;;;ACcA,MAAa,sCAAsC,YAAY;CAC7D,QAAQ;CACR,MAAM;CACN,cAAc;CACd,gBDfmD,EAAE,OAAO;EAC5D,SAAS,EAAE,QAAQ;EACnB,aAAa,yBAAyB,SAAS;CACjD,CCYkB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,QAAQ;CACf,cAAc;CACd,oBAAoB;CACpB,SAAS,OAAO,EAAE,aAAa;EAC7B,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI,CAAC,UAAU,OAAO,OAAO,2BAA2B,YAAY,OAAO,EAAE,SAAS,MAAM;GAC5F,IAAI,CAAC,OAAO,kCAAkC,GAAG,OAAO,EAAE,SAAS,MAAM;GAEzE,MAAM,UAAU,MAAM,OAAO,uBAAuB;GACpD,OAAO;IACL,SAAS,SAAS,YAAY;IAC9B,aAAa,SAAS,eAAe;GACvC;EACF,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,yCAAyC;EACrE;CACF;AACF,CAAC;AAED,MAAa,gCAAgC,YAAY;CACvD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,cAAc;CACd,YAAY;CACZ,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,QAAQ;CACf,cAAc;CACd,oBAAoB;CACpB,SAAS,OAAO,EAAE,QAAQ,aAAa,gBAAgB,sBAAsB,GA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,EAAA,CAC1B;EAChB,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,2CAA2C;EACvE;CACF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/server",
3
- "version": "1.77.0-alpha.3",
3
+ "version": "1.77.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [
@@ -117,14 +117,14 @@
117
117
  "zod": "^4.6.4",
118
118
  "zod-to-ts": "^2.1.0",
119
119
  "@internal/core": "0.1.2",
120
- "@internal/storage-test-utils": "0.0.138",
121
- "@internal/lint": "0.0.142",
122
- "@internal/test-utils": "0.0.78",
123
- "@internal/voice": "0.0.40",
124
- "@internal/types-builder": "0.0.117",
125
- "@mastra/agent-builder": "1.1.28-alpha.2",
126
- "@mastra/schema-compat": "1.3.13",
127
- "@mastra/core": "1.77.0-alpha.3"
120
+ "@internal/lint": "0.0.143",
121
+ "@internal/storage-test-utils": "0.0.139",
122
+ "@internal/voice": "0.0.41",
123
+ "@internal/types-builder": "0.0.118",
124
+ "@mastra/agent-builder": "1.1.28",
125
+ "@internal/test-utils": "0.0.79",
126
+ "@mastra/core": "1.77.0",
127
+ "@mastra/schema-compat": "1.3.14"
128
128
  },
129
129
  "homepage": "https://mastra.ai",
130
130
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"schedules-Buunf_MT.cjs","names":["z","HTTPException","createRoute"],"sources":["../src/server/schemas/schedules.ts","../src/server/handlers/schedules.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const scheduleStatusSchema = z.enum(['active', 'paused', 'completed']);\n\n/** Statuses a caller may set directly; `completed` is only reached by the scheduler. */\nconst settableScheduleStatusSchema = z.enum(['active', 'paused']);\n\n/** Mirrors the core `AgentSignalType` union. */\nconst signalTypeSchema = z.enum(['user', 'state', 'reactive', 'notification', 'user-message', 'system-reminder']);\n\n/** Attributes rendered onto the signal's XML tag. */\nconst signalAttributesSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n);\n\n/** Behavior + attributes applied when the thread is already streaming. */\nconst ifActiveSchema = z.object({\n behavior: z.enum(['deliver', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n});\n\n/**\n * Behavior + attributes applied when the thread is idle, plus a serializable\n * subset of stream options forwarded to the woken run.\n */\nconst ifIdleSchema = z.object({\n behavior: z.enum(['wake', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n streamOptions: z\n .object({\n requestContext: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n});\n\nexport const workflowRunStatusSchema = z.enum([\n 'running',\n 'success',\n 'failed',\n 'tripwire',\n 'suspended',\n 'waiting',\n 'pending',\n 'canceled',\n 'bailed',\n 'paused',\n 'skipped',\n]);\n\nexport const scheduleRunSummarySchema = z.object({\n status: workflowRunStatusSchema,\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n durationMs: z.number().optional(),\n error: z.string().optional(),\n});\n\n/**\n * Flat agent-schedule view. Persisted as a `Schedule` row with a\n * `target.type === 'agent'` variant; the HTTP surface flattens that\n * representation to the fields a user cares about (cron, prompt, threading,\n * status, lifecycle) without exposing the schedule plumbing. Discriminate\n * from workflow schedules by the presence of `agentId`.\n */\nexport const agentScheduleSchema = z.object({\n id: z.string(),\n agentId: z.string(),\n /** Mirror of the workflow-schedule discriminator — always absent on agent schedules. */\n workflowId: z.undefined().optional(),\n /** Workflow-run summary — never hydrated for agent schedules. */\n lastRun: z.undefined().optional(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n prompt: z.string(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/**\n * Flat workflow-schedule view. Discriminate from agent schedules by the\n * presence of `workflowId`.\n */\nexport const workflowScheduleSchema = z.object({\n id: z.string(),\n workflowId: z.string(),\n /** Mirror of the agent-schedule discriminator — always absent on workflow schedules. */\n agentId: z.undefined().optional(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n lastRun: scheduleRunSummarySchema.optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/** Union of the flat views returned by the unified `/schedules` surface. */\nexport const scheduleSchema = z.union([agentScheduleSchema, workflowScheduleSchema]);\n\nexport const scheduleTriggerOutcomeSchema = z.enum([\n 'published',\n 'succeeded',\n 'delivered',\n 'persisted',\n 'discarded',\n 'skipped',\n 'aborted',\n 'failed',\n // Legacy queue/notification outcomes — no longer written, but trigger rows\n // persisted by older builds may still carry them. Kept readable so the\n // response validator does not reject historical rows. Mirrors the core\n // ScheduleTriggerOutcome union.\n 'acked',\n 'alerted',\n 'deferred',\n 'appended-from-queue',\n 'dropped-stale',\n 'dropped-superseded',\n 'dropped-busy',\n]);\n\nexport const scheduleTriggerKindSchema = z.enum(['schedule-fire', 'queue-drain', 'manual']);\n\nexport const scheduleTriggerResponseSchema = z.object({\n id: z.string().optional(),\n scheduleId: z.string(),\n runId: z.string().nullable(),\n scheduledFireAt: z.number(),\n actualFireAt: z.number(),\n outcome: scheduleTriggerOutcomeSchema,\n error: z.string().optional(),\n triggerKind: scheduleTriggerKindSchema.optional(),\n parentTriggerId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n run: scheduleRunSummarySchema.optional(),\n});\n\nexport const listSchedulesQuerySchema = z.object({\n agentId: z.string().optional(),\n workflowId: z.string().optional(),\n status: scheduleStatusSchema.optional(),\n /** Agent-schedule only: match the target threadId. */\n threadId: z.string().optional(),\n /** Match the schedule's resourceId (agent thread identity or workflow run attribution). */\n resourceId: z.string().optional(),\n /** Agent-schedule only: match the free-form target name. */\n name: z.string().optional(),\n});\n\nexport const listSchedulesResponseSchema = z.object({\n schedules: z.array(scheduleSchema),\n});\n\nexport const scheduleIdPathParams = z.object({\n scheduleId: z.string(),\n});\n\n/**\n * Agent variant of the create body — targets an agent by `agentId`. Strict so\n * a body carrying both `agentId` and `workflowId` is rejected as ambiguous\n * instead of silently matching the agent branch of the union.\n */\nconst createAgentScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `agent_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n agentId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n prompt: z.string(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Workflow variant of the create body — targets a workflow by `workflowId`.\n * Strict so ambiguous bodies (both ids) are rejected by the union.\n */\nconst createWorkflowScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `schedule_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n workflowId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Body for POST /schedules. Discriminated by which target id is present:\n * `agentId` creates an agent schedule, `workflowId` a workflow schedule.\n * Both variants are strict, so a body carrying both ids (or unknown keys)\n * fails validation instead of silently dropping fields.\n */\nexport const createScheduleBodySchema = z.union([createAgentScheduleBodySchema, createWorkflowScheduleBodySchema]);\n\n/**\n * Body for PATCH /schedules/:scheduleId — partial update. Fields apply to\n * the matching target type; agent-only fields on a workflow schedule are\n * rejected by the service. An agent schedule's `threadId` / `resourceId` are\n * intentionally not editable; they are part of its identity — to re-target,\n * delete and recreate. A workflow schedule's `resourceId` is only run-attribution\n * metadata (not identity) and may be updated.\n */\nexport const updateScheduleBodySchema = z.object({\n cron: z.string().optional(),\n timezone: z.string().optional(),\n status: settableScheduleStatusSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n // Agent-schedule fields\n prompt: z.string().optional(),\n name: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n // Workflow-schedule fields\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n});\n\nexport const deleteScheduleResponseSchema = z.object({\n message: z.string(),\n});\n\n/** Response for POST /schedules/:scheduleId/run. */\nexport const runScheduleResponseSchema = z.object({\n scheduleId: z.string(),\n claimId: z.string(),\n scheduledFireAt: z.number(),\n});\n\nexport const listScheduleTriggersQuerySchema = z.object({\n limit: z.coerce.number().int().positive().optional(),\n fromActualFireAt: z.coerce.number().int().nonnegative().optional(),\n toActualFireAt: z.coerce.number().int().nonnegative().optional(),\n});\n\nexport const listScheduleTriggersResponseSchema = z.object({\n triggers: z.array(scheduleTriggerResponseSchema),\n});\n\nexport type AgentScheduleResponse = z.infer<typeof agentScheduleSchema>;\nexport type WorkflowScheduleResponse = z.infer<typeof workflowScheduleSchema>;\nexport type ScheduleResponse = z.infer<typeof scheduleSchema>;\n","import type { Mastra } from '@mastra/core';\nimport type { AgentSchedule, AnySchedule, WorkflowSchedule } from '@mastra/core/schedules';\nimport type { WorkflowRunState } from '@mastra/core/workflows';\nimport { HTTPException } from '../http-exception';\nimport {\n createScheduleBodySchema,\n deleteScheduleResponseSchema,\n listSchedulesQuerySchema,\n listSchedulesResponseSchema,\n listScheduleTriggersQuerySchema,\n listScheduleTriggersResponseSchema,\n runScheduleResponseSchema,\n scheduleIdPathParams,\n scheduleSchema,\n updateScheduleBodySchema,\n} from '../schemas/schedules';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\ntype RunSummary = {\n status: WorkflowRunState['status'];\n startedAt?: number;\n completedAt?: number;\n durationMs?: number;\n error?: string;\n};\n\nfunction snapshotToRunSummary(run: {\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}): RunSummary | undefined {\n const snapshot = typeof run.snapshot === 'string' ? null : run.snapshot;\n if (!snapshot) return undefined;\n const startedAt = run.createdAt instanceof Date ? run.createdAt.getTime() : undefined;\n const isTerminal =\n snapshot.status === 'success' ||\n snapshot.status === 'failed' ||\n snapshot.status === 'canceled' ||\n snapshot.status === 'bailed' ||\n snapshot.status === 'tripwire';\n const completedAt = isTerminal ? (run.updatedAt instanceof Date ? run.updatedAt.getTime() : undefined) : undefined;\n const durationMs = startedAt !== undefined && completedAt !== undefined ? completedAt - startedAt : undefined;\n return {\n status: snapshot.status,\n startedAt,\n completedAt,\n durationMs,\n error: snapshot.error?.message,\n };\n}\n\nasync function fetchRunSummary(mastra: Mastra, workflowName: string, runId: string): Promise<RunSummary | undefined> {\n try {\n const workflowsStore = await mastra.getStorage()?.getStore('workflows');\n const run = await workflowsStore?.getWorkflowRunById({ runId, workflowName });\n if (!run) return undefined;\n return snapshotToRunSummary(run);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Attach a `lastRun` summary to workflow schedules. Agent schedules pass\n * through unchanged — their `lastRunId` is an agent run, not a workflow run.\n */\nasync function hydrateScheduleResponse(\n mastra: Mastra,\n schedule: AnySchedule,\n): Promise<AgentSchedule | (WorkflowSchedule & { lastRun?: RunSummary })> {\n if (!schedule.workflowId || !schedule.lastRunId) {\n return schedule;\n }\n const lastRun = await fetchRunSummary(mastra, schedule.workflowId, schedule.lastRunId);\n return lastRun ? { ...schedule, lastRun } : schedule;\n}\n\n/**\n * Resolve a schedule by id via `mastra.schedules`. Returns 404 for missing\n * rows so handlers surface a clean HTTP error instead of a service error.\n */\nasync function loadSchedule(mastra: Mastra, scheduleId: string): Promise<AnySchedule> {\n const schedule = await mastra.schedules.get(scheduleId);\n if (!schedule) {\n throw new HTTPException(404, { message: 'Schedule not found' });\n }\n return schedule;\n}\n\nexport const LIST_SCHEDULES_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules',\n responseType: 'json' as const,\n queryParamSchema: listSchedulesQuerySchema,\n responseSchema: listSchedulesResponseSchema,\n summary: 'List schedules',\n description:\n 'Returns all schedules — agent schedules and workflow schedules — optionally filtered by agentId, workflowId, or status. Completed schedules are excluded unless requested with a status filter. Agent schedules can additionally be filtered by threadId, resourceId, or name.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, workflowId, status, threadId, resourceId, name }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n // Schedules domain not configured — there are no schedules to return.\n return { schedules: [] };\n }\n const schedules = await mastra.schedules.list({ agentId, workflowId, status, threadId, resourceId, name });\n const hydrated = await Promise.all(schedules.map(schedule => hydrateScheduleResponse(mastra, schedule)));\n return { schedules: hydrated };\n },\n});\n\nexport const GET_SCHEDULE_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Get a schedule by ID',\n description: 'Returns a single schedule by its id.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n const schedule = await loadSchedule(mastra, scheduleId);\n return hydrateScheduleResponse(mastra, schedule);\n },\n});\n\nexport const CREATE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules',\n responseType: 'json' as const,\n bodySchema: createScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Create a schedule',\n description:\n 'Creates a new schedule. Pass `agentId` (plus `prompt`) to schedule an agent, or `workflowId` (plus optional `inputData`) to schedule a workflow. Agent schedules get a random `agent_<uuid>` id, workflow schedules a random `schedule_<uuid>` id; pass `id` for a stable slug instead.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, ...body }) => {\n // getAgentById / getWorkflowById throw a MastraError (status 404) when the\n // target is unknown; translate that into a clean HTTP 404 instead of\n // letting it surface as 500.\n if ('workflowId' in body && body.workflowId) {\n try {\n mastra.getWorkflowById(body.workflowId);\n } catch {\n throw new HTTPException(404, { message: `Workflow \"${body.workflowId}\" not found` });\n }\n return await mastra.schedules.create({\n workflowId: body.workflowId,\n cron: body.cron,\n ...(body.id ? { id: body.id } : {}),\n ...(body.timezone ? { timezone: body.timezone } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId ? { resourceId: body.resourceId } : {}),\n ...(body.metadata ? { metadata: body.metadata } : {}),\n });\n }\n const agentBody = body as Extract<typeof body, { agentId: string }>;\n try {\n mastra.getAgentById(agentBody.agentId);\n } catch {\n throw new HTTPException(404, { message: `Agent \"${agentBody.agentId}\" not found` });\n }\n return await mastra.schedules.create({\n agentId: agentBody.agentId,\n cron: agentBody.cron,\n prompt: agentBody.prompt,\n ...(agentBody.id ? { id: agentBody.id } : {}),\n ...(agentBody.name ? { name: agentBody.name } : {}),\n ...(agentBody.timezone ? { timezone: agentBody.timezone } : {}),\n ...(agentBody.threadId ? { threadId: agentBody.threadId } : {}),\n ...(agentBody.resourceId ? { resourceId: agentBody.resourceId } : {}),\n ...(agentBody.signalType ? { signalType: agentBody.signalType } : {}),\n ...(agentBody.tagName ? { tagName: agentBody.tagName } : {}),\n ...(agentBody.attributes ? { attributes: agentBody.attributes } : {}),\n ...(agentBody.ifActive ? { ifActive: agentBody.ifActive } : {}),\n ...(agentBody.ifIdle ? { ifIdle: agentBody.ifIdle } : {}),\n ...(agentBody.providerOptions ? { providerOptions: agentBody.providerOptions } : {}),\n ...(agentBody.metadata ? { metadata: agentBody.metadata } : {}),\n });\n },\n});\n\nexport const UPDATE_SCHEDULE_ROUTE = createRoute({\n method: 'PATCH',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n bodySchema: updateScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Update a schedule',\n description:\n \"Partial update of a schedule. Fields apply to the matching target type; agent-only fields on a workflow schedule are rejected. An agent schedule's `threadId` and `resourceId` are part of its identity and cannot be changed — to re-target, delete and recreate. A workflow schedule's `resourceId` is run-attribution metadata and may be updated. Editing `cron` (or `timezone`) recomputes `nextFireAt`. A recomputed cadence that can still fire reactivates a `completed` schedule, while a cadence with no future occurrence leaves the schedule `completed`.\",\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, ...body }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.update(scheduleId, {\n ...(body.cron !== undefined ? { cron: body.cron } : {}),\n ...(body.timezone !== undefined ? { timezone: body.timezone } : {}),\n ...(body.status !== undefined ? { status: body.status } : {}),\n ...(body.metadata !== undefined ? { metadata: body.metadata } : {}),\n ...(body.prompt !== undefined ? { prompt: body.prompt } : {}),\n ...(body.name !== undefined ? { name: body.name } : {}),\n ...(body.signalType !== undefined ? { signalType: body.signalType } : {}),\n ...(body.tagName !== undefined ? { tagName: body.tagName } : {}),\n ...(body.attributes !== undefined ? { attributes: body.attributes } : {}),\n ...(body.ifActive !== undefined ? { ifActive: body.ifActive } : {}),\n ...(body.ifIdle !== undefined ? { ifIdle: body.ifIdle } : {}),\n ...(body.providerOptions !== undefined ? { providerOptions: body.providerOptions } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext !== undefined ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId !== undefined ? { resourceId: body.resourceId } : {}),\n });\n },\n});\n\nexport const DELETE_SCHEDULE_ROUTE = createRoute({\n method: 'DELETE',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: deleteScheduleResponseSchema,\n summary: 'Delete a schedule',\n description: 'Permanently deletes the schedule. 404 when the schedule does not exist.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n await mastra.schedules.delete(scheduleId);\n return { message: 'Schedule deleted' };\n },\n});\n\nexport const PAUSE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/pause',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Pause a schedule',\n description:\n 'Marks the schedule as paused. The scheduler tick loop will skip paused schedules. Idempotent — pausing an already-paused schedule returns the current state unchanged. Pause status survives redeploys.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.pause(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RESUME_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/resume',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Resume a paused schedule',\n description:\n 'Marks the schedule as active and recomputes nextFireAt from \"now\" so a long-paused schedule does not fire a backlog. Idempotent — resuming an already-active schedule returns the current state unchanged.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.resume(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RUN_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/run',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: runScheduleResponseSchema,\n summary: 'Fire a schedule now',\n description:\n 'Manually triggers a single schedule fire out-of-band from the cron schedule. Records a trigger row with `triggerKind: \"manual\"`. Does not advance `nextFireAt`.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.run(scheduleId);\n },\n});\n\nexport const LIST_SCHEDULE_TRIGGERS_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId/triggers',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n queryParamSchema: listScheduleTriggersQuerySchema,\n responseSchema: listScheduleTriggersResponseSchema,\n summary: 'List trigger history for a schedule',\n description: 'Returns the audit trail of trigger attempts for a schedule, ordered by actualFireAt descending.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, limit, fromActualFireAt, toActualFireAt }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n return { triggers: [] };\n }\n const schedule = await mastra.schedules.get(scheduleId);\n const triggers = await schedulesStore.listTriggers(schedule?.id ?? scheduleId, {\n limit,\n fromActualFireAt,\n toActualFireAt,\n });\n if (!schedule?.workflowId) {\n return { triggers };\n }\n const workflowName = schedule.workflowId;\n const hydrated = await Promise.all(\n triggers.map(async trigger => {\n if (trigger.outcome !== 'published' || !trigger.runId) return trigger;\n const run = await fetchRunSummary(mastra, workflowName, trigger.runId);\n return run ? { ...trigger, run } : trigger;\n }),\n );\n return { triggers: hydrated };\n },\n});\n"],"mappings":";;;;AAEA,MAAa,uB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UAAU,YACb,OAAO,EAAE,SAAS;EAEpB,MAAM,eAAe,SAAS;EAQ9B,OAAO,EAAE,UAAU,MAPI,QAAQ,IAC7B,SAAS,IAAI,OAAM,YAAW;GAC5B,IAAI,QAAQ,YAAY,eAAe,CAAC,QAAQ,OAAO,OAAO;GAC9D,MAAM,MAAM,MAAM,gBAAgB,QAAQ,cAAc,QAAQ,KAAK;GACrE,OAAO,MAAM;IAAE,GAAG;IAAS;GAAI,IAAI;EACrC,CAAC,CACH,EAC4B;CAC9B;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"schedules-OiPV0jLY.js","names":["z"],"sources":["../src/server/schemas/schedules.ts","../src/server/handlers/schedules.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const scheduleStatusSchema = z.enum(['active', 'paused', 'completed']);\n\n/** Statuses a caller may set directly; `completed` is only reached by the scheduler. */\nconst settableScheduleStatusSchema = z.enum(['active', 'paused']);\n\n/** Mirrors the core `AgentSignalType` union. */\nconst signalTypeSchema = z.enum(['user', 'state', 'reactive', 'notification', 'user-message', 'system-reminder']);\n\n/** Attributes rendered onto the signal's XML tag. */\nconst signalAttributesSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n);\n\n/** Behavior + attributes applied when the thread is already streaming. */\nconst ifActiveSchema = z.object({\n behavior: z.enum(['deliver', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n});\n\n/**\n * Behavior + attributes applied when the thread is idle, plus a serializable\n * subset of stream options forwarded to the woken run.\n */\nconst ifIdleSchema = z.object({\n behavior: z.enum(['wake', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n streamOptions: z\n .object({\n requestContext: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n});\n\nexport const workflowRunStatusSchema = z.enum([\n 'running',\n 'success',\n 'failed',\n 'tripwire',\n 'suspended',\n 'waiting',\n 'pending',\n 'canceled',\n 'bailed',\n 'paused',\n 'skipped',\n]);\n\nexport const scheduleRunSummarySchema = z.object({\n status: workflowRunStatusSchema,\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n durationMs: z.number().optional(),\n error: z.string().optional(),\n});\n\n/**\n * Flat agent-schedule view. Persisted as a `Schedule` row with a\n * `target.type === 'agent'` variant; the HTTP surface flattens that\n * representation to the fields a user cares about (cron, prompt, threading,\n * status, lifecycle) without exposing the schedule plumbing. Discriminate\n * from workflow schedules by the presence of `agentId`.\n */\nexport const agentScheduleSchema = z.object({\n id: z.string(),\n agentId: z.string(),\n /** Mirror of the workflow-schedule discriminator — always absent on agent schedules. */\n workflowId: z.undefined().optional(),\n /** Workflow-run summary — never hydrated for agent schedules. */\n lastRun: z.undefined().optional(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n prompt: z.string(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/**\n * Flat workflow-schedule view. Discriminate from agent schedules by the\n * presence of `workflowId`.\n */\nexport const workflowScheduleSchema = z.object({\n id: z.string(),\n workflowId: z.string(),\n /** Mirror of the agent-schedule discriminator — always absent on workflow schedules. */\n agentId: z.undefined().optional(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n lastRun: scheduleRunSummarySchema.optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/** Union of the flat views returned by the unified `/schedules` surface. */\nexport const scheduleSchema = z.union([agentScheduleSchema, workflowScheduleSchema]);\n\nexport const scheduleTriggerOutcomeSchema = z.enum([\n 'published',\n 'succeeded',\n 'delivered',\n 'persisted',\n 'discarded',\n 'skipped',\n 'aborted',\n 'failed',\n // Legacy queue/notification outcomes — no longer written, but trigger rows\n // persisted by older builds may still carry them. Kept readable so the\n // response validator does not reject historical rows. Mirrors the core\n // ScheduleTriggerOutcome union.\n 'acked',\n 'alerted',\n 'deferred',\n 'appended-from-queue',\n 'dropped-stale',\n 'dropped-superseded',\n 'dropped-busy',\n]);\n\nexport const scheduleTriggerKindSchema = z.enum(['schedule-fire', 'queue-drain', 'manual']);\n\nexport const scheduleTriggerResponseSchema = z.object({\n id: z.string().optional(),\n scheduleId: z.string(),\n runId: z.string().nullable(),\n scheduledFireAt: z.number(),\n actualFireAt: z.number(),\n outcome: scheduleTriggerOutcomeSchema,\n error: z.string().optional(),\n triggerKind: scheduleTriggerKindSchema.optional(),\n parentTriggerId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n run: scheduleRunSummarySchema.optional(),\n});\n\nexport const listSchedulesQuerySchema = z.object({\n agentId: z.string().optional(),\n workflowId: z.string().optional(),\n status: scheduleStatusSchema.optional(),\n /** Agent-schedule only: match the target threadId. */\n threadId: z.string().optional(),\n /** Match the schedule's resourceId (agent thread identity or workflow run attribution). */\n resourceId: z.string().optional(),\n /** Agent-schedule only: match the free-form target name. */\n name: z.string().optional(),\n});\n\nexport const listSchedulesResponseSchema = z.object({\n schedules: z.array(scheduleSchema),\n});\n\nexport const scheduleIdPathParams = z.object({\n scheduleId: z.string(),\n});\n\n/**\n * Agent variant of the create body — targets an agent by `agentId`. Strict so\n * a body carrying both `agentId` and `workflowId` is rejected as ambiguous\n * instead of silently matching the agent branch of the union.\n */\nconst createAgentScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `agent_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n agentId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n prompt: z.string(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Workflow variant of the create body — targets a workflow by `workflowId`.\n * Strict so ambiguous bodies (both ids) are rejected by the union.\n */\nconst createWorkflowScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `schedule_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n workflowId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Body for POST /schedules. Discriminated by which target id is present:\n * `agentId` creates an agent schedule, `workflowId` a workflow schedule.\n * Both variants are strict, so a body carrying both ids (or unknown keys)\n * fails validation instead of silently dropping fields.\n */\nexport const createScheduleBodySchema = z.union([createAgentScheduleBodySchema, createWorkflowScheduleBodySchema]);\n\n/**\n * Body for PATCH /schedules/:scheduleId — partial update. Fields apply to\n * the matching target type; agent-only fields on a workflow schedule are\n * rejected by the service. An agent schedule's `threadId` / `resourceId` are\n * intentionally not editable; they are part of its identity — to re-target,\n * delete and recreate. A workflow schedule's `resourceId` is only run-attribution\n * metadata (not identity) and may be updated.\n */\nexport const updateScheduleBodySchema = z.object({\n cron: z.string().optional(),\n timezone: z.string().optional(),\n status: settableScheduleStatusSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n // Agent-schedule fields\n prompt: z.string().optional(),\n name: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n // Workflow-schedule fields\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n});\n\nexport const deleteScheduleResponseSchema = z.object({\n message: z.string(),\n});\n\n/** Response for POST /schedules/:scheduleId/run. */\nexport const runScheduleResponseSchema = z.object({\n scheduleId: z.string(),\n claimId: z.string(),\n scheduledFireAt: z.number(),\n});\n\nexport const listScheduleTriggersQuerySchema = z.object({\n limit: z.coerce.number().int().positive().optional(),\n fromActualFireAt: z.coerce.number().int().nonnegative().optional(),\n toActualFireAt: z.coerce.number().int().nonnegative().optional(),\n});\n\nexport const listScheduleTriggersResponseSchema = z.object({\n triggers: z.array(scheduleTriggerResponseSchema),\n});\n\nexport type AgentScheduleResponse = z.infer<typeof agentScheduleSchema>;\nexport type WorkflowScheduleResponse = z.infer<typeof workflowScheduleSchema>;\nexport type ScheduleResponse = z.infer<typeof scheduleSchema>;\n","import type { Mastra } from '@mastra/core';\nimport type { AgentSchedule, AnySchedule, WorkflowSchedule } from '@mastra/core/schedules';\nimport type { WorkflowRunState } from '@mastra/core/workflows';\nimport { HTTPException } from '../http-exception';\nimport {\n createScheduleBodySchema,\n deleteScheduleResponseSchema,\n listSchedulesQuerySchema,\n listSchedulesResponseSchema,\n listScheduleTriggersQuerySchema,\n listScheduleTriggersResponseSchema,\n runScheduleResponseSchema,\n scheduleIdPathParams,\n scheduleSchema,\n updateScheduleBodySchema,\n} from '../schemas/schedules';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\ntype RunSummary = {\n status: WorkflowRunState['status'];\n startedAt?: number;\n completedAt?: number;\n durationMs?: number;\n error?: string;\n};\n\nfunction snapshotToRunSummary(run: {\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}): RunSummary | undefined {\n const snapshot = typeof run.snapshot === 'string' ? null : run.snapshot;\n if (!snapshot) return undefined;\n const startedAt = run.createdAt instanceof Date ? run.createdAt.getTime() : undefined;\n const isTerminal =\n snapshot.status === 'success' ||\n snapshot.status === 'failed' ||\n snapshot.status === 'canceled' ||\n snapshot.status === 'bailed' ||\n snapshot.status === 'tripwire';\n const completedAt = isTerminal ? (run.updatedAt instanceof Date ? run.updatedAt.getTime() : undefined) : undefined;\n const durationMs = startedAt !== undefined && completedAt !== undefined ? completedAt - startedAt : undefined;\n return {\n status: snapshot.status,\n startedAt,\n completedAt,\n durationMs,\n error: snapshot.error?.message,\n };\n}\n\nasync function fetchRunSummary(mastra: Mastra, workflowName: string, runId: string): Promise<RunSummary | undefined> {\n try {\n const workflowsStore = await mastra.getStorage()?.getStore('workflows');\n const run = await workflowsStore?.getWorkflowRunById({ runId, workflowName });\n if (!run) return undefined;\n return snapshotToRunSummary(run);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Attach a `lastRun` summary to workflow schedules. Agent schedules pass\n * through unchanged — their `lastRunId` is an agent run, not a workflow run.\n */\nasync function hydrateScheduleResponse(\n mastra: Mastra,\n schedule: AnySchedule,\n): Promise<AgentSchedule | (WorkflowSchedule & { lastRun?: RunSummary })> {\n if (!schedule.workflowId || !schedule.lastRunId) {\n return schedule;\n }\n const lastRun = await fetchRunSummary(mastra, schedule.workflowId, schedule.lastRunId);\n return lastRun ? { ...schedule, lastRun } : schedule;\n}\n\n/**\n * Resolve a schedule by id via `mastra.schedules`. Returns 404 for missing\n * rows so handlers surface a clean HTTP error instead of a service error.\n */\nasync function loadSchedule(mastra: Mastra, scheduleId: string): Promise<AnySchedule> {\n const schedule = await mastra.schedules.get(scheduleId);\n if (!schedule) {\n throw new HTTPException(404, { message: 'Schedule not found' });\n }\n return schedule;\n}\n\nexport const LIST_SCHEDULES_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules',\n responseType: 'json' as const,\n queryParamSchema: listSchedulesQuerySchema,\n responseSchema: listSchedulesResponseSchema,\n summary: 'List schedules',\n description:\n 'Returns all schedules — agent schedules and workflow schedules — optionally filtered by agentId, workflowId, or status. Completed schedules are excluded unless requested with a status filter. Agent schedules can additionally be filtered by threadId, resourceId, or name.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, workflowId, status, threadId, resourceId, name }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n // Schedules domain not configured — there are no schedules to return.\n return { schedules: [] };\n }\n const schedules = await mastra.schedules.list({ agentId, workflowId, status, threadId, resourceId, name });\n const hydrated = await Promise.all(schedules.map(schedule => hydrateScheduleResponse(mastra, schedule)));\n return { schedules: hydrated };\n },\n});\n\nexport const GET_SCHEDULE_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Get a schedule by ID',\n description: 'Returns a single schedule by its id.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n const schedule = await loadSchedule(mastra, scheduleId);\n return hydrateScheduleResponse(mastra, schedule);\n },\n});\n\nexport const CREATE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules',\n responseType: 'json' as const,\n bodySchema: createScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Create a schedule',\n description:\n 'Creates a new schedule. Pass `agentId` (plus `prompt`) to schedule an agent, or `workflowId` (plus optional `inputData`) to schedule a workflow. Agent schedules get a random `agent_<uuid>` id, workflow schedules a random `schedule_<uuid>` id; pass `id` for a stable slug instead.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, ...body }) => {\n // getAgentById / getWorkflowById throw a MastraError (status 404) when the\n // target is unknown; translate that into a clean HTTP 404 instead of\n // letting it surface as 500.\n if ('workflowId' in body && body.workflowId) {\n try {\n mastra.getWorkflowById(body.workflowId);\n } catch {\n throw new HTTPException(404, { message: `Workflow \"${body.workflowId}\" not found` });\n }\n return await mastra.schedules.create({\n workflowId: body.workflowId,\n cron: body.cron,\n ...(body.id ? { id: body.id } : {}),\n ...(body.timezone ? { timezone: body.timezone } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId ? { resourceId: body.resourceId } : {}),\n ...(body.metadata ? { metadata: body.metadata } : {}),\n });\n }\n const agentBody = body as Extract<typeof body, { agentId: string }>;\n try {\n mastra.getAgentById(agentBody.agentId);\n } catch {\n throw new HTTPException(404, { message: `Agent \"${agentBody.agentId}\" not found` });\n }\n return await mastra.schedules.create({\n agentId: agentBody.agentId,\n cron: agentBody.cron,\n prompt: agentBody.prompt,\n ...(agentBody.id ? { id: agentBody.id } : {}),\n ...(agentBody.name ? { name: agentBody.name } : {}),\n ...(agentBody.timezone ? { timezone: agentBody.timezone } : {}),\n ...(agentBody.threadId ? { threadId: agentBody.threadId } : {}),\n ...(agentBody.resourceId ? { resourceId: agentBody.resourceId } : {}),\n ...(agentBody.signalType ? { signalType: agentBody.signalType } : {}),\n ...(agentBody.tagName ? { tagName: agentBody.tagName } : {}),\n ...(agentBody.attributes ? { attributes: agentBody.attributes } : {}),\n ...(agentBody.ifActive ? { ifActive: agentBody.ifActive } : {}),\n ...(agentBody.ifIdle ? { ifIdle: agentBody.ifIdle } : {}),\n ...(agentBody.providerOptions ? { providerOptions: agentBody.providerOptions } : {}),\n ...(agentBody.metadata ? { metadata: agentBody.metadata } : {}),\n });\n },\n});\n\nexport const UPDATE_SCHEDULE_ROUTE = createRoute({\n method: 'PATCH',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n bodySchema: updateScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Update a schedule',\n description:\n \"Partial update of a schedule. Fields apply to the matching target type; agent-only fields on a workflow schedule are rejected. An agent schedule's `threadId` and `resourceId` are part of its identity and cannot be changed — to re-target, delete and recreate. A workflow schedule's `resourceId` is run-attribution metadata and may be updated. Editing `cron` (or `timezone`) recomputes `nextFireAt`. A recomputed cadence that can still fire reactivates a `completed` schedule, while a cadence with no future occurrence leaves the schedule `completed`.\",\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, ...body }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.update(scheduleId, {\n ...(body.cron !== undefined ? { cron: body.cron } : {}),\n ...(body.timezone !== undefined ? { timezone: body.timezone } : {}),\n ...(body.status !== undefined ? { status: body.status } : {}),\n ...(body.metadata !== undefined ? { metadata: body.metadata } : {}),\n ...(body.prompt !== undefined ? { prompt: body.prompt } : {}),\n ...(body.name !== undefined ? { name: body.name } : {}),\n ...(body.signalType !== undefined ? { signalType: body.signalType } : {}),\n ...(body.tagName !== undefined ? { tagName: body.tagName } : {}),\n ...(body.attributes !== undefined ? { attributes: body.attributes } : {}),\n ...(body.ifActive !== undefined ? { ifActive: body.ifActive } : {}),\n ...(body.ifIdle !== undefined ? { ifIdle: body.ifIdle } : {}),\n ...(body.providerOptions !== undefined ? { providerOptions: body.providerOptions } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext !== undefined ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId !== undefined ? { resourceId: body.resourceId } : {}),\n });\n },\n});\n\nexport const DELETE_SCHEDULE_ROUTE = createRoute({\n method: 'DELETE',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: deleteScheduleResponseSchema,\n summary: 'Delete a schedule',\n description: 'Permanently deletes the schedule. 404 when the schedule does not exist.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n await mastra.schedules.delete(scheduleId);\n return { message: 'Schedule deleted' };\n },\n});\n\nexport const PAUSE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/pause',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Pause a schedule',\n description:\n 'Marks the schedule as paused. The scheduler tick loop will skip paused schedules. Idempotent — pausing an already-paused schedule returns the current state unchanged. Pause status survives redeploys.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.pause(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RESUME_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/resume',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Resume a paused schedule',\n description:\n 'Marks the schedule as active and recomputes nextFireAt from \"now\" so a long-paused schedule does not fire a backlog. Idempotent — resuming an already-active schedule returns the current state unchanged.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.resume(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RUN_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/run',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: runScheduleResponseSchema,\n summary: 'Fire a schedule now',\n description:\n 'Manually triggers a single schedule fire out-of-band from the cron schedule. Records a trigger row with `triggerKind: \"manual\"`. Does not advance `nextFireAt`.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.run(scheduleId);\n },\n});\n\nexport const LIST_SCHEDULE_TRIGGERS_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId/triggers',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n queryParamSchema: listScheduleTriggersQuerySchema,\n responseSchema: listScheduleTriggersResponseSchema,\n summary: 'List trigger history for a schedule',\n description: 'Returns the audit trail of trigger attempts for a schedule, ordered by actualFireAt descending.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, limit, fromActualFireAt, toActualFireAt }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n return { triggers: [] };\n }\n const schedule = await mastra.schedules.get(scheduleId);\n const triggers = await schedulesStore.listTriggers(schedule?.id ?? scheduleId, {\n limit,\n fromActualFireAt,\n toActualFireAt,\n });\n if (!schedule?.workflowId) {\n return { triggers };\n }\n const workflowName = schedule.workflowId;\n const hydrated = await Promise.all(\n triggers.map(async trigger => {\n if (trigger.outcome !== 'published' || !trigger.runId) return trigger;\n const run = await fetchRunSummary(mastra, workflowName, trigger.runId);\n return run ? { ...trigger, run } : trigger;\n }),\n );\n return { triggers: hydrated };\n },\n});\n"],"mappings":";;;;AAEA,MAAa,uBAAuBA,IAAE,KAAK;CAAC;CAAU;CAAU;AAAW,CAAC;;AAG5E,MAAM,+BAA+BA,IAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;;AAGhE,MAAM,mBAAmBA,IAAE,KAAK;CAAC;CAAQ;CAAS;CAAY;CAAgB;CAAgB;AAAiB,CAAC;;AAGhH,MAAM,yBAAyBA,IAAE,OAC/BA,IAAE,OAAO,GACTA,IAAE,MAAM;CAACA,IAAE,OAAO;CAAGA,IAAE,OAAO;CAAGA,IAAE,QAAQ;CAAGA,IAAE,KAAK;AAAC,CAAC,CAAC,CAAC,SAAS,CACpE;;AAGA,MAAM,iBAAiBA,IAAE,OAAO;CAC9B,UAAUA,IAAE,KAAK;EAAC;EAAW;EAAW;CAAS,CAAC,CAAC,C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ChD;AACF,CAAC;AAED,MAAa,qBAAqB,YAAY;CAC5C,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,SAAS;CACT,aACE;CACF,MAAM,CAAC,WAAW;CAClB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,iBAAiB;EACzC,MAAM,aAAa,QAAQ,UAAU;EACrC,OAAO,MAAM,OAAO,UAAU,IAAI,UAAU;CAC9C;AACF,CAAC;AAED,MAAa,+BAA+B,YAAY;CACtD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,WAAW;CAClB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,YAAY,OAAO,kBAAkB,qBAAqB;EAClF,MAAM,iBAAiB,MAAM,OAAO,WAAW,CAAC,EAAE,SAAS,WAAW;EACtE,IAAI,CAAC,gBACH,OAAO,EAAE,UAAU,CAAC,EAAE;EAExB,MAAM,WAAW,MAAM,OAAO,UAAU,IAAI,UAAU;EACtD,MAAM,WAAW,MAAM,eAAe,aAAa,UAAU,MAAM,YAAY;GAC7E;GACA;GACA;EACF,CAAC;EACD,IAAI,CAAC,UAAU,YACb,OAAO,EAAE,SAAS;EAEpB,MAAM,eAAe,SAAS;EAQ9B,OAAO,EAAE,UAAU,MAPI,QAAQ,IAC7B,SAAS,IAAI,OAAM,YAAW;GAC5B,IAAI,QAAQ,YAAY,eAAe,CAAC,QAAQ,OAAO,OAAO;GAC9D,MAAM,MAAM,MAAM,gBAAgB,QAAQ,cAAc,QAAQ,KAAK;GACrE,OAAO,MAAM;IAAE,GAAG;IAAS;GAAI,IAAI;EACrC,CAAC,CACH,EAC4B;CAC9B;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils-BQA09BCt.cjs","names":["authEE","HTTPException","isReservedRequestContextKey","MASTRA_RESOURCE_ID_KEY","MastraMemory"],"sources":["../src/server/fga-permissions.ts","../src/server/handlers/utils.ts"],"sourcesContent":["/**\n * Safe re-export of `MastraFGAPermissions` from `@mastra/core/auth/ee`.\n *\n * Why this shim exists:\n * `MastraFGAPermissions` was introduced in `@mastra/core@1.32.0`. Earlier\n * versions of `@mastra/core` ship `@mastra/core/auth/ee` but do not export\n * this constant. A direct named import (`import { MastraFGAPermissions }\n * from '@mastra/core/auth/ee'`) fails at ESM link time when this version\n * of `@mastra/server` is paired with `@mastra/core < 1.32.0`, taking the\n * entire user bundle down before any code runs.\n *\n * A namespace import tolerates missing names — `ns.MissingExport` is just\n * `undefined`, no link-time error. We then expose the permission map.\n *\n * Fallback values:\n * If the consuming `@mastra/core` does not export `MastraFGAPermissions`,\n * we substitute a hardcoded map of the canonical permission strings used\n * by routes in `@mastra/server`. This preserves the explicit RBAC\n * permission overrides those routes already had as string literals in\n * `@mastra/server@1.31.0` (e.g. `requiresPermission: \"agents:execute\"`\n * on `/v1/responses`). Without this fallback, `requiresPermission` would\n * be `undefined` on old core and the auth layer would derive the wrong\n * permission from the route path (e.g. `v1:write` instead of\n * `agents:execute`), breaking RBAC users who upgrade `@mastra/server`\n * but stay on `@mastra/core@1.31.0`.\n *\n * Once the consuming `@mastra/core` is on `1.32.0+` the values are real\n * and behaviour is identical to a direct named import.\n */\n\nimport * as authEE from '@mastra/core/auth/ee';\n\n// Canonical strings for the FGA permission keys actually referenced by\n// `@mastra/server` source. Mirrors `MastraFGAPermissions` in\n// `@mastra/core@1.32.0+` for these specific keys, and matches the string\n// literals previously hardcoded on the same routes in `@mastra/server@1.31.0`.\nconst FALLBACK_PERMISSIONS = {\n AGENTS_CREATE: 'agents:create',\n AGENTS_DELETE: 'agents:delete',\n AGENTS_EXECUTE: 'agents:execute',\n AGENTS_READ: 'agents:read',\n MEMORY_DELETE: 'memory:delete',\n MEMORY_READ: 'memory:read',\n MEMORY_WRITE: 'memory:write',\n TOOLS_EXECUTE: 'tools:execute',\n TOOLS_READ: 'tools:read',\n STORED_WORKFLOWS_READ: 'stored-workflows:read',\n STORED_WORKFLOWS_WRITE: 'stored-workflows:write',\n WORKFLOWS_EXECUTE: 'workflows:execute',\n WORKFLOWS_READ: 'workflows:read',\n} as const;\n\nconst realPermissions = (authEE as any).MastraFGAPermissions;\n\n// Typed as `any` on purpose: consumers of `@mastra/server` may run their\n// typecheck against a `@mastra/core` that doesn't export `MastraFGAPermissions`\n// (anything < 1.32.0). Pinning to the real type would push that name into the\n// emitted `.d.ts` and break downstream typecheck. `any` lets the property\n// accesses (`MastraFGAPermissions.AGENTS_READ`) flow through cleanly on every\n// supported core.\nexport const MastraFGAPermissions: any =\n realPermissions && Object.keys(realPermissions).length > 0 ? realPermissions : FALLBACK_PERMISSIONS;\n","import type { MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { MastraMemory } from '@mastra/core/memory';\nimport { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, isReservedRequestContextKey } from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\n\n// Validation helper\nexport function validateBody(body: Record<string, unknown>) {\n const errorResponse = Object.entries(body).reduce<Record<string, string>>((acc, [key, value]) => {\n if (!value) {\n acc[key] = `Argument \"${key}\" is required`;\n }\n return acc;\n }, {});\n\n if (Object.keys(errorResponse).length > 0) {\n throw new HTTPException(400, { message: Object.values(errorResponse)[0] });\n }\n}\n\n/**\n * sanitizes the body by removing disallowed keys.\n * @param body body to sanitize\n * @param disallowedKeys keys to remove from the body\n */\nexport function sanitizeBody(body: Record<string, unknown>, disallowedKeys: string[]) {\n for (const key of disallowedKeys) {\n if (key in body) {\n delete body[key];\n }\n }\n}\n\nconst CREDENTIAL_HEADER_NAMES = new Set([\n 'authorization',\n 'proxy-authorization',\n 'x-api-key',\n 'api-key',\n 'x-goog-api-key',\n 'cookie',\n]);\n\n/**\n * Removes credential-bearing headers from client-supplied `modelSettings.headers`\n * so a caller's own auth (e.g. the app's bearer token) can never override the\n * provider credential configured on the server. Non-credential headers are kept.\n */\nexport function stripClientCredentialHeaders(body: Record<string, unknown>) {\n const modelSettings = body.modelSettings;\n if (!modelSettings || typeof modelSettings !== 'object') return;\n const headers = (modelSettings as { headers?: unknown }).headers;\n if (!headers || typeof headers !== 'object') return;\n\n const kept = Object.fromEntries(\n Object.entries(headers).filter(([name]) => !CREDENTIAL_HEADER_NAMES.has(name.toLowerCase())),\n );\n body.modelSettings = { ...modelSettings, headers: kept };\n}\n\nexport function parsePerPage(\n value: string | undefined,\n defaultValue: number = 100,\n max: number = 1000,\n): number | false {\n const normalized = (value || '').trim().toLowerCase();\n // Handle explicit false to bypass pagination\n if (normalized === 'false') {\n return false;\n }\n const parsed = parseInt(value || String(defaultValue), 10);\n if (isNaN(parsed)) return defaultValue;\n return Math.min(max, Math.max(1, parsed));\n}\n\n/**\n * Parses filter query parameters into a key-value object.\n */\nexport function parseFilters(filters: string | string[] | undefined): Record<string, string> | undefined {\n if (!filters) return undefined;\n\n return Object.fromEntries(\n (Array.isArray(filters) ? filters : [filters]).map((attr: string) => {\n const [key, ...valueParts] = attr.split(':');\n const value = valueParts.join(':'); // ✅ Handles colons in values\n return [key, value];\n }),\n );\n}\n\n/**\n * Merges a body-supplied requestContext into the trusted server RequestContext.\n * The server context is authoritative: reserved keys are skipped and body values\n * only fill keys the server context has not already set.\n */\nexport function mergeBodyRequestContext(serverRequestContext: RequestContext, bodyRequestContext: unknown): void {\n if (!bodyRequestContext || typeof bodyRequestContext !== 'object') {\n return;\n }\n\n for (const [key, value] of Object.entries(bodyRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n if (serverRequestContext.get(key) === undefined) {\n serverRequestContext.set(key, value);\n }\n }\n}\n\n// ============================================================================\n// Authorization Utilities\n// ============================================================================\n\n/**\n * Gets the effective resourceId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveResourceId(\n requestContext: RequestContext | undefined,\n clientResourceId: string | undefined,\n): string | undefined {\n const contextResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n return contextResourceId || clientResourceId;\n}\n\n/**\n * Returns the resource id resolved from the request context alone (set via\n * `mapUserToResourceId` or the `x-resource-id` header), ignoring any\n * client-provided value. Its presence indicates a resource-scoped caller;\n * its absence indicates a privileged/service context.\n */\nexport function getContextResourceId(requestContext: RequestContext | undefined): string | undefined {\n return requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n}\n\n/**\n * Ensures a memory request has a resolvable resource ID. The body's\n * `memory.resource` is optional so authenticated setups can rely on the\n * server-derived resource ID (MASTRA_RESOURCE_ID_KEY set via mapUserToResourceId).\n * When neither the body nor the request context provides one, reject with a\n * clear 400 instead of failing deep inside agent execution.\n */\nexport function requireEffectiveResourceId(\n effectiveResourceId: string | undefined,\n): asserts effectiveResourceId is string {\n if (!effectiveResourceId) {\n throw new HTTPException(400, {\n message:\n 'A resource ID is required when using memory. Provide memory.resource in the request body, or configure server auth with mapUserToResourceId to derive it from the authenticated user.',\n });\n }\n}\n\n/**\n * Gets the effective threadId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveThreadId(\n requestContext: RequestContext | undefined,\n clientThreadId: string | undefined,\n): string | undefined {\n const contextThreadId = requestContext?.get(MASTRA_THREAD_ID_KEY) as string | undefined;\n return contextThreadId || clientThreadId;\n}\n\n/**\n * Validates that a thread belongs to the specified resourceId.\n * Throws 403 if the thread exists but belongs to a different resource.\n * Threads with no resourceId are accessible to all (shared threads).\n */\nexport async function validateThreadOwnership(\n thread: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (thread && effectiveResourceId && thread.resourceId && thread.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: thread belongs to a different resource' });\n }\n}\n\n/**\n * Validates both coarse resource ownership and fine-grained thread access.\n * FGA enforcement is a no-op when no FGA provider is configured.\n */\nexport async function enforceThreadAccess({\n mastra,\n requestContext,\n threadId,\n thread,\n effectiveResourceId,\n permission = MastraFGAPermissions.MEMORY_READ,\n}: {\n mastra: any;\n requestContext?: RequestContext;\n threadId: string;\n thread?: { resourceId?: string | null } | null;\n effectiveResourceId?: string;\n permission?: MastraFGAPermissionInput;\n}): Promise<void> {\n await validateThreadOwnership(thread, effectiveResourceId);\n\n const fgaProvider = mastra?.getServer?.()?.fga;\n if (!fgaProvider) {\n return;\n }\n\n const user = requestContext?.get('user');\n if (!user || typeof user !== 'object') {\n throw new HTTPException(403, { message: 'FGA authorization denied: authenticated user is required' });\n }\n\n await MastraMemory.checkThreadFGA({\n mastra,\n user: user as { id: string; [key: string]: unknown },\n threadId,\n resourceId: thread?.resourceId ?? effectiveResourceId,\n requestContext,\n permission,\n });\n}\n\n/**\n * Validates that a workflow run belongs to the specified resourceId.\n * Throws 403 if the run exists but belongs to a different resource.\n */\nexport async function validateRunOwnership(\n run: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (run && effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,uBAAuB;CAC3B,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,aAAa;CACb,cAAc;CACd,eAAe;CACf,YAAY;CACZ,uBAAuB;CACvB,wBAAwB;CACxB,mBAAmB;CACnB,gBAAgB;AAClB;AAEA,MAAM,kBAAmBA,qBAAe;AAQxC,MAAa,uBACX,mBAAmB,OAAO,KAAK,eAAe,CAAC,CAAC,SAAS,IAAI,kBAAkB;;;ACrDjF,SAAgB,aAAa,MAA+B;CAC1D,MAAM,gBAAgB,OAAO,QAAQ,IAAI,CAAC,CAAC,QAAgC,KAAK,CAAC,KAAK,WAAW;EAC/F,IAAI,CAAC,OACH,IAAI,OAA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AAMG,oBAAAA,aAAa,eAAe;EAChC;EACM;EACN;EACA,YAAY,QAAQ,cAAc;EAClC;EACA;CACF,CAAC;AACH;;;;;AAMA,eAAsB,qBACpB,KACA,qBACe;CACf,IAAI,OAAO,uBAAuB,IAAI,cAAc,IAAI,eAAe,qBACrE,MAAM,IAAIH,uBAAAA,cAAc,KAAK,EAAE,SAAS,8DAA8D,CAAC;AAE3G"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils-kaP2cyIO.js","names":[],"sources":["../src/server/fga-permissions.ts","../src/server/handlers/utils.ts"],"sourcesContent":["/**\n * Safe re-export of `MastraFGAPermissions` from `@mastra/core/auth/ee`.\n *\n * Why this shim exists:\n * `MastraFGAPermissions` was introduced in `@mastra/core@1.32.0`. Earlier\n * versions of `@mastra/core` ship `@mastra/core/auth/ee` but do not export\n * this constant. A direct named import (`import { MastraFGAPermissions }\n * from '@mastra/core/auth/ee'`) fails at ESM link time when this version\n * of `@mastra/server` is paired with `@mastra/core < 1.32.0`, taking the\n * entire user bundle down before any code runs.\n *\n * A namespace import tolerates missing names — `ns.MissingExport` is just\n * `undefined`, no link-time error. We then expose the permission map.\n *\n * Fallback values:\n * If the consuming `@mastra/core` does not export `MastraFGAPermissions`,\n * we substitute a hardcoded map of the canonical permission strings used\n * by routes in `@mastra/server`. This preserves the explicit RBAC\n * permission overrides those routes already had as string literals in\n * `@mastra/server@1.31.0` (e.g. `requiresPermission: \"agents:execute\"`\n * on `/v1/responses`). Without this fallback, `requiresPermission` would\n * be `undefined` on old core and the auth layer would derive the wrong\n * permission from the route path (e.g. `v1:write` instead of\n * `agents:execute`), breaking RBAC users who upgrade `@mastra/server`\n * but stay on `@mastra/core@1.31.0`.\n *\n * Once the consuming `@mastra/core` is on `1.32.0+` the values are real\n * and behaviour is identical to a direct named import.\n */\n\nimport * as authEE from '@mastra/core/auth/ee';\n\n// Canonical strings for the FGA permission keys actually referenced by\n// `@mastra/server` source. Mirrors `MastraFGAPermissions` in\n// `@mastra/core@1.32.0+` for these specific keys, and matches the string\n// literals previously hardcoded on the same routes in `@mastra/server@1.31.0`.\nconst FALLBACK_PERMISSIONS = {\n AGENTS_CREATE: 'agents:create',\n AGENTS_DELETE: 'agents:delete',\n AGENTS_EXECUTE: 'agents:execute',\n AGENTS_READ: 'agents:read',\n MEMORY_DELETE: 'memory:delete',\n MEMORY_READ: 'memory:read',\n MEMORY_WRITE: 'memory:write',\n TOOLS_EXECUTE: 'tools:execute',\n TOOLS_READ: 'tools:read',\n STORED_WORKFLOWS_READ: 'stored-workflows:read',\n STORED_WORKFLOWS_WRITE: 'stored-workflows:write',\n WORKFLOWS_EXECUTE: 'workflows:execute',\n WORKFLOWS_READ: 'workflows:read',\n} as const;\n\nconst realPermissions = (authEE as any).MastraFGAPermissions;\n\n// Typed as `any` on purpose: consumers of `@mastra/server` may run their\n// typecheck against a `@mastra/core` that doesn't export `MastraFGAPermissions`\n// (anything < 1.32.0). Pinning to the real type would push that name into the\n// emitted `.d.ts` and break downstream typecheck. `any` lets the property\n// accesses (`MastraFGAPermissions.AGENTS_READ`) flow through cleanly on every\n// supported core.\nexport const MastraFGAPermissions: any =\n realPermissions && Object.keys(realPermissions).length > 0 ? realPermissions : FALLBACK_PERMISSIONS;\n","import type { MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { MastraMemory } from '@mastra/core/memory';\nimport { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, isReservedRequestContextKey } from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\n\n// Validation helper\nexport function validateBody(body: Record<string, unknown>) {\n const errorResponse = Object.entries(body).reduce<Record<string, string>>((acc, [key, value]) => {\n if (!value) {\n acc[key] = `Argument \"${key}\" is required`;\n }\n return acc;\n }, {});\n\n if (Object.keys(errorResponse).length > 0) {\n throw new HTTPException(400, { message: Object.values(errorResponse)[0] });\n }\n}\n\n/**\n * sanitizes the body by removing disallowed keys.\n * @param body body to sanitize\n * @param disallowedKeys keys to remove from the body\n */\nexport function sanitizeBody(body: Record<string, unknown>, disallowedKeys: string[]) {\n for (const key of disallowedKeys) {\n if (key in body) {\n delete body[key];\n }\n }\n}\n\nconst CREDENTIAL_HEADER_NAMES = new Set([\n 'authorization',\n 'proxy-authorization',\n 'x-api-key',\n 'api-key',\n 'x-goog-api-key',\n 'cookie',\n]);\n\n/**\n * Removes credential-bearing headers from client-supplied `modelSettings.headers`\n * so a caller's own auth (e.g. the app's bearer token) can never override the\n * provider credential configured on the server. Non-credential headers are kept.\n */\nexport function stripClientCredentialHeaders(body: Record<string, unknown>) {\n const modelSettings = body.modelSettings;\n if (!modelSettings || typeof modelSettings !== 'object') return;\n const headers = (modelSettings as { headers?: unknown }).headers;\n if (!headers || typeof headers !== 'object') return;\n\n const kept = Object.fromEntries(\n Object.entries(headers).filter(([name]) => !CREDENTIAL_HEADER_NAMES.has(name.toLowerCase())),\n );\n body.modelSettings = { ...modelSettings, headers: kept };\n}\n\nexport function parsePerPage(\n value: string | undefined,\n defaultValue: number = 100,\n max: number = 1000,\n): number | false {\n const normalized = (value || '').trim().toLowerCase();\n // Handle explicit false to bypass pagination\n if (normalized === 'false') {\n return false;\n }\n const parsed = parseInt(value || String(defaultValue), 10);\n if (isNaN(parsed)) return defaultValue;\n return Math.min(max, Math.max(1, parsed));\n}\n\n/**\n * Parses filter query parameters into a key-value object.\n */\nexport function parseFilters(filters: string | string[] | undefined): Record<string, string> | undefined {\n if (!filters) return undefined;\n\n return Object.fromEntries(\n (Array.isArray(filters) ? filters : [filters]).map((attr: string) => {\n const [key, ...valueParts] = attr.split(':');\n const value = valueParts.join(':'); // ✅ Handles colons in values\n return [key, value];\n }),\n );\n}\n\n/**\n * Merges a body-supplied requestContext into the trusted server RequestContext.\n * The server context is authoritative: reserved keys are skipped and body values\n * only fill keys the server context has not already set.\n */\nexport function mergeBodyRequestContext(serverRequestContext: RequestContext, bodyRequestContext: unknown): void {\n if (!bodyRequestContext || typeof bodyRequestContext !== 'object') {\n return;\n }\n\n for (const [key, value] of Object.entries(bodyRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n if (serverRequestContext.get(key) === undefined) {\n serverRequestContext.set(key, value);\n }\n }\n}\n\n// ============================================================================\n// Authorization Utilities\n// ============================================================================\n\n/**\n * Gets the effective resourceId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveResourceId(\n requestContext: RequestContext | undefined,\n clientResourceId: string | undefined,\n): string | undefined {\n const contextResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n return contextResourceId || clientResourceId;\n}\n\n/**\n * Returns the resource id resolved from the request context alone (set via\n * `mapUserToResourceId` or the `x-resource-id` header), ignoring any\n * client-provided value. Its presence indicates a resource-scoped caller;\n * its absence indicates a privileged/service context.\n */\nexport function getContextResourceId(requestContext: RequestContext | undefined): string | undefined {\n return requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n}\n\n/**\n * Ensures a memory request has a resolvable resource ID. The body's\n * `memory.resource` is optional so authenticated setups can rely on the\n * server-derived resource ID (MASTRA_RESOURCE_ID_KEY set via mapUserToResourceId).\n * When neither the body nor the request context provides one, reject with a\n * clear 400 instead of failing deep inside agent execution.\n */\nexport function requireEffectiveResourceId(\n effectiveResourceId: string | undefined,\n): asserts effectiveResourceId is string {\n if (!effectiveResourceId) {\n throw new HTTPException(400, {\n message:\n 'A resource ID is required when using memory. Provide memory.resource in the request body, or configure server auth with mapUserToResourceId to derive it from the authenticated user.',\n });\n }\n}\n\n/**\n * Gets the effective threadId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveThreadId(\n requestContext: RequestContext | undefined,\n clientThreadId: string | undefined,\n): string | undefined {\n const contextThreadId = requestContext?.get(MASTRA_THREAD_ID_KEY) as string | undefined;\n return contextThreadId || clientThreadId;\n}\n\n/**\n * Validates that a thread belongs to the specified resourceId.\n * Throws 403 if the thread exists but belongs to a different resource.\n * Threads with no resourceId are accessible to all (shared threads).\n */\nexport async function validateThreadOwnership(\n thread: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (thread && effectiveResourceId && thread.resourceId && thread.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: thread belongs to a different resource' });\n }\n}\n\n/**\n * Validates both coarse resource ownership and fine-grained thread access.\n * FGA enforcement is a no-op when no FGA provider is configured.\n */\nexport async function enforceThreadAccess({\n mastra,\n requestContext,\n threadId,\n thread,\n effectiveResourceId,\n permission = MastraFGAPermissions.MEMORY_READ,\n}: {\n mastra: any;\n requestContext?: RequestContext;\n threadId: string;\n thread?: { resourceId?: string | null } | null;\n effectiveResourceId?: string;\n permission?: MastraFGAPermissionInput;\n}): Promise<void> {\n await validateThreadOwnership(thread, effectiveResourceId);\n\n const fgaProvider = mastra?.getServer?.()?.fga;\n if (!fgaProvider) {\n return;\n }\n\n const user = requestContext?.get('user');\n if (!user || typeof user !== 'object') {\n throw new HTTPException(403, { message: 'FGA authorization denied: authenticated user is required' });\n }\n\n await MastraMemory.checkThreadFGA({\n mastra,\n user: user as { id: string; [key: string]: unknown },\n threadId,\n resourceId: thread?.resourceId ?? effectiveResourceId,\n requestContext,\n permission,\n });\n}\n\n/**\n * Validates that a workflow run belongs to the specified resourceId.\n * Throws 403 if the run exists but belongs to a different resource.\n */\nexport async function validateRunOwnership(\n run: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (run && effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,uBAAuB;CAC3B,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,aAAa;CACb,cAAc;CACd,eAAe;CACf,YAAY;CACZ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