@mastra/server 1.80.0-alpha.4 → 1.80.0-alpha.6

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 (184) hide show
  1. package/dist/{a2a-BUOtgjP-.cjs → a2a-3ykajvdu.cjs} +2 -2
  2. package/dist/{a2a-BUOtgjP-.cjs.map → a2a-3ykajvdu.cjs.map} +1 -1
  3. package/dist/{a2a-B2K45wEY.js → a2a-D6ajBqAA.js} +2 -2
  4. package/dist/{a2a-B2K45wEY.js.map → a2a-D6ajBqAA.js.map} +1 -1
  5. package/dist/{agent-builder-BEhoRLS_.js → agent-builder-BDHi4NOZ.js} +4 -4
  6. package/dist/{agent-builder-BEhoRLS_.js.map → agent-builder-BDHi4NOZ.js.map} +1 -1
  7. package/dist/{agent-builder-CTHPsm8d.cjs → agent-builder-D3WRvBAH.cjs} +4 -4
  8. package/dist/{agent-builder-CTHPsm8d.cjs.map → agent-builder-D3WRvBAH.cjs.map} +1 -1
  9. package/dist/{agents-vFpMvK3w.cjs → agents-Bs1GFnXz.cjs} +5 -2
  10. package/dist/{agents-vFpMvK3w.cjs.map → agents-Bs1GFnXz.cjs.map} +1 -1
  11. package/dist/{agents-DSZgApzs.js → agents-CiUW6yvl.js} +105 -14
  12. package/dist/agents-CiUW6yvl.js.map +1 -0
  13. package/dist/{agents-A-ahR0eQ.js → agents-Cl3KTHU4.js} +5 -2
  14. package/dist/{agents-A-ahR0eQ.js.map → agents-Cl3KTHU4.js.map} +1 -1
  15. package/dist/{agents-I0TVb_TM.cjs → agents-DBsmIR4c.cjs} +105 -14
  16. package/dist/agents-DBsmIR4c.cjs.map +1 -0
  17. package/dist/{api-schema-manifest-j2xurBb0.js → api-schema-manifest-C6MbIQch.js} +2 -2
  18. package/dist/{api-schema-manifest-j2xurBb0.js.map → api-schema-manifest-C6MbIQch.js.map} +1 -1
  19. package/dist/{api-schema-manifest-DCuGBEO0.cjs → api-schema-manifest-COH6PAvQ.cjs} +2 -2
  20. package/dist/{api-schema-manifest-DCuGBEO0.cjs.map → api-schema-manifest-COH6PAvQ.cjs.map} +1 -1
  21. package/dist/{background-tasks-BMVUFtVh.cjs → background-tasks-BMp9Q6SB.cjs} +2 -2
  22. package/dist/{background-tasks-BMVUFtVh.cjs.map → background-tasks-BMp9Q6SB.cjs.map} +1 -1
  23. package/dist/{background-tasks-CFkXHgyQ.js → background-tasks-DIpPsqVy.js} +2 -2
  24. package/dist/{background-tasks-CFkXHgyQ.js.map → background-tasks-DIpPsqVy.js.map} +1 -1
  25. package/dist/{conversations-BfBS1UwQ.js → conversations-Ce0dCZ23.js} +3 -3
  26. package/dist/{conversations-BfBS1UwQ.js.map → conversations-Ce0dCZ23.js.map} +1 -1
  27. package/dist/{conversations-BSYZlASE.cjs → conversations-RVdtAQEv.cjs} +3 -3
  28. package/dist/{conversations-BSYZlASE.cjs.map → conversations-RVdtAQEv.cjs.map} +1 -1
  29. package/dist/dist-C-L2kyKZ.js +1 -0
  30. package/dist/{dist-Cci9RRWj.cjs → dist-Clj7hRKz.cjs} +47 -69
  31. package/dist/dist-Clj7hRKz.cjs.map +1 -0
  32. package/dist/{dist-DJ3281Ve.cjs → dist-D6oS7RF1.cjs} +1 -1
  33. package/dist/{dist-bAoX6ick.js → dist-PlsLrwz8.js} +48 -70
  34. package/dist/dist-PlsLrwz8.js.map +1 -0
  35. package/dist/docs/SKILL.md +1 -1
  36. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  37. package/dist/{editor-builder-8li-nXor.cjs → editor-builder-9T1aGM2f.cjs} +2 -2
  38. package/dist/{editor-builder-8li-nXor.cjs.map → editor-builder-9T1aGM2f.cjs.map} +1 -1
  39. package/dist/{editor-builder-BXT6F3Hl.cjs → editor-builder-Bj_or9-c.cjs} +3 -3
  40. package/dist/{editor-builder-BXT6F3Hl.cjs.map → editor-builder-Bj_or9-c.cjs.map} +1 -1
  41. package/dist/{editor-builder-Bywazgj1.js → editor-builder-Cc0zrTC1.js} +3 -3
  42. package/dist/{editor-builder-Bywazgj1.js.map → editor-builder-Cc0zrTC1.js.map} +1 -1
  43. package/dist/{editor-builder-BCZy1ZH1.js → editor-builder-lzO2zecA.js} +2 -2
  44. package/dist/{editor-builder-BCZy1ZH1.js.map → editor-builder-lzO2zecA.js.map} +1 -1
  45. package/dist/{logs-Cbq2PiQG.js → logs-DIBh_xCk.js} +2 -2
  46. package/dist/{logs-Cbq2PiQG.js.map → logs-DIBh_xCk.js.map} +1 -1
  47. package/dist/{logs-BqHVVZBm.cjs → logs-NNur5jkf.cjs} +2 -2
  48. package/dist/{logs-BqHVVZBm.cjs.map → logs-NNur5jkf.cjs.map} +1 -1
  49. package/dist/{memory-CtSwODLV.js → memory-DeZ1je-b.js} +5 -6
  50. package/dist/memory-DeZ1je-b.js.map +1 -0
  51. package/dist/{memory-dujCippo.cjs → memory-Pj9P9vsl.cjs} +5 -6
  52. package/dist/memory-Pj9P9vsl.cjs.map +1 -0
  53. package/dist/{plans-CSLB_JKn.cjs → plans-Cu3zbWP_.cjs} +4 -4
  54. package/dist/{plans-CSLB_JKn.cjs.map → plans-Cu3zbWP_.cjs.map} +1 -1
  55. package/dist/{plans-DToC_H5z.js → plans-DVErlJoO.js} +4 -4
  56. package/dist/{plans-DToC_H5z.js.map → plans-DVErlJoO.js.map} +1 -1
  57. package/dist/{probe-image-size-CTKFNI9H.cjs → probe-image-size-C0psF6WM.cjs} +2 -2
  58. package/dist/{probe-image-size-CTKFNI9H.cjs.map → probe-image-size-C0psF6WM.cjs.map} +1 -1
  59. package/dist/{probe-image-size-DnRk0ecb.js → probe-image-size-CpV7slsd.js} +2 -2
  60. package/dist/{probe-image-size-DnRk0ecb.js.map → probe-image-size-CpV7slsd.js.map} +1 -1
  61. package/dist/{responses-w6B0iv_t.js → responses-DOqM_drh.js} +3 -3
  62. package/dist/{responses-w6B0iv_t.js.map → responses-DOqM_drh.js.map} +1 -1
  63. package/dist/{responses-OoIIZ1g6.cjs → responses-DniqbL1B.cjs} +3 -3
  64. package/dist/{responses-OoIIZ1g6.cjs.map → responses-DniqbL1B.cjs.map} +1 -1
  65. package/dist/{routes-KTxoRutQ.cjs → routes-B_-KRQOi.cjs} +16 -16
  66. package/dist/{routes-KTxoRutQ.cjs.map → routes-B_-KRQOi.cjs.map} +1 -1
  67. package/dist/{routes-CIjXlRu7.js → routes-BfQBQbwB.js} +16 -16
  68. package/dist/{routes-CIjXlRu7.js.map → routes-BfQBQbwB.js.map} +1 -1
  69. package/dist/{schedules-CSkQFQwy.cjs → schedules-CL4IU7kS.cjs} +2 -2
  70. package/dist/{schedules-CSkQFQwy.cjs.map → schedules-CL4IU7kS.cjs.map} +1 -1
  71. package/dist/{schedules-DfelziYe.js → schedules-CQPodXrR.js} +2 -2
  72. package/dist/{schedules-DfelziYe.js.map → schedules-CQPodXrR.js.map} +1 -1
  73. package/dist/{scores-FzL-bpCC.cjs → scores-BAZL_l3k.cjs} +2 -2
  74. package/dist/{scores-FzL-bpCC.cjs.map → scores-BAZL_l3k.cjs.map} +1 -1
  75. package/dist/{scores-PdRDQNaC.js → scores-BXrRHFvI.js} +2 -2
  76. package/dist/{scores-PdRDQNaC.js.map → scores-BXrRHFvI.js.map} +1 -1
  77. package/dist/server/handlers/a2a.cjs +1 -1
  78. package/dist/server/handlers/a2a.js +1 -1
  79. package/dist/server/handlers/agent-builder.cjs +1 -1
  80. package/dist/server/handlers/agent-builder.js +1 -1
  81. package/dist/server/handlers/agent-controller.cjs +14 -11
  82. package/dist/server/handlers/agent-controller.cjs.map +1 -1
  83. package/dist/server/handlers/agent-controller.d.ts +2 -0
  84. package/dist/server/handlers/agent-controller.d.ts.map +1 -1
  85. package/dist/server/handlers/agent-controller.js +14 -11
  86. package/dist/server/handlers/agent-controller.js.map +1 -1
  87. package/dist/server/handlers/agents.cjs +1 -1
  88. package/dist/server/handlers/agents.d.ts +2 -0
  89. package/dist/server/handlers/agents.d.ts.map +1 -1
  90. package/dist/server/handlers/agents.js +1 -1
  91. package/dist/server/handlers/background-tasks.cjs +1 -1
  92. package/dist/server/handlers/background-tasks.js +1 -1
  93. package/dist/server/handlers/conversations.cjs +1 -1
  94. package/dist/server/handlers/conversations.js +1 -1
  95. package/dist/server/handlers/editor-builder.cjs +1 -1
  96. package/dist/server/handlers/editor-builder.js +1 -1
  97. package/dist/server/handlers/error.cjs +1 -0
  98. package/dist/server/handlers/error.cjs.map +1 -1
  99. package/dist/server/handlers/error.d.ts.map +1 -1
  100. package/dist/server/handlers/error.js +1 -0
  101. package/dist/server/handlers/error.js.map +1 -1
  102. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  103. package/dist/server/handlers/favorites-enrichment.js +1 -1
  104. package/dist/server/handlers/logs.cjs +1 -1
  105. package/dist/server/handlers/logs.js +1 -1
  106. package/dist/server/handlers/memory.cjs +1 -1
  107. package/dist/server/handlers/memory.d.ts.map +1 -1
  108. package/dist/server/handlers/memory.js +1 -1
  109. package/dist/server/handlers/observability-new-endpoints.d.ts +2 -10
  110. package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
  111. package/dist/server/handlers/plans.cjs +1 -1
  112. package/dist/server/handlers/plans.js +1 -1
  113. package/dist/server/handlers/responses.cjs +1 -1
  114. package/dist/server/handlers/responses.js +1 -1
  115. package/dist/server/handlers/responses.storage.cjs +1 -1
  116. package/dist/server/handlers/responses.storage.js +1 -1
  117. package/dist/server/handlers/schedules.cjs +1 -1
  118. package/dist/server/handlers/schedules.js +1 -1
  119. package/dist/server/handlers/scores.cjs +1 -1
  120. package/dist/server/handlers/scores.js +1 -1
  121. package/dist/server/handlers/stored-agent-favorites.cjs +1 -1
  122. package/dist/server/handlers/stored-agent-favorites.js +1 -1
  123. package/dist/server/handlers/stored-agents.cjs +1 -1
  124. package/dist/server/handlers/stored-agents.js +1 -1
  125. package/dist/server/handlers/stored-skill-favorites.cjs +1 -1
  126. package/dist/server/handlers/stored-skill-favorites.js +1 -1
  127. package/dist/server/handlers/stored-skills.cjs +1 -1
  128. package/dist/server/handlers/stored-skills.js +1 -1
  129. package/dist/server/handlers/system.cjs +1 -1
  130. package/dist/server/handlers/system.js +1 -1
  131. package/dist/server/handlers/tools.cjs +1 -1
  132. package/dist/server/handlers/tools.js +1 -1
  133. package/dist/server/handlers/utils.cjs +2 -1
  134. package/dist/server/handlers/utils.d.ts +17 -2
  135. package/dist/server/handlers/utils.d.ts.map +1 -1
  136. package/dist/server/handlers/utils.js +1 -1
  137. package/dist/server/handlers/workflow-builder.cjs +1 -1
  138. package/dist/server/handlers/workflow-builder.js +1 -1
  139. package/dist/server/handlers/workflows.cjs +1 -1
  140. package/dist/server/handlers/workflows.d.ts.map +1 -1
  141. package/dist/server/handlers/workflows.js +1 -1
  142. package/dist/server/handlers/workspace.d.ts +23 -23
  143. package/dist/server/handlers.cjs +11 -11
  144. package/dist/server/handlers.js +11 -11
  145. package/dist/server/schemas/agents.d.ts +1 -0
  146. package/dist/server/schemas/agents.d.ts.map +1 -1
  147. package/dist/server/schemas/index.cjs +2 -2
  148. package/dist/server/schemas/index.js +2 -2
  149. package/dist/server/server-adapter/index.cjs +1 -1
  150. package/dist/server/server-adapter/index.js +1 -1
  151. package/dist/server/server-adapter/routes/observability.d.ts +1 -5
  152. package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
  153. package/dist/server/utils/agent-stream-events.d.ts +23 -0
  154. package/dist/server/utils/agent-stream-events.d.ts.map +1 -0
  155. package/dist/{tools-tMPXGAUO.js → tools-Do1uV_07.js} +5 -5
  156. package/dist/tools-Do1uV_07.js.map +1 -0
  157. package/dist/{tools-CottqeCZ.cjs → tools-HYYytfMx.cjs} +5 -5
  158. package/dist/tools-HYYytfMx.cjs.map +1 -0
  159. package/dist/{utils-1UlUJRyC.cjs → utils-BbYUI6Yn.cjs} +32 -7
  160. package/dist/utils-BbYUI6Yn.cjs.map +1 -0
  161. package/dist/{utils-DEwjGOpJ.js → utils-DHxjw4Tn.js} +27 -8
  162. package/dist/utils-DHxjw4Tn.js.map +1 -0
  163. package/dist/{workflow-builder-CJEajbkw.cjs → workflow-builder-DJKziSOo.cjs} +4 -4
  164. package/dist/{workflow-builder-CJEajbkw.cjs.map → workflow-builder-DJKziSOo.cjs.map} +1 -1
  165. package/dist/{workflow-builder-BcVfkods.js → workflow-builder-ezo8ZG1K.js} +4 -4
  166. package/dist/{workflow-builder-BcVfkods.js.map → workflow-builder-ezo8ZG1K.js.map} +1 -1
  167. package/dist/{workflows-CxPsDCnW.cjs → workflows-BWLDlaL9.cjs} +28 -28
  168. package/dist/workflows-BWLDlaL9.cjs.map +1 -0
  169. package/dist/{workflows-BjLruwQB.js → workflows-Dm2iK1nq.js} +28 -28
  170. package/dist/workflows-Dm2iK1nq.js.map +1 -0
  171. package/package.json +6 -6
  172. package/dist/agents-DSZgApzs.js.map +0 -1
  173. package/dist/agents-I0TVb_TM.cjs.map +0 -1
  174. package/dist/dist-Cci9RRWj.cjs.map +0 -1
  175. package/dist/dist-bAoX6ick.js.map +0 -1
  176. package/dist/dist-t_05BTrR.js +0 -1
  177. package/dist/memory-CtSwODLV.js.map +0 -1
  178. package/dist/memory-dujCippo.cjs.map +0 -1
  179. package/dist/tools-CottqeCZ.cjs.map +0 -1
  180. package/dist/tools-tMPXGAUO.js.map +0 -1
  181. package/dist/utils-1UlUJRyC.cjs.map +0 -1
  182. package/dist/utils-DEwjGOpJ.js.map +0 -1
  183. package/dist/workflows-BjLruwQB.js.map +0 -1
  184. package/dist/workflows-CxPsDCnW.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-Do1uV_07.js","names":[],"sources":["../src/server/handlers/tools.ts"],"sourcesContent":["import { isVercelTool, isProviderDefinedTool } from '@mastra/core/tools';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '@mastra/schema-compat/schema';\nimport type { PublicSchema } from '@mastra/schema-compat/schema';\nimport { stringify } from 'superjson';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\nimport {\n executeToolContextBodySchema,\n executeToolResponseSchema,\n listToolsResponseSchema,\n serializedToolSchema,\n toolIdPathParams,\n agentToolPathParams,\n executeToolBodySchema,\n} from '../schemas/agents';\nimport { optionalRunIdSchema } from '../schemas/common';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { getAgentFromSystem } from './agents';\nimport { handleError } from './error';\nimport { stripInjectedToolOverrideFields } from './tool-schema-overrides';\nimport { getHandlerFGAProvider, validateBody } from './utils';\n\n/**\n * Resolves a schema that may be a lazy function (e.g. AI SDK provider tools).\n * Recursively resolves until a non-function value is returned.\n * Skips functions that are themselves valid schemas (e.g. ArkType types are\n * callable but also implement StandardSchema via ~standard).\n */\nfunction resolveLazySchema(schema: unknown): unknown {\n if (typeof schema === 'function' && !('~standard' in schema)) {\n return resolveLazySchema(schema());\n }\n return schema;\n}\n\nfunction schemaToJsonSchema(schema: PublicSchema<unknown> | undefined) {\n if (!schema) {\n return undefined;\n }\n\n return standardSchemaToJSONSchema(toStandardSchema(schema), { target: 'draft-2020-12' });\n}\n\nfunction serializeSchema(schema: unknown, options?: { stripInjectedOverrides?: boolean }): string | undefined {\n const jsonSchema = schemaToJsonSchema(resolveLazySchema(schema) as PublicSchema<unknown> | undefined);\n if (jsonSchema === undefined) return undefined;\n return stringify(options?.stripInjectedOverrides ? stripInjectedToolOverrideFields(jsonSchema) : jsonSchema);\n}\n\n/**\n * Searches dynamically-resolved agent tools (provided via `toolsResolver` /\n * function-based `tools`) for a tool with the given id. Used as a fallback\n * after the static tool registry (`registeredTools` + `mastra.getToolById`)\n * misses, so global tool routes can resolve tools that only exist on agents.\n *\n * Errors thrown by an individual agent's `listTools()` are logged and\n * skipped so a single broken resolver doesn't take down the whole lookup.\n */\nasync function findToolInAgents(mastra: any, toolId: string, requestContext: any): Promise<any | undefined> {\n const agents = mastra.listAgents() || {};\n for (const agent of Object.values(agents) as any[]) {\n try {\n const agentTools = await agent.listTools({ requestContext });\n const found = Object.values(agentTools || {}).find((t: any) => t.id === toolId);\n if (found) return found;\n } catch (error) {\n mastra.getLogger?.()?.warn?.('Failed to list tools for agent while resolving tool by id', {\n agentId: agent?.id,\n toolId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return undefined;\n}\n\n/**\n * Serializes a tool for API responses, handling both regular tools (with Zod schemas)\n * and provider-defined tools (with AI SDK lazy schemas).\n */\nfunction serializeTool(tool: any): any {\n // Provider-defined tools (e.g. google.tools.googleSearch(), openai.tools.webSearch())\n // have lazy inputSchema functions that return AI SDK Schema objects, not Zod schemas.\n // We resolve them and use the jsonSchema property directly.\n if (isProviderDefinedTool(tool)) {\n const resolvedInput = resolveLazySchema(tool.inputSchema);\n const resolvedOutput = resolveLazySchema(tool.outputSchema);\n return {\n ...tool,\n inputSchema:\n resolvedInput && typeof resolvedInput === 'object' && 'jsonSchema' in resolvedInput\n ? stringify(resolvedInput.jsonSchema)\n : undefined,\n outputSchema:\n resolvedOutput && typeof resolvedOutput === 'object' && 'jsonSchema' in resolvedOutput\n ? stringify(resolvedOutput.jsonSchema)\n : undefined,\n };\n }\n\n return {\n ...tool,\n inputSchema: serializeSchema(tool.inputSchema, { stripInjectedOverrides: true }),\n outputSchema: serializeSchema(tool.outputSchema),\n requestContextSchema: serializeSchema(tool.requestContextSchema),\n };\n}\n\n// ============================================================================\n// Route Definitions (new pattern - handlers defined inline with createRoute)\n// ============================================================================\n\nexport const LIST_TOOLS_ROUTE = createRoute({\n method: 'GET',\n path: '/tools',\n responseType: 'json',\n responseSchema: listToolsResponseSchema,\n summary: 'List all tools',\n description: 'Returns a list of all available tools in the system',\n tags: ['Tools'],\n requiresAuth: true,\n handler: async ({ mastra, registeredTools, requestContext }) => {\n try {\n // Merge tools from two sources: mastra.listTools() includes dynamically created tools\n // (e.g. MCP tools, or agent tools registered by their intrinsic id), while registeredTools\n // includes tools discovered by the CLI bundler (keyed by export name).\n //\n // The same tool instance can appear in both maps under different keys (e.g. an agent\n // registers it by `tool.id` while the bundler registers it by export name). Dedupe by\n // `tool.id`, preferring the registeredTools (bundler) key, so each tool appears once.\n const registered = registeredTools && Object.keys(registeredTools).length > 0 ? registeredTools : {};\n\n const allTools: Record<string, any> = {};\n const seenToolIds = new Map<string, string>();\n\n // registeredTools first so their key wins for a given tool.id.\n for (const [key, tool] of Object.entries(registered)) {\n const toolId = typeof (tool as any)?.id === 'string' ? (tool as any).id : undefined;\n if (toolId !== undefined) seenToolIds.set(toolId, key);\n allTools[key] = tool;\n }\n\n for (const [key, tool] of Object.entries(mastra.listTools() ?? {})) {\n const toolId = typeof (tool as any)?.id === 'string' ? (tool as any).id : undefined;\n // Skip if this exact tool.id was already registered (under any key) by registeredTools.\n if (toolId !== undefined && seenToolIds.has(toolId)) continue;\n if (toolId !== undefined) seenToolIds.set(toolId, key);\n allTools[key] = tool;\n }\n\n const serializedTools = Object.entries(allTools).reduce<Record<string, any>>((acc, [id, _tool]) => {\n acc[id] = serializeTool(_tool);\n return acc;\n }, {});\n\n // Filter tools by FGA if configured\n const fgaProvider = getHandlerFGAProvider(mastra, requestContext);\n const user = requestContext?.get('user');\n if (fgaProvider && user) {\n const toolList = Object.entries(serializedTools).map(([id, t]) => ({ id, ...t }));\n const accessible = await fgaProvider.filterAccessible(user, toolList, 'tool', MastraFGAPermissions.TOOLS_READ);\n const accessibleSet = new Set(accessible.map((t: any) => t.id));\n for (const id of Object.keys(serializedTools)) {\n if (!accessibleSet.has(id)) {\n delete serializedTools[id];\n }\n }\n }\n\n return serializedTools;\n } catch (error) {\n return handleError(error, 'Error getting tools');\n }\n },\n});\n\nexport const GET_TOOL_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/tools/:toolId',\n responseType: 'json',\n pathParamSchema: toolIdPathParams,\n responseSchema: serializedToolSchema,\n summary: 'Get tool by ID',\n description: 'Returns details for a specific tool including its schema and configuration',\n tags: ['Tools'],\n requiresAuth: true,\n handler: async ({ mastra, registeredTools, toolId, requestContext }) => {\n try {\n let tool: any;\n\n // Try explicit registeredTools first, then fallback to mastra\n if (registeredTools && Object.keys(registeredTools).length > 0) {\n tool = Object.values(registeredTools).find((t: any) => t.id === toolId);\n }\n if (!tool) {\n try {\n tool = mastra.getToolById(toolId);\n } catch {\n // tool not found in global registry, continue to agent fallback\n }\n }\n\n // Fallback: search dynamically-resolved agent tools (toolsResolver)\n if (!tool) {\n tool = await findToolInAgents(mastra, toolId, requestContext);\n }\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n return serializeTool(tool);\n } catch (error) {\n return handleError(error, 'Error getting tool');\n }\n },\n});\n\nexport const EXECUTE_TOOL_ROUTE = createRoute({\n method: 'POST',\n path: '/tools/:toolId/execute',\n responseType: 'json',\n pathParamSchema: toolIdPathParams,\n queryParamSchema: optionalRunIdSchema,\n bodySchema: executeToolContextBodySchema,\n responseSchema: executeToolResponseSchema,\n summary: 'Execute tool',\n description: 'Executes a specific tool with the provided input data',\n tags: ['Tools'],\n requiresAuth: true,\n handler: async ({ mastra, runId, toolId, registeredTools, requestContext, ...bodyParams }) => {\n try {\n if (!toolId) {\n throw new HTTPException(400, { message: 'Tool ID is required' });\n }\n\n let tool: any;\n\n // Try explicit registeredTools first, then fallback to mastra\n if (registeredTools && Object.keys(registeredTools).length > 0) {\n tool = Object.values(registeredTools).find((t: any) => t.id === toolId);\n }\n if (!tool) {\n try {\n tool = mastra.getToolById(toolId);\n } catch {\n // tool not found in global registry, continue to agent fallback\n }\n }\n\n // Fallback: search dynamically-resolved agent tools (toolsResolver)\n if (!tool) {\n tool = await findToolInAgents(mastra, toolId, requestContext);\n }\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n if (!tool?.execute) {\n throw new HTTPException(400, { message: 'Tool is not executable' });\n }\n\n const { data } = bodyParams;\n\n validateBody({ data });\n\n let result;\n if (isVercelTool(tool)) {\n result = await (tool as any).execute(data);\n } else {\n result = await tool.execute(data!, {\n mastra,\n requestContext,\n // TODO: Pass proper tracing context when server API supports tracing\n tracingContext: { currentSpan: undefined },\n ...(runId\n ? {\n workflow: {\n runId,\n suspend: async () => {},\n },\n }\n : {}),\n });\n }\n\n return result;\n } catch (error) {\n return handleError(error, 'Error executing tool');\n }\n },\n});\n\n// ============================================================================\n// Agent Tool Routes\n// ============================================================================\n\nexport const GET_AGENT_TOOL_ROUTE = createRoute({\n method: 'GET',\n path: '/agents/:agentId/tools/:toolId',\n responseType: 'json',\n pathParamSchema: agentToolPathParams,\n responseSchema: serializedToolSchema,\n summary: 'Get agent tool',\n description: 'Returns details for a specific tool assigned to the agent',\n tags: ['Agents', 'Tools'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, toolId, requestContext }) => {\n try {\n if (!agentId) {\n throw new HTTPException(400, { message: 'Agent ID is required' });\n }\n const agent = await getAgentFromSystem({ mastra, agentId });\n\n const agentTools = await agent.listTools({ requestContext });\n\n const tool = Object.values(agentTools || {}).find((tool: any) => tool.id === toolId) as any;\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n return serializeTool(tool);\n } catch (error) {\n return handleError(error, 'Error getting agent tool');\n }\n },\n});\n\nexport const EXECUTE_AGENT_TOOL_ROUTE = createRoute({\n method: 'POST',\n path: '/agents/:agentId/tools/:toolId/execute',\n responseType: 'json',\n pathParamSchema: agentToolPathParams,\n bodySchema: executeToolBodySchema,\n responseSchema: executeToolResponseSchema,\n summary: 'Execute agent tool',\n description: 'Executes a specific tool assigned to the agent with the provided input data',\n tags: ['Agents', 'Tools'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, toolId, data, requestContext }) => {\n try {\n if (!agentId) {\n throw new HTTPException(400, { message: 'Agent ID is required' });\n }\n const agent = await getAgentFromSystem({ mastra, agentId });\n\n const agentTools = await agent.listTools({ requestContext });\n\n const tool = Object.values(agentTools || {}).find((tool: any) => tool.id === toolId) as any;\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n if (!tool?.execute) {\n throw new HTTPException(400, { message: 'Tool is not executable' });\n }\n\n const result = await tool.execute(data, {\n mastra,\n requestContext,\n // TODO: Pass proper tracing context when server API supports tracing\n tracingContext: { currentSpan: undefined },\n });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error executing agent tool');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,kBAAkB,QAA0B;CACnD,IAAI,OAAO,WAAW,cAAc,EAAE,eAAe,SACnD,OAAO,kBAAkB,OAAO,CAAC;CAEnC,OAAO;AACT;AAEA,SAAS,mBAAmB,QAA2C;CACrE,IAAI,CAAC,QACH;CAGF,OAAO,2BAA2B,iBAAiB,MAAM,GAAG,EAAE,QAAQ,gBAAgB,CAAC;AACzF;AAEA,SAAS,gBAAgB,QAAiB,SAAoE;CAC5G,MAAM,aAAa,mBAAmB,kBAAkB,MAAM,CAAsC;CACpG,IAAI,eAAe,KAAA,GAAW,OAAO,KAAA;CACrC,OAAO,UAAU,SAAS,yBAAyB,gCAAgC,UAAU,IAAI,UAAU;AAC7G;;;;;;;;;;AAWA,eAAe,iBAAiB,QAAa,QAAgB,gBAA+C;CAC1G,MAAM,SAAS,OAAO,WAAW,KAAK,CAAC;CACvC,KAAK,MAAM,SAAS,OAAO,OAAO,MAAM,GACtC,IAAI;EACF,MAAM,aAAa,MAAM,MAAM,UAAU,EAAE,eAAe,CAAC;EAC3D,MAAM,QAAQ,OAAO,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,MAAM,MAAW,EAAE,OAAO,MAAM;EAC9E,IAAI,OAAO,OAAO;CACpB,SAAS,OAAO;EACd,OAAO,YAAY,CAAC,EAAE,OAAO,6DAA6D;GACxF,SAAS,OAAO;GAChB;GACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;AAGJ;;;;;AAMA,SAAS,cAAc,MAAgB;CAIrC,IAAI,sBAAsB,IAAI,GAAG;EAC/B,MAAM,gBAAgB,kBAAkB,KAAK,WAAW;EACxD,MAAM,iBAAiB,kBAAkB,K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,iBAAiB,CAAC;GAG5D,IAAI,CAAC,MAAM,SACT,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,yBAAyB,CAAC;GAUpE,OAAO,MAPc,KAAK,QAAQ,MAAM;IACtC;IACA;IAEA,gBAAgB,EAAE,aAAa,KAAA,EAAU;GAC3C,CAAC;EAGH,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,4BAA4B;EACxD;CACF;AACF,CAAC"}
@@ -1,14 +1,14 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-10nMEhjP.cjs");
2
2
  const require_http_exception = require("./http-exception-Co3MbFUf.cjs");
3
3
  const require_common = require("./common-DVZqSEhZ.cjs");
4
- const require_agents = require("./agents-vFpMvK3w.cjs");
4
+ const require_agents = require("./agents-Bs1GFnXz.cjs");
5
5
  const require_schema_Bf12g7KC = require("./schema-Bf12g7KC-plP4Ir6h.cjs");
6
6
  const require_route_builder = require("./route-builder-CvARmqnA.cjs");
7
7
  const require_utils = require("./utils-BnH77wPf.cjs");
8
8
  const require_server_handlers_error = require("./server/handlers/error.cjs");
9
- const require_utils$1 = require("./utils-1UlUJRyC.cjs");
9
+ const require_utils$1 = require("./utils-BbYUI6Yn.cjs");
10
+ const require_agents$1 = require("./agents-DBsmIR4c.cjs");
10
11
  const require_server_handlers_tool_schema_overrides = require("./server/handlers/tool-schema-overrides.cjs");
11
- const require_agents$1 = require("./agents-I0TVb_TM.cjs");
12
12
  let _mastra_core_tools = require("@mastra/core/tools");
13
13
  // src/server/handlers/tools.ts
14
14
  var tools_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
@@ -110,7 +110,7 @@ const LIST_TOOLS_ROUTE = require_route_builder.createRoute({
110
110
  acc[id] = serializeTool(_tool);
111
111
  return acc;
112
112
  }, {});
113
- const fgaProvider = mastra.getServer?.()?.fga;
113
+ const fgaProvider = require_utils$1.getHandlerFGAProvider(mastra, requestContext);
114
114
  const user = requestContext?.get("user");
115
115
  if (fgaProvider && user) {
116
116
  const toolList = Object.entries(serializedTools).map(([id, t]) => ({
@@ -287,4 +287,4 @@ Object.defineProperty(exports, "tools_exports", {
287
287
  }
288
288
  });
289
289
 
290
- //# sourceMappingURL=tools-CottqeCZ.cjs.map
290
+ //# sourceMappingURL=tools-HYYytfMx.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-HYYytfMx.cjs","names":["standardSchemaToJSONSchema","toStandardSchema","stringify","stripInjectedToolOverrideFields","isProviderDefinedTool","createRoute","listToolsResponseSchema","getHandlerFGAProvider","MastraFGAPermissions","handleError","toolIdPathParams","serializedToolSchema","HTTPException","optionalRunIdSchema","executeToolContextBodySchema","executeToolResponseSchema","isVercelTool","agentToolPathParams","getAgentFromSystem","executeToolBodySchema"],"sources":["../src/server/handlers/tools.ts"],"sourcesContent":["import { isVercelTool, isProviderDefinedTool } from '@mastra/core/tools';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '@mastra/schema-compat/schema';\nimport type { PublicSchema } from '@mastra/schema-compat/schema';\nimport { stringify } from 'superjson';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\nimport {\n executeToolContextBodySchema,\n executeToolResponseSchema,\n listToolsResponseSchema,\n serializedToolSchema,\n toolIdPathParams,\n agentToolPathParams,\n executeToolBodySchema,\n} from '../schemas/agents';\nimport { optionalRunIdSchema } from '../schemas/common';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { getAgentFromSystem } from './agents';\nimport { handleError } from './error';\nimport { stripInjectedToolOverrideFields } from './tool-schema-overrides';\nimport { getHandlerFGAProvider, validateBody } from './utils';\n\n/**\n * Resolves a schema that may be a lazy function (e.g. AI SDK provider tools).\n * Recursively resolves until a non-function value is returned.\n * Skips functions that are themselves valid schemas (e.g. ArkType types are\n * callable but also implement StandardSchema via ~standard).\n */\nfunction resolveLazySchema(schema: unknown): unknown {\n if (typeof schema === 'function' && !('~standard' in schema)) {\n return resolveLazySchema(schema());\n }\n return schema;\n}\n\nfunction schemaToJsonSchema(schema: PublicSchema<unknown> | undefined) {\n if (!schema) {\n return undefined;\n }\n\n return standardSchemaToJSONSchema(toStandardSchema(schema), { target: 'draft-2020-12' });\n}\n\nfunction serializeSchema(schema: unknown, options?: { stripInjectedOverrides?: boolean }): string | undefined {\n const jsonSchema = schemaToJsonSchema(resolveLazySchema(schema) as PublicSchema<unknown> | undefined);\n if (jsonSchema === undefined) return undefined;\n return stringify(options?.stripInjectedOverrides ? stripInjectedToolOverrideFields(jsonSchema) : jsonSchema);\n}\n\n/**\n * Searches dynamically-resolved agent tools (provided via `toolsResolver` /\n * function-based `tools`) for a tool with the given id. Used as a fallback\n * after the static tool registry (`registeredTools` + `mastra.getToolById`)\n * misses, so global tool routes can resolve tools that only exist on agents.\n *\n * Errors thrown by an individual agent's `listTools()` are logged and\n * skipped so a single broken resolver doesn't take down the whole lookup.\n */\nasync function findToolInAgents(mastra: any, toolId: string, requestContext: any): Promise<any | undefined> {\n const agents = mastra.listAgents() || {};\n for (const agent of Object.values(agents) as any[]) {\n try {\n const agentTools = await agent.listTools({ requestContext });\n const found = Object.values(agentTools || {}).find((t: any) => t.id === toolId);\n if (found) return found;\n } catch (error) {\n mastra.getLogger?.()?.warn?.('Failed to list tools for agent while resolving tool by id', {\n agentId: agent?.id,\n toolId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return undefined;\n}\n\n/**\n * Serializes a tool for API responses, handling both regular tools (with Zod schemas)\n * and provider-defined tools (with AI SDK lazy schemas).\n */\nfunction serializeTool(tool: any): any {\n // Provider-defined tools (e.g. google.tools.googleSearch(), openai.tools.webSearch())\n // have lazy inputSchema functions that return AI SDK Schema objects, not Zod schemas.\n // We resolve them and use the jsonSchema property directly.\n if (isProviderDefinedTool(tool)) {\n const resolvedInput = resolveLazySchema(tool.inputSchema);\n const resolvedOutput = resolveLazySchema(tool.outputSchema);\n return {\n ...tool,\n inputSchema:\n resolvedInput && typeof resolvedInput === 'object' && 'jsonSchema' in resolvedInput\n ? stringify(resolvedInput.jsonSchema)\n : undefined,\n outputSchema:\n resolvedOutput && typeof resolvedOutput === 'object' && 'jsonSchema' in resolvedOutput\n ? stringify(resolvedOutput.jsonSchema)\n : undefined,\n };\n }\n\n return {\n ...tool,\n inputSchema: serializeSchema(tool.inputSchema, { stripInjectedOverrides: true }),\n outputSchema: serializeSchema(tool.outputSchema),\n requestContextSchema: serializeSchema(tool.requestContextSchema),\n };\n}\n\n// ============================================================================\n// Route Definitions (new pattern - handlers defined inline with createRoute)\n// ============================================================================\n\nexport const LIST_TOOLS_ROUTE = createRoute({\n method: 'GET',\n path: '/tools',\n responseType: 'json',\n responseSchema: listToolsResponseSchema,\n summary: 'List all tools',\n description: 'Returns a list of all available tools in the system',\n tags: ['Tools'],\n requiresAuth: true,\n handler: async ({ mastra, registeredTools, requestContext }) => {\n try {\n // Merge tools from two sources: mastra.listTools() includes dynamically created tools\n // (e.g. MCP tools, or agent tools registered by their intrinsic id), while registeredTools\n // includes tools discovered by the CLI bundler (keyed by export name).\n //\n // The same tool instance can appear in both maps under different keys (e.g. an agent\n // registers it by `tool.id` while the bundler registers it by export name). Dedupe by\n // `tool.id`, preferring the registeredTools (bundler) key, so each tool appears once.\n const registered = registeredTools && Object.keys(registeredTools).length > 0 ? registeredTools : {};\n\n const allTools: Record<string, any> = {};\n const seenToolIds = new Map<string, string>();\n\n // registeredTools first so their key wins for a given tool.id.\n for (const [key, tool] of Object.entries(registered)) {\n const toolId = typeof (tool as any)?.id === 'string' ? (tool as any).id : undefined;\n if (toolId !== undefined) seenToolIds.set(toolId, key);\n allTools[key] = tool;\n }\n\n for (const [key, tool] of Object.entries(mastra.listTools() ?? {})) {\n const toolId = typeof (tool as any)?.id === 'string' ? (tool as any).id : undefined;\n // Skip if this exact tool.id was already registered (under any key) by registeredTools.\n if (toolId !== undefined && seenToolIds.has(toolId)) continue;\n if (toolId !== undefined) seenToolIds.set(toolId, key);\n allTools[key] = tool;\n }\n\n const serializedTools = Object.entries(allTools).reduce<Record<string, any>>((acc, [id, _tool]) => {\n acc[id] = serializeTool(_tool);\n return acc;\n }, {});\n\n // Filter tools by FGA if configured\n const fgaProvider = getHandlerFGAProvider(mastra, requestContext);\n const user = requestContext?.get('user');\n if (fgaProvider && user) {\n const toolList = Object.entries(serializedTools).map(([id, t]) => ({ id, ...t }));\n const accessible = await fgaProvider.filterAccessible(user, toolList, 'tool', MastraFGAPermissions.TOOLS_READ);\n const accessibleSet = new Set(accessible.map((t: any) => t.id));\n for (const id of Object.keys(serializedTools)) {\n if (!accessibleSet.has(id)) {\n delete serializedTools[id];\n }\n }\n }\n\n return serializedTools;\n } catch (error) {\n return handleError(error, 'Error getting tools');\n }\n },\n});\n\nexport const GET_TOOL_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/tools/:toolId',\n responseType: 'json',\n pathParamSchema: toolIdPathParams,\n responseSchema: serializedToolSchema,\n summary: 'Get tool by ID',\n description: 'Returns details for a specific tool including its schema and configuration',\n tags: ['Tools'],\n requiresAuth: true,\n handler: async ({ mastra, registeredTools, toolId, requestContext }) => {\n try {\n let tool: any;\n\n // Try explicit registeredTools first, then fallback to mastra\n if (registeredTools && Object.keys(registeredTools).length > 0) {\n tool = Object.values(registeredTools).find((t: any) => t.id === toolId);\n }\n if (!tool) {\n try {\n tool = mastra.getToolById(toolId);\n } catch {\n // tool not found in global registry, continue to agent fallback\n }\n }\n\n // Fallback: search dynamically-resolved agent tools (toolsResolver)\n if (!tool) {\n tool = await findToolInAgents(mastra, toolId, requestContext);\n }\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n return serializeTool(tool);\n } catch (error) {\n return handleError(error, 'Error getting tool');\n }\n },\n});\n\nexport const EXECUTE_TOOL_ROUTE = createRoute({\n method: 'POST',\n path: '/tools/:toolId/execute',\n responseType: 'json',\n pathParamSchema: toolIdPathParams,\n queryParamSchema: optionalRunIdSchema,\n bodySchema: executeToolContextBodySchema,\n responseSchema: executeToolResponseSchema,\n summary: 'Execute tool',\n description: 'Executes a specific tool with the provided input data',\n tags: ['Tools'],\n requiresAuth: true,\n handler: async ({ mastra, runId, toolId, registeredTools, requestContext, ...bodyParams }) => {\n try {\n if (!toolId) {\n throw new HTTPException(400, { message: 'Tool ID is required' });\n }\n\n let tool: any;\n\n // Try explicit registeredTools first, then fallback to mastra\n if (registeredTools && Object.keys(registeredTools).length > 0) {\n tool = Object.values(registeredTools).find((t: any) => t.id === toolId);\n }\n if (!tool) {\n try {\n tool = mastra.getToolById(toolId);\n } catch {\n // tool not found in global registry, continue to agent fallback\n }\n }\n\n // Fallback: search dynamically-resolved agent tools (toolsResolver)\n if (!tool) {\n tool = await findToolInAgents(mastra, toolId, requestContext);\n }\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n if (!tool?.execute) {\n throw new HTTPException(400, { message: 'Tool is not executable' });\n }\n\n const { data } = bodyParams;\n\n validateBody({ data });\n\n let result;\n if (isVercelTool(tool)) {\n result = await (tool as any).execute(data);\n } else {\n result = await tool.execute(data!, {\n mastra,\n requestContext,\n // TODO: Pass proper tracing context when server API supports tracing\n tracingContext: { currentSpan: undefined },\n ...(runId\n ? {\n workflow: {\n runId,\n suspend: async () => {},\n },\n }\n : {}),\n });\n }\n\n return result;\n } catch (error) {\n return handleError(error, 'Error executing tool');\n }\n },\n});\n\n// ============================================================================\n// Agent Tool Routes\n// ============================================================================\n\nexport const GET_AGENT_TOOL_ROUTE = createRoute({\n method: 'GET',\n path: '/agents/:agentId/tools/:toolId',\n responseType: 'json',\n pathParamSchema: agentToolPathParams,\n responseSchema: serializedToolSchema,\n summary: 'Get agent tool',\n description: 'Returns details for a specific tool assigned to the agent',\n tags: ['Agents', 'Tools'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, toolId, requestContext }) => {\n try {\n if (!agentId) {\n throw new HTTPException(400, { message: 'Agent ID is required' });\n }\n const agent = await getAgentFromSystem({ mastra, agentId });\n\n const agentTools = await agent.listTools({ requestContext });\n\n const tool = Object.values(agentTools || {}).find((tool: any) => tool.id === toolId) as any;\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n return serializeTool(tool);\n } catch (error) {\n return handleError(error, 'Error getting agent tool');\n }\n },\n});\n\nexport const EXECUTE_AGENT_TOOL_ROUTE = createRoute({\n method: 'POST',\n path: '/agents/:agentId/tools/:toolId/execute',\n responseType: 'json',\n pathParamSchema: agentToolPathParams,\n bodySchema: executeToolBodySchema,\n responseSchema: executeToolResponseSchema,\n summary: 'Execute agent tool',\n description: 'Executes a specific tool assigned to the agent with the provided input data',\n tags: ['Agents', 'Tools'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, toolId, data, requestContext }) => {\n try {\n if (!agentId) {\n throw new HTTPException(400, { message: 'Agent ID is required' });\n }\n const agent = await getAgentFromSystem({ mastra, agentId });\n\n const agentTools = await agent.listTools({ requestContext });\n\n const tool = Object.values(agentTools || {}).find((tool: any) => tool.id === toolId) as any;\n\n if (!tool) {\n throw new HTTPException(404, { message: 'Tool not found' });\n }\n\n if (!tool?.execute) {\n throw new HTTPException(400, { message: 'Tool is not executable' });\n }\n\n const result = await tool.execute(data, {\n mastra,\n requestContext,\n // TODO: Pass proper tracing context when server API supports tracing\n tracingContext: { currentSpan: undefined },\n });\n\n return result;\n } catch (error) {\n return handleError(error, 'Error executing agent tool');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,kBAAkB,QAA0B;CACnD,IAAI,OAAO,WAAW,cAAc,EAAE,eAAe,SACnD,OAAO,kBAAkB,OAAO,CAAC;CAEnC,OAAO;AACT;AAEA,SAAS,mBAAmB,QAA2C;CACrE,IAAI,CAAC,QACH;CAGF,OAAOA,wBAAAA,2BAA2BC,wBAAAA,iBAAiB,MAAM,GAAG,EAAE,QAAQ,gBAAgB,CAAC;AACzF;AAEA,SAAS,gBAAgB,QAAiB,SAAoE;CAC5G,MAAM,aAAa,mBAAmB,kBAAkB,MAAM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AC;GAUpE,OAAO,MAPc,KAAK,QAAQ,MAAM;IACtC;IACA;IAEA,gBAAgB,EAAE,aAAa,KAAA,EAAU;GAC3C,CAAC;EAGH,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,4BAA4B;EACxD;CACF;AACF,CAAC"}
@@ -62,6 +62,24 @@ function getPublicWorkflowById(mastra, workflowId) {
62
62
  const workflows = mastra.listWorkflows();
63
63
  return Object.values(workflows).find((workflow) => workflow.id === workflowId) ?? (Object.hasOwn(workflows, workflowId) ? workflows[workflowId] : void 0);
64
64
  }
65
+ /**
66
+ * Resolves the FGA provider a handler should use for this request, following
67
+ * the same auth-mode-aware selection as the route-level checks: Studio auth
68
+ * requests use `studio.fga` when it is configured, and everything else uses
69
+ * `server.fga`.
70
+ *
71
+ * Returns `undefined` when FGA is not configured at all. When FGA is
72
+ * configured but no provider applies to this request (for example `studio.fga`
73
+ * is set and the request used server auth), the request is denied rather than
74
+ * treated as unrestricted.
75
+ */
76
+ function getHandlerFGAProvider(mastra, requestContext) {
77
+ const studioFga = mastra?.getStudio?.()?.fga;
78
+ const serverFga = mastra?.getServer?.()?.fga;
79
+ if (requestContext?.get("mastra__authMode") === "studio" && studioFga) return studioFga;
80
+ if (serverFga) return serverFga;
81
+ if (studioFga) throw new require_http_exception.HTTPException(403, { message: "Access denied: no FGA provider is configured for this request" });
82
+ }
65
83
  function validateBody(body) {
66
84
  const errorResponse = Object.entries(body).reduce((acc, [key, value]) => {
67
85
  if (!value) acc[key] = `Argument "${key}" is required`;
@@ -193,7 +211,8 @@ async function validateThreadOwnership(thread, effectiveResourceId) {
193
211
  */
194
212
  async function enforceThreadAccess({ mastra, requestContext, threadId, thread, effectiveResourceId, permission = MastraFGAPermissions.MEMORY_READ }) {
195
213
  await validateThreadOwnership(thread, effectiveResourceId);
196
- if (!mastra?.getServer?.()?.fga) return;
214
+ const fgaProvider = getHandlerFGAProvider(mastra, requestContext);
215
+ if (!fgaProvider) return;
197
216
  const user = requestContext?.get("user");
198
217
  if (!user || typeof user !== "object") throw new require_http_exception.HTTPException(403, { message: "FGA authorization denied: authenticated user is required" });
199
218
  await _mastra_core_memory.MastraMemory.checkThreadFGA({
@@ -202,7 +221,8 @@ async function enforceThreadAccess({ mastra, requestContext, threadId, thread, e
202
221
  threadId,
203
222
  resourceId: thread?.resourceId ?? effectiveResourceId,
204
223
  requestContext,
205
- permission
224
+ permission,
225
+ fgaProvider
206
226
  });
207
227
  }
208
228
  /**
@@ -215,10 +235,9 @@ async function enforceThreadAccess({ mastra, requestContext, threadId, thread, e
215
235
  * an FGA provider authorizes the route; otherwise it is refused rather than granted implicitly,
216
236
  * as on the thread-transfer route.
217
237
  */
218
- async function validateRunOwnership(run, effectiveResourceId, mastra) {
238
+ async function validateRunOwnership(run, effectiveResourceId, mastra, requestContext) {
219
239
  if (!run) return;
220
- const server = mastra?.getServer?.();
221
- if (!(typeof (server?.auth)?.mapUserToResourceId === "function")) {
240
+ if (!(typeof ((mastra?.getServer?.())?.auth)?.mapUserToResourceId === "function")) {
222
241
  if (effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) throw new require_http_exception.HTTPException(403, { message: "Access denied: workflow run belongs to a different resource" });
223
242
  return;
224
243
  }
@@ -226,7 +245,7 @@ async function validateRunOwnership(run, effectiveResourceId, mastra) {
226
245
  if (run.resourceId !== effectiveResourceId) throw new require_http_exception.HTTPException(403, { message: "Access denied: workflow run belongs to a different resource" });
227
246
  return;
228
247
  }
229
- if (!server?.fga) throw new require_http_exception.HTTPException(403, { message: "Access denied: unscoped workflow run access requires explicit authorization. Configure an FGA provider to authorize privileged run access." });
248
+ if (!getHandlerFGAProvider(mastra, requestContext)) throw new require_http_exception.HTTPException(403, { message: "Access denied: unscoped workflow run access requires explicit authorization. Configure an FGA provider to authorize privileged run access." });
230
249
  }
231
250
  Object.defineProperty(exports, "MastraFGAPermissions", {
232
251
  enumerable: true,
@@ -264,6 +283,12 @@ Object.defineProperty(exports, "getEffectiveThreadId", {
264
283
  return getEffectiveThreadId;
265
284
  }
266
285
  });
286
+ Object.defineProperty(exports, "getHandlerFGAProvider", {
287
+ enumerable: true,
288
+ get: function() {
289
+ return getHandlerFGAProvider;
290
+ }
291
+ });
267
292
  Object.defineProperty(exports, "getPublicWorkflowById", {
268
293
  enumerable: true,
269
294
  get: function() {
@@ -325,4 +350,4 @@ Object.defineProperty(exports, "validateThreadOwnership", {
325
350
  }
326
351
  });
327
352
 
328
- //# sourceMappingURL=utils-1UlUJRyC.cjs.map
353
+ //# sourceMappingURL=utils-BbYUI6Yn.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-BbYUI6Yn.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 { Mastra } from '@mastra/core';\nimport type { IFGAProvider, MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type { Workflow } from '@mastra/core/workflows';\nimport {\n MASTRA_AUTH_MODE_KEY,\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_THREAD_ID_KEY,\n isReservedRequestContextKey,\n} from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\n\n/**\n * Resolves a workflow by id or registration key from the set Mastra exposes\n * publicly. Unlike `mastra.getWorkflowById`, this excludes hidden internal\n * workflows (e.g. a durable agent's backing loop), which must never be\n * runnable through HTTP routes.\n */\nexport function getPublicWorkflowById(mastra: Mastra, workflowId: string): Workflow | undefined {\n const workflows = mastra.listWorkflows();\n return (\n Object.values(workflows).find(workflow => workflow.id === workflowId) ??\n (Object.hasOwn(workflows, workflowId) ? workflows[workflowId] : undefined)\n );\n}\n\n/**\n * Resolves the FGA provider a handler should use for this request, following\n * the same auth-mode-aware selection as the route-level checks: Studio auth\n * requests use `studio.fga` when it is configured, and everything else uses\n * `server.fga`.\n *\n * Returns `undefined` when FGA is not configured at all. When FGA is\n * configured but no provider applies to this request (for example `studio.fga`\n * is set and the request used server auth), the request is denied rather than\n * treated as unrestricted.\n */\nexport function getHandlerFGAProvider(mastra: any, requestContext?: RequestContext): IFGAProvider | undefined {\n const studioFga = mastra?.getStudio?.()?.fga as IFGAProvider | undefined;\n const serverFga = mastra?.getServer?.()?.fga as IFGAProvider | undefined;\n\n if (requestContext?.get(MASTRA_AUTH_MODE_KEY) === 'studio' && studioFga) return studioFga;\n if (serverFga) return serverFga;\n if (studioFga) {\n throw new HTTPException(403, { message: 'Access denied: no FGA provider is configured for this request' });\n }\n return undefined;\n}\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 * Applies the effective threadId to a client memory thread option. Object\n * threads keep their other fields (metadata, title, ...) so they reach thread\n * creation; a client-supplied resourceId is dropped because the server decides\n * the resource.\n */\nexport function applyEffectiveThreadId<T extends string | { id: string } | undefined>(\n thread: T,\n effectiveThreadId: string | undefined,\n): T | string {\n if (!effectiveThreadId) return thread;\n if (thread && typeof thread === 'object') {\n const { resourceId: _resourceId, ...fields } = thread as { id: string; resourceId?: unknown };\n return { ...fields, id: effectiveThreadId } as T;\n }\n return effectiveThreadId;\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 = getHandlerFGAProvider(mastra, requestContext);\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 fgaProvider,\n });\n}\n\n/**\n * Validates that a caller may act on a workflow run.\n *\n * Without `server.auth.mapUserToResourceId` there is no tenancy model, and only a mismatch\n * between two present resource ids is denied. With a mapper, a resource-scoped caller may only\n * act on runs it owns (an owner-less run is not its run). An unscoped caller is a\n * privileged/service context (see getContextResourceId), but that privilege is only granted when\n * an FGA provider authorizes the route; otherwise it is refused rather than granted implicitly,\n * as on the thread-transfer route.\n */\nexport async function validateRunOwnership(\n run: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n mastra?: {\n getServer?: () => { auth?: unknown; fga?: unknown } | undefined;\n getStudio?: () => { fga?: unknown } | undefined;\n },\n requestContext?: RequestContext,\n): Promise<void> {\n if (!run) return;\n const server = mastra?.getServer?.();\n const tenancy =\n typeof (server?.auth as { mapUserToResourceId?: unknown } | undefined)?.mapUserToResourceId === 'function';\n if (!tenancy) {\n if (effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n return;\n }\n if (effectiveResourceId) {\n if (run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n return;\n }\n if (!getHandlerFGAProvider(mastra, requestContext)) {\n throw new HTTPException(403, {\n message:\n 'Access denied: unscoped workflow run access requires explicit authorization. Configure an FGA provider to authorize privileged run access.',\n });\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;;;;;;;;ACzCjF,SAAgB,sBAAsB,QAAgB,YAA0C;CAC9F,MAAM,YAAY,OAAO,cAAc;CACvC,OACE,OAAO,OAAO,SAAS,CAAC,CAAC,MAAK,aAAY,SAAS,OAAO,UAAU,MACnE,OAAO,OAAO,WAAW,UAAU,IAAI,UAAU,cAAc,KAAA;AAEpE;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,QAAa,gBAA2D;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AC;AAEL"}
@@ -60,6 +60,24 @@ function getPublicWorkflowById(mastra, workflowId) {
60
60
  const workflows = mastra.listWorkflows();
61
61
  return Object.values(workflows).find((workflow) => workflow.id === workflowId) ?? (Object.hasOwn(workflows, workflowId) ? workflows[workflowId] : void 0);
62
62
  }
63
+ /**
64
+ * Resolves the FGA provider a handler should use for this request, following
65
+ * the same auth-mode-aware selection as the route-level checks: Studio auth
66
+ * requests use `studio.fga` when it is configured, and everything else uses
67
+ * `server.fga`.
68
+ *
69
+ * Returns `undefined` when FGA is not configured at all. When FGA is
70
+ * configured but no provider applies to this request (for example `studio.fga`
71
+ * is set and the request used server auth), the request is denied rather than
72
+ * treated as unrestricted.
73
+ */
74
+ function getHandlerFGAProvider(mastra, requestContext) {
75
+ const studioFga = mastra?.getStudio?.()?.fga;
76
+ const serverFga = mastra?.getServer?.()?.fga;
77
+ if (requestContext?.get("mastra__authMode") === "studio" && studioFga) return studioFga;
78
+ if (serverFga) return serverFga;
79
+ if (studioFga) throw new HTTPException(403, { message: "Access denied: no FGA provider is configured for this request" });
80
+ }
63
81
  function validateBody(body) {
64
82
  const errorResponse = Object.entries(body).reduce((acc, [key, value]) => {
65
83
  if (!value) acc[key] = `Argument "${key}" is required`;
@@ -191,7 +209,8 @@ async function validateThreadOwnership(thread, effectiveResourceId) {
191
209
  */
192
210
  async function enforceThreadAccess({ mastra, requestContext, threadId, thread, effectiveResourceId, permission = MastraFGAPermissions.MEMORY_READ }) {
193
211
  await validateThreadOwnership(thread, effectiveResourceId);
194
- if (!mastra?.getServer?.()?.fga) return;
212
+ const fgaProvider = getHandlerFGAProvider(mastra, requestContext);
213
+ if (!fgaProvider) return;
195
214
  const user = requestContext?.get("user");
196
215
  if (!user || typeof user !== "object") throw new HTTPException(403, { message: "FGA authorization denied: authenticated user is required" });
197
216
  await MastraMemory.checkThreadFGA({
@@ -200,7 +219,8 @@ async function enforceThreadAccess({ mastra, requestContext, threadId, thread, e
200
219
  threadId,
201
220
  resourceId: thread?.resourceId ?? effectiveResourceId,
202
221
  requestContext,
203
- permission
222
+ permission,
223
+ fgaProvider
204
224
  });
205
225
  }
206
226
  /**
@@ -213,10 +233,9 @@ async function enforceThreadAccess({ mastra, requestContext, threadId, thread, e
213
233
  * an FGA provider authorizes the route; otherwise it is refused rather than granted implicitly,
214
234
  * as on the thread-transfer route.
215
235
  */
216
- async function validateRunOwnership(run, effectiveResourceId, mastra) {
236
+ async function validateRunOwnership(run, effectiveResourceId, mastra, requestContext) {
217
237
  if (!run) return;
218
- const server = mastra?.getServer?.();
219
- if (!(typeof (server?.auth)?.mapUserToResourceId === "function")) {
238
+ if (!(typeof ((mastra?.getServer?.())?.auth)?.mapUserToResourceId === "function")) {
220
239
  if (effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) throw new HTTPException(403, { message: "Access denied: workflow run belongs to a different resource" });
221
240
  return;
222
241
  }
@@ -224,8 +243,8 @@ async function validateRunOwnership(run, effectiveResourceId, mastra) {
224
243
  if (run.resourceId !== effectiveResourceId) throw new HTTPException(403, { message: "Access denied: workflow run belongs to a different resource" });
225
244
  return;
226
245
  }
227
- if (!server?.fga) throw new HTTPException(403, { message: "Access denied: unscoped workflow run access requires explicit authorization. Configure an FGA provider to authorize privileged run access." });
246
+ if (!getHandlerFGAProvider(mastra, requestContext)) throw new HTTPException(403, { message: "Access denied: unscoped workflow run access requires explicit authorization. Configure an FGA provider to authorize privileged run access." });
228
247
  }
229
- export { getEffectiveThreadId as a, parseFilters as c, sanitizeBody as d, stripClientCredentialHeaders as f, MastraFGAPermissions as g, validateThreadOwnership as h, getEffectiveResourceId as i, parsePerPage as l, validateRunOwnership as m, enforceThreadAccess as n, getPublicWorkflowById as o, validateBody as p, getContextResourceId as r, mergeBodyRequestContext as s, applyEffectiveThreadId as t, requireEffectiveResourceId as u };
248
+ export { MastraFGAPermissions as _, getEffectiveThreadId as a, mergeBodyRequestContext as c, requireEffectiveResourceId as d, sanitizeBody as f, validateThreadOwnership as g, validateRunOwnership as h, getEffectiveResourceId as i, parseFilters as l, validateBody as m, enforceThreadAccess as n, getHandlerFGAProvider as o, stripClientCredentialHeaders as p, getContextResourceId as r, getPublicWorkflowById as s, applyEffectiveThreadId as t, parsePerPage as u };
230
249
 
231
- //# sourceMappingURL=utils-DEwjGOpJ.js.map
250
+ //# sourceMappingURL=utils-DHxjw4Tn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-DHxjw4Tn.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 { Mastra } from '@mastra/core';\nimport type { IFGAProvider, MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type { Workflow } from '@mastra/core/workflows';\nimport {\n MASTRA_AUTH_MODE_KEY,\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_THREAD_ID_KEY,\n isReservedRequestContextKey,\n} from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\n\n/**\n * Resolves a workflow by id or registration key from the set Mastra exposes\n * publicly. Unlike `mastra.getWorkflowById`, this excludes hidden internal\n * workflows (e.g. a durable agent's backing loop), which must never be\n * runnable through HTTP routes.\n */\nexport function getPublicWorkflowById(mastra: Mastra, workflowId: string): Workflow | undefined {\n const workflows = mastra.listWorkflows();\n return (\n Object.values(workflows).find(workflow => workflow.id === workflowId) ??\n (Object.hasOwn(workflows, workflowId) ? workflows[workflowId] : undefined)\n );\n}\n\n/**\n * Resolves the FGA provider a handler should use for this request, following\n * the same auth-mode-aware selection as the route-level checks: Studio auth\n * requests use `studio.fga` when it is configured, and everything else uses\n * `server.fga`.\n *\n * Returns `undefined` when FGA is not configured at all. When FGA is\n * configured but no provider applies to this request (for example `studio.fga`\n * is set and the request used server auth), the request is denied rather than\n * treated as unrestricted.\n */\nexport function getHandlerFGAProvider(mastra: any, requestContext?: RequestContext): IFGAProvider | undefined {\n const studioFga = mastra?.getStudio?.()?.fga as IFGAProvider | undefined;\n const serverFga = mastra?.getServer?.()?.fga as IFGAProvider | undefined;\n\n if (requestContext?.get(MASTRA_AUTH_MODE_KEY) === 'studio' && studioFga) return studioFga;\n if (serverFga) return serverFga;\n if (studioFga) {\n throw new HTTPException(403, { message: 'Access denied: no FGA provider is configured for this request' });\n }\n return undefined;\n}\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 * Applies the effective threadId to a client memory thread option. Object\n * threads keep their other fields (metadata, title, ...) so they reach thread\n * creation; a client-supplied resourceId is dropped because the server decides\n * the resource.\n */\nexport function applyEffectiveThreadId<T extends string | { id: string } | undefined>(\n thread: T,\n effectiveThreadId: string | undefined,\n): T | string {\n if (!effectiveThreadId) return thread;\n if (thread && typeof thread === 'object') {\n const { resourceId: _resourceId, ...fields } = thread as { id: string; resourceId?: unknown };\n return { ...fields, id: effectiveThreadId } as T;\n }\n return effectiveThreadId;\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 = getHandlerFGAProvider(mastra, requestContext);\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 fgaProvider,\n });\n}\n\n/**\n * Validates that a caller may act on a workflow run.\n *\n * Without `server.auth.mapUserToResourceId` there is no tenancy model, and only a mismatch\n * between two present resource ids is denied. With a mapper, a resource-scoped caller may only\n * act on runs it owns (an owner-less run is not its run). An unscoped caller is a\n * privileged/service context (see getContextResourceId), but that privilege is only granted when\n * an FGA provider authorizes the route; otherwise it is refused rather than granted implicitly,\n * as on the thread-transfer route.\n */\nexport async function validateRunOwnership(\n run: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n mastra?: {\n getServer?: () => { auth?: unknown; fga?: unknown } | undefined;\n getStudio?: () => { fga?: unknown } | undefined;\n },\n requestContext?: RequestContext,\n): Promise<void> {\n if (!run) return;\n const server = mastra?.getServer?.();\n const tenancy =\n typeof (server?.auth as { mapUserToResourceId?: unknown } | undefined)?.mapUserToResourceId === 'function';\n if (!tenancy) {\n if (effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n return;\n }\n if (effectiveResourceId) {\n if (run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n return;\n }\n if (!getHandlerFGAProvider(mastra, requestContext)) {\n throw new HTTPException(403, {\n message:\n 'Access denied: unscoped workflow run access requires explicit authorization. Configure an FGA provider to authorize privileged run access.',\n });\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,kBAAmB,OAAe;AAQxC,MAAa,uBACX,mBAAmB,OAAO,KAAK,eAAe,CAAC,CAAC,SAAS,IAAI,kBAAkB;;;;;;;;ACzCjF,SAAgB,sBAAsB,QAAgB,YAA0C;CAC9F,MAAM,YAAY,OAAO,cAAc;CACvC,OACE,OAAO,OAAO,SAAS,CAAC,CAAC,MAAK,aAAY,SAAS,OAAO,UAAU,MACnE,OAAO,OAAO,WAAW,UAAU,IAAI,UAAU,cAAc,KAAA;AAEpE;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,QAAa,gBAA2D;CAC5G,MAAM,YAAY,QAAQ,YAAY,CAAC,EAAE;CACzC,MAAM,YAAY,QAAQ,YAAY,CAAC,EAAE;CAEzC,IAAI,gBAAgB,IAAA,kBAAwB,MAAM,YAAY,WAAW,OAAO;CAChF,IAAI,WAAW,OAAO;CACtB,IAAI,WACF,MAAM,IA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AAc,KAAK,EAAE,SAAS,wDAAwD,CAAC;AAErG;;;;;AAMA,eAAsB,oBAAoB,EACxC,QACA,gBACA,UACA,QACA,qBACA,aAAa,qBAAqB,eAQlB;CAChB,MAAM,wBAAwB,QAAQ,mBAAmB;CAEzD,MAAM,cAAc,sBAAsB,QAAQ,cAAc;CAChE,IAAI,CAAC,aACH;CAGF,MAAM,OAAO,gBAAgB,IAAI,MAAM;CACvC,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,2DAA2D,CAAC;CAGtG,MAAM,aAAa,eAAe;EAChC;EACM;EACN;EACA,YAAY,QAAQ,cAAc;EAClC;EACA;EACA;CACF,CAAC;AACH;;;;;;;;;;;AAYA,eAAsB,qBACpB,KACA,qBACA,QAIA,gBACe;CACf,IAAI,CAAC,KAAK;CAIV,IAAI,EADF,SAFa,QAAQ,YAAY,EAAA,EAEjB,KAAA,EAAwD,wBAAwB,aACpF;EACZ,IAAI,uBAAuB,IAAI,cAAc,IAAI,eAAe,qBAC9D,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,8DAA8D,CAAC;EAEzG;CACF;CACA,IAAI,qBAAqB;EACvB,IAAI,IAAI,eAAe,qBACrB,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,8DAA8D,CAAC;EAEzG;CACF;CACA,IAAI,CAAC,sBAAsB,QAAQ,cAAc,GAC/C,MAAM,IAAI,cAAc,KAAK,EAC3B,SACE,6IACJ,CAAC;AAEL"}
@@ -1,9 +1,9 @@
1
1
  const require_http_exception = require("./http-exception-Co3MbFUf.cjs");
2
- const require_agents = require("./agents-vFpMvK3w.cjs");
2
+ const require_agents = require("./agents-Bs1GFnXz.cjs");
3
3
  const require_route_builder = require("./route-builder-CvARmqnA.cjs");
4
4
  const require_server_handlers_error = require("./server/handlers/error.cjs");
5
- const require_utils = require("./utils-1UlUJRyC.cjs");
6
- const require_editor_builder = require("./editor-builder-8li-nXor.cjs");
5
+ const require_utils = require("./utils-BbYUI6Yn.cjs");
6
+ const require_editor_builder = require("./editor-builder-9T1aGM2f.cjs");
7
7
  let zod_v4 = require("zod/v4");
8
8
  // src/server/schemas/workflow-builder.ts
9
9
  const workflowBuilderSettingsResponseSchema = zod_v4.z.object({
@@ -110,4 +110,4 @@ Object.defineProperty(exports, "STREAM_WORKFLOW_BUILDER_ROUTE", {
110
110
  }
111
111
  });
112
112
 
113
- //# sourceMappingURL=workflow-builder-CJEajbkw.cjs.map
113
+ //# sourceMappingURL=workflow-builder-DJKziSOo.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-builder-CJEajbkw.cjs","names":["z","builderModelPolicySchema","createRoute","handleError","agentExecutionBodySchema","streamResponseSchema","HTTPException","getEffectiveResourceId","getEffectiveThreadId","enforceThreadAccess","applyEffectiveThreadId"],"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 applyEffectiveThreadId,\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, scopes: _scopes, ...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: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId),\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;;ACSD,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,gCAAg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EA,yBAAyB;KACvB,GAAG;KACH,UAAU,uBAAuB,aAAa;KAC9C,QAAQC,cAAAA,uBAAuB,aAAa,QAAQ,iBAAiB;IACvE;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,OAAOP,8BAAAA,YAAY,OAAO,2CAA2C;EACvE;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"workflow-builder-DJKziSOo.cjs","names":["z","builderModelPolicySchema","createRoute","handleError","agentExecutionBodySchema","streamResponseSchema","HTTPException","getEffectiveResourceId","getEffectiveThreadId","enforceThreadAccess","applyEffectiveThreadId"],"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 applyEffectiveThreadId,\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, scopes: _scopes, ...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: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId),\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;;ACSD,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,8BA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ACA,gBAAgB;MAChB,UAAU;MACV;MACA;MACA,YAAY;KACd,CAAC;IAEL;IAEA,yBAAyB;KACvB,GAAG;KACH,UAAU,uBAAuB,aAAa;KAC9C,QAAQC,cAAAA,uBAAuB,aAAa,QAAQ,iBAAiB;IACvE;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,OAAOP,8BAAAA,YAAY,OAAO,2CAA2C;EACvE;CACF;AACF,CAAC"}
@@ -1,9 +1,9 @@
1
1
  import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
2
- import { X as streamResponseSchema, r as agentExecutionBodySchema } from "./agents-A-ahR0eQ.js";
2
+ import { X as streamResponseSchema, r as agentExecutionBodySchema } from "./agents-Cl3KTHU4.js";
3
3
  import { n as createRoute } from "./route-builder-BxPrwNog.js";
4
4
  import { handleError } from "./server/handlers/error.js";
5
- import { a as getEffectiveThreadId, i as getEffectiveResourceId, n as enforceThreadAccess, p as validateBody, s as mergeBodyRequestContext, t as applyEffectiveThreadId, u as requireEffectiveResourceId } from "./utils-DEwjGOpJ.js";
6
- import { a as builderModelPolicySchema } from "./editor-builder-BCZy1ZH1.js";
5
+ import { a as getEffectiveThreadId, c as mergeBodyRequestContext, d as requireEffectiveResourceId, i as getEffectiveResourceId, m as validateBody, n as enforceThreadAccess, t as applyEffectiveThreadId } from "./utils-DHxjw4Tn.js";
6
+ import { a as builderModelPolicySchema } from "./editor-builder-lzO2zecA.js";
7
7
  import { z } from "zod/v4";
8
8
  // src/server/schemas/workflow-builder.ts
9
9
  const workflowBuilderSettingsResponseSchema = z.object({
@@ -99,4 +99,4 @@ const STREAM_WORKFLOW_BUILDER_ROUTE = createRoute({
99
99
  });
100
100
  export { STREAM_WORKFLOW_BUILDER_ROUTE as n, GET_WORKFLOW_BUILDER_SETTINGS_ROUTE as t };
101
101
 
102
- //# sourceMappingURL=workflow-builder-BcVfkods.js.map
102
+ //# sourceMappingURL=workflow-builder-ezo8ZG1K.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-builder-BcVfkods.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 applyEffectiveThreadId,\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, scopes: _scopes, ...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: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId),\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,wCAAwC,EAAE,OAAO;CAC5D,SAAS,EAAE,QAAQ;CACnB,aAAa,yBAAyB,SAAS;AACjD,CAAC;;ACSD,MAAa,sCAAsC,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,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,GAAG,aAAa;EAC3F,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI,CAAC,QAAQ,kCAAkC,KAAK,OAAO,OAAO,2BAA2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AC"}
1
+ {"version":3,"file":"workflow-builder-ezo8ZG1K.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 applyEffectiveThreadId,\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, scopes: _scopes, ...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: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId),\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,wCAAwC,EAAE,OAAO;CAC5D,SAAS,EAAE,QAAQ;CACnB,aAAa,yBAAyB,SAAS;AACjD,CAAC;;ACSD,MAAa,sCAAsC,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,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,GAAG,aAAa;EAC3F,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI,CAAC,QAAQ,kCAAkC,KAAK,OAAO,OAAO,2BAA2B,YAC3F,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,kCAAkC,CAAC;GAG7E,MAAM,UAAU,MAAM,OAAO,uBAAuB;GACpD,IAAI,CAAC,SAAS,SAAS,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,kCAAkC,CAAC;GAClG,MAAM,QAAQ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