@mastra/server 1.67.0-alpha.1 → 1.67.0-alpha.3

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 (191) hide show
  1. package/dist/_types/@internal_voice/dist/_types/@internal_core/dist/request-context/index.d.ts +21 -0
  2. package/dist/{a2a-CW4FVjHx.cjs → a2a-DQ8GeDz4.cjs} +3 -3
  3. package/dist/{a2a-CW4FVjHx.cjs.map → a2a-DQ8GeDz4.cjs.map} +1 -1
  4. package/dist/{a2a-Di7S6YaM.js → a2a-DUBjstWk.js} +3 -3
  5. package/dist/{a2a-Di7S6YaM.js.map → a2a-DUBjstWk.js.map} +1 -1
  6. package/dist/{api-schema-manifest-Cpw4nIVv.cjs → api-schema-manifest-1LriOYQM.cjs} +3 -3
  7. package/dist/{api-schema-manifest-Cpw4nIVv.cjs.map → api-schema-manifest-1LriOYQM.cjs.map} +1 -1
  8. package/dist/{api-schema-manifest-BkKHbFJi.js → api-schema-manifest-DNk8B4kw.js} +3 -3
  9. package/dist/{api-schema-manifest-BkKHbFJi.js.map → api-schema-manifest-DNk8B4kw.js.map} +1 -1
  10. package/dist/{background-tasks-Bl7Hn8h9.js → background-tasks-B4yoNDY_.js} +2 -2
  11. package/dist/{background-tasks-Bl7Hn8h9.js.map → background-tasks-B4yoNDY_.js.map} +1 -1
  12. package/dist/{background-tasks-BJhziawt.cjs → background-tasks-BarPeyNJ.cjs} +2 -2
  13. package/dist/{background-tasks-BJhziawt.cjs.map → background-tasks-BarPeyNJ.cjs.map} +1 -1
  14. package/dist/{builder-registry-Bcpr74BB.js → builder-registry-DI3Ysclf.js} +3 -3
  15. package/dist/{builder-registry-Bcpr74BB.js.map → builder-registry-DI3Ysclf.js.map} +1 -1
  16. package/dist/{builder-registry-BINitddV.cjs → builder-registry-r71f11_E.cjs} +3 -3
  17. package/dist/{builder-registry-BINitddV.cjs.map → builder-registry-r71f11_E.cjs.map} +1 -1
  18. package/dist/{channels-CnEljW9e.js → channels-B_K1oJ7S.js} +2 -2
  19. package/dist/{channels-CnEljW9e.js.map → channels-B_K1oJ7S.js.map} +1 -1
  20. package/dist/{channels-D8e5YDTn.cjs → channels-CGDo0Prv.cjs} +2 -2
  21. package/dist/{channels-D8e5YDTn.cjs.map → channels-CGDo0Prv.cjs.map} +1 -1
  22. package/dist/{conversations-D89Io31L.js → conversations-Bs-k9f9N.js} +2 -2
  23. package/dist/{conversations-D89Io31L.js.map → conversations-Bs-k9f9N.js.map} +1 -1
  24. package/dist/{conversations-DJybpnE5.cjs → conversations-o3AEJjRo.cjs} +2 -2
  25. package/dist/{conversations-DJybpnE5.cjs.map → conversations-o3AEJjRo.cjs.map} +1 -1
  26. package/dist/{dist-B8gYiHIX.js → dist-Bw-Zrv4_.js} +173 -27
  27. package/dist/{dist-B8gYiHIX.js.map → dist-Bw-Zrv4_.js.map} +1 -1
  28. package/dist/{dist-CaVro31X.cjs → dist-Du9y2ur5.cjs} +177 -31
  29. package/dist/{dist-CaVro31X.cjs.map → dist-Du9y2ur5.cjs.map} +1 -1
  30. package/dist/docs/SKILL.md +1 -1
  31. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  32. package/dist/{dynamic-workflows-Cn9MXevC.js → dynamic-workflows-C3DXgmSP.js} +2 -2
  33. package/dist/{dynamic-workflows-Cn9MXevC.js.map → dynamic-workflows-C3DXgmSP.js.map} +1 -1
  34. package/dist/{dynamic-workflows-DSg9_yec.cjs → dynamic-workflows-DeUG3lA2.cjs} +2 -2
  35. package/dist/{dynamic-workflows-DSg9_yec.cjs.map → dynamic-workflows-DeUG3lA2.cjs.map} +1 -1
  36. package/dist/{editor-builder-DeFo8Kl5.cjs → editor-builder-DFh_-7Id.cjs} +2 -2
  37. package/dist/{editor-builder-DeFo8Kl5.cjs.map → editor-builder-DFh_-7Id.cjs.map} +1 -1
  38. package/dist/{editor-builder-DzpPA6dp.js → editor-builder-QRcP8-SQ.js} +2 -2
  39. package/dist/{editor-builder-DzpPA6dp.js.map → editor-builder-QRcP8-SQ.js.map} +1 -1
  40. package/dist/{memory-CVODqy7m.cjs → memory-CE6rUGmo.cjs} +22 -1
  41. package/dist/memory-CE6rUGmo.cjs.map +1 -0
  42. package/dist/{memory-CjWJYFVI.js → memory-Cp3Yo-OX.js} +11 -2
  43. package/dist/{memory-CjWJYFVI.js.map → memory-Cp3Yo-OX.js.map} +1 -1
  44. package/dist/{observability-new-endpoints-BNPjbEXf.cjs → observability-new-endpoints-I2OxQzfY.cjs} +2 -2
  45. package/dist/{observability-new-endpoints-BNPjbEXf.cjs.map → observability-new-endpoints-I2OxQzfY.cjs.map} +1 -1
  46. package/dist/{observability-new-endpoints-CSiMF_Kf.js → observability-new-endpoints-pIq_OWa8.js} +2 -2
  47. package/dist/{observability-new-endpoints-CSiMF_Kf.js.map → observability-new-endpoints-pIq_OWa8.js.map} +1 -1
  48. package/dist/{route-builder-BveLN9LU.js → route-builder-BukcT_Kp.js} +2 -2
  49. package/dist/{route-builder-BveLN9LU.js.map → route-builder-BukcT_Kp.js.map} +1 -1
  50. package/dist/{route-builder-C8n4ugUf.cjs → route-builder-DupY8fkI.cjs} +4 -4
  51. package/dist/{route-builder-C8n4ugUf.cjs.map → route-builder-DupY8fkI.cjs.map} +1 -1
  52. package/dist/{routes-Dgd2S9av.cjs → routes-9i4gAixo.cjs} +11 -10
  53. package/dist/routes-9i4gAixo.cjs.map +1 -0
  54. package/dist/{routes-DCwOOz84.js → routes-DXUcYEc6.js} +12 -11
  55. package/dist/routes-DXUcYEc6.js.map +1 -0
  56. package/dist/{schedules-BcEUUuX_.js → schedules-BzymFGR_.js} +2 -2
  57. package/dist/{schedules-BcEUUuX_.js.map → schedules-BzymFGR_.js.map} +1 -1
  58. package/dist/{schedules-fj9U0_tA.cjs → schedules-DaEv0Usj.cjs} +2 -2
  59. package/dist/{schedules-fj9U0_tA.cjs.map → schedules-DaEv0Usj.cjs.map} +1 -1
  60. package/dist/schema-BF_cZG0Y.js +2 -0
  61. package/dist/schema-C7CvwM1d.cjs +1 -0
  62. package/dist/{schema-Bv9OdW1f-DLSJSqQv.js → schema-D_ikovK6-BzTeMhWf.js} +467 -131
  63. package/dist/schema-D_ikovK6-BzTeMhWf.js.map +1 -0
  64. package/dist/{schema-Bv9OdW1f-CxTiW8RD.cjs → schema-D_ikovK6-DQrOVw5N.cjs} +467 -131
  65. package/dist/schema-D_ikovK6-DQrOVw5N.cjs.map +1 -0
  66. package/dist/server/handlers/a2a.cjs +1 -1
  67. package/dist/server/handlers/a2a.js +1 -1
  68. package/dist/server/handlers/agent-builder.cjs +3 -3
  69. package/dist/server/handlers/agent-builder.js +3 -3
  70. package/dist/server/handlers/agent-controller.cjs +3 -3
  71. package/dist/server/handlers/agent-controller.js +3 -3
  72. package/dist/server/handlers/agent-versions.cjs +2 -2
  73. package/dist/server/handlers/agent-versions.js +2 -2
  74. package/dist/server/handlers/agents.cjs +6 -6
  75. package/dist/server/handlers/agents.js +5 -5
  76. package/dist/server/handlers/auth.cjs +1 -1
  77. package/dist/server/handlers/auth.js +1 -1
  78. package/dist/server/handlers/background-tasks.cjs +1 -1
  79. package/dist/server/handlers/background-tasks.js +1 -1
  80. package/dist/server/handlers/builder-registry.cjs +1 -1
  81. package/dist/server/handlers/builder-registry.js +1 -1
  82. package/dist/server/handlers/channels.cjs +1 -1
  83. package/dist/server/handlers/channels.js +1 -1
  84. package/dist/server/handlers/conversations.cjs +3 -3
  85. package/dist/server/handlers/conversations.js +3 -3
  86. package/dist/server/handlers/datasets.cjs +1 -1
  87. package/dist/server/handlers/datasets.js +1 -1
  88. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  89. package/dist/server/handlers/dynamic-workflows.js +1 -1
  90. package/dist/server/handlers/editor-builder.cjs +1 -1
  91. package/dist/server/handlers/editor-builder.js +1 -1
  92. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  93. package/dist/server/handlers/favorites-enrichment.js +1 -1
  94. package/dist/server/handlers/logs.cjs +2 -2
  95. package/dist/server/handlers/logs.js +2 -2
  96. package/dist/server/handlers/mcp-client-versions.cjs +2 -2
  97. package/dist/server/handlers/mcp-client-versions.js +2 -2
  98. package/dist/server/handlers/mcp.cjs +1 -1
  99. package/dist/server/handlers/mcp.js +1 -1
  100. package/dist/server/handlers/memory.cjs +64 -3
  101. package/dist/server/handlers/memory.cjs.map +1 -1
  102. package/dist/server/handlers/memory.d.ts +47 -0
  103. package/dist/server/handlers/memory.d.ts.map +1 -1
  104. package/dist/server/handlers/memory.js +64 -4
  105. package/dist/server/handlers/memory.js.map +1 -1
  106. package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
  107. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  108. package/dist/server/handlers/observability-shared.cjs +1 -1
  109. package/dist/server/handlers/observability-shared.js +1 -1
  110. package/dist/server/handlers/observability.cjs +2 -2
  111. package/dist/server/handlers/observability.js +2 -2
  112. package/dist/server/handlers/plans.cjs +2 -2
  113. package/dist/server/handlers/plans.js +2 -2
  114. package/dist/server/handlers/processor-providers.cjs +1 -1
  115. package/dist/server/handlers/processor-providers.js +1 -1
  116. package/dist/server/handlers/processors.cjs +1 -1
  117. package/dist/server/handlers/processors.js +1 -1
  118. package/dist/server/handlers/prompt-block-versions.cjs +2 -2
  119. package/dist/server/handlers/prompt-block-versions.js +2 -2
  120. package/dist/server/handlers/responses.cjs +2 -2
  121. package/dist/server/handlers/responses.js +2 -2
  122. package/dist/server/handlers/responses.storage.cjs +1 -1
  123. package/dist/server/handlers/responses.storage.js +1 -1
  124. package/dist/server/handlers/schedules.cjs +1 -1
  125. package/dist/server/handlers/schedules.js +1 -1
  126. package/dist/server/handlers/scorer-versions.cjs +2 -2
  127. package/dist/server/handlers/scorer-versions.js +2 -2
  128. package/dist/server/handlers/scores.cjs +1 -1
  129. package/dist/server/handlers/scores.js +1 -1
  130. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  131. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  132. package/dist/server/handlers/stored-agents.cjs +3 -3
  133. package/dist/server/handlers/stored-agents.js +3 -3
  134. package/dist/server/handlers/stored-mcp-clients.cjs +2 -2
  135. package/dist/server/handlers/stored-mcp-clients.js +2 -2
  136. package/dist/server/handlers/stored-prompt-blocks.cjs +2 -2
  137. package/dist/server/handlers/stored-prompt-blocks.js +2 -2
  138. package/dist/server/handlers/stored-scorers.cjs +2 -2
  139. package/dist/server/handlers/stored-scorers.js +2 -2
  140. package/dist/server/handlers/stored-skill-favorites.cjs +3 -3
  141. package/dist/server/handlers/stored-skill-favorites.js +3 -3
  142. package/dist/server/handlers/stored-skills.cjs +3 -3
  143. package/dist/server/handlers/stored-skills.js +3 -3
  144. package/dist/server/handlers/stored-workspaces.cjs +2 -2
  145. package/dist/server/handlers/stored-workspaces.js +2 -2
  146. package/dist/server/handlers/system.cjs +2 -2
  147. package/dist/server/handlers/system.js +2 -2
  148. package/dist/server/handlers/tool-providers.cjs +1 -1
  149. package/dist/server/handlers/tool-providers.js +1 -1
  150. package/dist/server/handlers/tools.cjs +6 -6
  151. package/dist/server/handlers/tools.js +5 -5
  152. package/dist/server/handlers/utils.cjs +2 -1
  153. package/dist/server/handlers/utils.d.ts +7 -0
  154. package/dist/server/handlers/utils.d.ts.map +1 -1
  155. package/dist/server/handlers/utils.js +2 -2
  156. package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
  157. package/dist/server/handlers/validate-agent-instructions.js +1 -1
  158. package/dist/server/handlers/vector.cjs +1 -1
  159. package/dist/server/handlers/vector.js +1 -1
  160. package/dist/server/handlers/workflows.cjs +3 -3
  161. package/dist/server/handlers/workflows.js +3 -3
  162. package/dist/server/handlers/workspace.cjs +1 -1
  163. package/dist/server/handlers/workspace.js +1 -1
  164. package/dist/server/handlers.cjs +2 -2
  165. package/dist/server/handlers.js +2 -2
  166. package/dist/server/schemas/index.cjs +4 -2
  167. package/dist/server/schemas/index.js +3 -3
  168. package/dist/server/schemas/memory.d.ts +18 -0
  169. package/dist/server/schemas/memory.d.ts.map +1 -1
  170. package/dist/server/server-adapter/index.cjs +3 -3
  171. package/dist/server/server-adapter/index.js +3 -3
  172. package/dist/server/server-adapter/routes/memory.d.ts +46 -0
  173. package/dist/server/server-adapter/routes/memory.d.ts.map +1 -1
  174. package/dist/{utils-DJMUhfvY.cjs → utils-BtkczLrA.cjs} +17 -2
  175. package/dist/utils-BtkczLrA.cjs.map +1 -0
  176. package/dist/{utils-Hz8Hc2cd.js → utils-CMWGBd0O.js} +12 -3
  177. package/dist/utils-CMWGBd0O.js.map +1 -0
  178. package/dist/{utils-B2vd77Fi.js → utils-Duk4hfT_.js} +3 -3
  179. package/dist/{utils-B2vd77Fi.js.map → utils-Duk4hfT_.js.map} +1 -1
  180. package/dist/{utils-CmYnjLcY.cjs → utils-WcR0QSUB.cjs} +5 -5
  181. package/dist/{utils-CmYnjLcY.cjs.map → utils-WcR0QSUB.cjs.map} +1 -1
  182. package/package.json +7 -7
  183. package/dist/memory-CVODqy7m.cjs.map +0 -1
  184. package/dist/routes-DCwOOz84.js.map +0 -1
  185. package/dist/routes-Dgd2S9av.cjs.map +0 -1
  186. package/dist/schema-Bv9OdW1f-CxTiW8RD.cjs.map +0 -1
  187. package/dist/schema-Bv9OdW1f-DLSJSqQv.js.map +0 -1
  188. package/dist/schema-CGeYTFwm.js +0 -2
  189. package/dist/schema-CNKnRmv1.cjs +0 -1
  190. package/dist/utils-DJMUhfvY.cjs.map +0 -1
  191. package/dist/utils-Hz8Hc2cd.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"channels-CnEljW9e.js","names":[],"sources":["../src/server/schemas/channels.ts","../src/server/handlers/channels.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n// ============================================================================\n// Path Parameter Schemas\n// ============================================================================\n\nexport const channelPlatformPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n});\n\nexport const channelAgentPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n agentId: z.string().describe('Agent identifier'),\n});\n\n// ============================================================================\n// Body Parameter Schemas\n// ============================================================================\n\nexport const connectChannelBodySchema = z.object({\n agentId: z.string().describe('Agent identifier to connect'),\n options: z.record(z.string(), z.unknown()).optional().describe('Platform-specific connection options'),\n});\n\n// ============================================================================\n// Response Schemas\n// ============================================================================\n\nconst channelPlatformInfoSchema = z.object({\n id: z.string().describe('Platform identifier'),\n name: z.string().describe('Human-readable platform name'),\n isConfigured: z.boolean().describe('Whether the platform is ready to connect agents'),\n connectOptionsSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for connect options'),\n});\n\nconst channelInstallationInfoSchema = z.object({\n id: z.string().describe('Installation identifier'),\n platform: z.string().describe('Platform identifier'),\n agentId: z.string().describe('Connected agent identifier'),\n status: z.enum(['active', 'pending']).describe('Installation status'),\n displayName: z.string().optional().describe('Platform-specific display name'),\n installedAt: z.coerce.date().optional().describe('Installation timestamp'),\n});\n\nconst channelConnectOAuthSchema = z.object({\n type: z.literal('oauth').describe('OAuth-based connection requiring browser redirect'),\n authorizationUrl: z.string().describe('OAuth authorization URL for user redirect'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectDeepLinkSchema = z.object({\n type: z.literal('deep_link').describe('Deep-link connection requiring native app interaction'),\n url: z.string().describe('Deep link URL to open in platform app'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectImmediateSchema = z.object({\n type: z.literal('immediate').describe('Immediate connection with no user interaction needed'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectResultSchema = z.discriminatedUnion('type', [\n channelConnectOAuthSchema,\n channelConnectDeepLinkSchema,\n channelConnectImmediateSchema,\n]);\n\nexport const listChannelPlatformsResponseSchema = z.array(channelPlatformInfoSchema);\n\nexport const listChannelInstallationsResponseSchema = z.array(channelInstallationInfoSchema);\n\nexport const connectChannelResponseSchema = channelConnectResultSchema;\n\nexport const disconnectChannelResponseSchema = z.object({\n success: z.boolean(),\n});\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\nimport type { RequestContext } from '@mastra/core/di';\nimport { coreFeatures } from '@mastra/core/features';\n\nimport { MASTRA_USER_KEY } from '../constants';\nimport { HTTPException } from '../http-exception';\nimport {\n channelPlatformPathParams,\n channelAgentPathParams,\n connectChannelBodySchema,\n listChannelPlatformsResponseSchema,\n listChannelInstallationsResponseSchema,\n connectChannelResponseSchema,\n disconnectChannelResponseSchema,\n} from '../schemas/channels';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { assertWriteAccess, getCallerAuthorId, hasAdminBypass, hasScopedPermission } from './authorship';\nimport { handleError } from './error';\n\n// ============================================================================\n// Feature gate + helpers\n// ============================================================================\n\nfunction assertChannelsAvailable(): void {\n if (!coreFeatures.has('channels')) {\n throw new HTTPException(501, { message: 'Channels require a newer version of @mastra/core' });\n }\n}\n\nfunction getChannelOrThrow(mastra: Mastra, platform: string): ChannelProvider {\n const channels = Object.values(mastra.channels ?? {});\n const channel = channels.find(c => c.id === platform);\n if (!channel) {\n const available = channels.map(c => c.id).join(', ');\n throw new HTTPException(404, {\n message: `Channel \"${platform}\" is not registered. Available: ${available || 'none'}`,\n });\n }\n return channel;\n}\n\n/**\n * Unified connect/disconnect authorization.\n *\n * - Stored agent exists → same write access as editing the agent record.\n * - Code-defined agent (no stored record) → route's `requiresAuth` is the gate.\n * - Agent doesn't exist anywhere:\n * - connect → 404 (can't connect a channel to a non-existent agent)\n * - disconnect → orphan cleanup, gated on `channels:write`\n */\nasync function assertChannelAgentWriteAccess(\n mastra: Mastra,\n requestContext: RequestContext,\n agentId: string,\n action: 'connect' | 'disconnect',\n): Promise<void> {\n const storage = mastra.getStorage();\n const agentsStore = storage ? await storage.getStore('agents') : null;\n const stored = agentsStore ? await agentsStore.getById(agentId) : null;\n\n if (stored) {\n assertWriteAccess({\n requestContext,\n resource: 'agents',\n resourceId: agentId,\n action: 'edit',\n record: stored,\n });\n return;\n }\n\n // Not in stored-agents (or storage doesn't support it). Check the runtime\n // registry for a code-defined agent.\n const codeDefined = mastra.getAgentById(agentId);\n if (codeDefined) {\n // Code-defined agents have no owner/ACL — route's requiresAuth /\n // requiresPermission is the gate. Pass-through.\n return;\n }\n\n if (action === 'connect') {\n throw new HTTPException(404, { message: `Agent \"${agentId}\" not found` });\n }\n\n // Disconnect against an unknown agentId = orphan cleanup (stored agent was\n // deleted but the channel installation row is still around). Allow it, but\n // gate on channels:write so this isn't an \"any authenticated user\" backdoor.\n // Follow the same no-auth-configured pass-through as assertWriteAccess.\n const callerAuthorId = getCallerAuthorId(requestContext);\n if (!callerAuthorId && !requestContext.get(MASTRA_USER_KEY)) return;\n if (hasAdminBypass(requestContext, 'channels')) return;\n if (hasScopedPermission({ requestContext, resource: 'channels', action: 'write' })) return;\n\n throw new HTTPException(404, { message: 'Not found' });\n}\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\n/**\n * GET /channels/platforms - List available channel platforms\n */\nexport const LIST_CHANNEL_PLATFORMS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/platforms',\n responseType: 'json',\n responseSchema: listChannelPlatformsResponseSchema,\n summary: 'List channel platforms',\n description: 'Returns available channel platforms and their configuration status',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n assertChannelsAvailable();\n try {\n const channels = Object.values(mastra.channels ?? {});\n return channels.map(channel => {\n if (channel.getInfo) {\n return channel.getInfo();\n }\n return {\n id: channel.id,\n name: channel.id.charAt(0).toUpperCase() + channel.id.slice(1),\n isConfigured: true,\n };\n });\n } catch (error) {\n return handleError(error, 'Error listing channel platforms');\n }\n },\n});\n\n/**\n * GET /channels/:platform/installations - List installations for a platform\n */\nexport const LIST_CHANNEL_INSTALLATIONS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/:platform/installations',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n responseSchema: listChannelInstallationsResponseSchema,\n summary: 'List channel installations',\n description: 'Returns all active and pending installations for a channel platform',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, platform }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.listInstallations) {\n return [];\n }\n\n return await channel.listInstallations();\n } catch (error) {\n return handleError(error, 'Error listing channel installations');\n }\n },\n});\n\n/**\n * POST /channels/:platform/connect - Connect an agent to a platform\n */\nexport const CONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/connect',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n bodySchema: connectChannelBodySchema,\n responseSchema: connectChannelResponseSchema,\n summary: 'Connect agent to channel',\n description: 'Creates a platform app for the agent and returns an OAuth authorization URL',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId, options }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.connect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic connection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'connect');\n\n return await channel.connect(agentId, options);\n } catch (error) {\n return handleError(error, 'Error connecting agent to channel');\n }\n },\n});\n\n/**\n * POST /channels/:platform/:agentId/disconnect - Disconnect an agent from a platform\n */\nexport const DISCONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/:agentId/disconnect',\n responseType: 'json',\n pathParamSchema: channelAgentPathParams,\n responseSchema: disconnectChannelResponseSchema,\n summary: 'Disconnect agent from channel',\n description: 'Deletes the platform app and cleans up the installation',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.disconnect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic disconnection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'disconnect');\n\n await channel.disconnect(agentId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AI,CAAC,QAAQ,YACX,MAAM,IAAI,cAAc,KAAK,EAC3B,SAAS,YAAY,SAAS,+CAChC,CAAC;GAGH,MAAM,8BAA8B,QAAQ,gBAAgB,SAAS,YAAY;GAEjF,MAAM,QAAQ,WAAW,OAAO;GAChC,OAAO,EAAE,SAAS,KAAK;EACzB,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,wCAAwC;EACpE;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"channels-B_K1oJ7S.js","names":[],"sources":["../src/server/schemas/channels.ts","../src/server/handlers/channels.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n// ============================================================================\n// Path Parameter Schemas\n// ============================================================================\n\nexport const channelPlatformPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n});\n\nexport const channelAgentPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n agentId: z.string().describe('Agent identifier'),\n});\n\n// ============================================================================\n// Body Parameter Schemas\n// ============================================================================\n\nexport const connectChannelBodySchema = z.object({\n agentId: z.string().describe('Agent identifier to connect'),\n options: z.record(z.string(), z.unknown()).optional().describe('Platform-specific connection options'),\n});\n\n// ============================================================================\n// Response Schemas\n// ============================================================================\n\nconst channelPlatformInfoSchema = z.object({\n id: z.string().describe('Platform identifier'),\n name: z.string().describe('Human-readable platform name'),\n isConfigured: z.boolean().describe('Whether the platform is ready to connect agents'),\n connectOptionsSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for connect options'),\n});\n\nconst channelInstallationInfoSchema = z.object({\n id: z.string().describe('Installation identifier'),\n platform: z.string().describe('Platform identifier'),\n agentId: z.string().describe('Connected agent identifier'),\n status: z.enum(['active', 'pending']).describe('Installation status'),\n displayName: z.string().optional().describe('Platform-specific display name'),\n installedAt: z.coerce.date().optional().describe('Installation timestamp'),\n});\n\nconst channelConnectOAuthSchema = z.object({\n type: z.literal('oauth').describe('OAuth-based connection requiring browser redirect'),\n authorizationUrl: z.string().describe('OAuth authorization URL for user redirect'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectDeepLinkSchema = z.object({\n type: z.literal('deep_link').describe('Deep-link connection requiring native app interaction'),\n url: z.string().describe('Deep link URL to open in platform app'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectImmediateSchema = z.object({\n type: z.literal('immediate').describe('Immediate connection with no user interaction needed'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectResultSchema = z.discriminatedUnion('type', [\n channelConnectOAuthSchema,\n channelConnectDeepLinkSchema,\n channelConnectImmediateSchema,\n]);\n\nexport const listChannelPlatformsResponseSchema = z.array(channelPlatformInfoSchema);\n\nexport const listChannelInstallationsResponseSchema = z.array(channelInstallationInfoSchema);\n\nexport const connectChannelResponseSchema = channelConnectResultSchema;\n\nexport const disconnectChannelResponseSchema = z.object({\n success: z.boolean(),\n});\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\nimport type { RequestContext } from '@mastra/core/di';\nimport { coreFeatures } from '@mastra/core/features';\n\nimport { MASTRA_USER_KEY } from '../constants';\nimport { HTTPException } from '../http-exception';\nimport {\n channelPlatformPathParams,\n channelAgentPathParams,\n connectChannelBodySchema,\n listChannelPlatformsResponseSchema,\n listChannelInstallationsResponseSchema,\n connectChannelResponseSchema,\n disconnectChannelResponseSchema,\n} from '../schemas/channels';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { assertWriteAccess, getCallerAuthorId, hasAdminBypass, hasScopedPermission } from './authorship';\nimport { handleError } from './error';\n\n// ============================================================================\n// Feature gate + helpers\n// ============================================================================\n\nfunction assertChannelsAvailable(): void {\n if (!coreFeatures.has('channels')) {\n throw new HTTPException(501, { message: 'Channels require a newer version of @mastra/core' });\n }\n}\n\nfunction getChannelOrThrow(mastra: Mastra, platform: string): ChannelProvider {\n const channels = Object.values(mastra.channels ?? {});\n const channel = channels.find(c => c.id === platform);\n if (!channel) {\n const available = channels.map(c => c.id).join(', ');\n throw new HTTPException(404, {\n message: `Channel \"${platform}\" is not registered. Available: ${available || 'none'}`,\n });\n }\n return channel;\n}\n\n/**\n * Unified connect/disconnect authorization.\n *\n * - Stored agent exists → same write access as editing the agent record.\n * - Code-defined agent (no stored record) → route's `requiresAuth` is the gate.\n * - Agent doesn't exist anywhere:\n * - connect → 404 (can't connect a channel to a non-existent agent)\n * - disconnect → orphan cleanup, gated on `channels:write`\n */\nasync function assertChannelAgentWriteAccess(\n mastra: Mastra,\n requestContext: RequestContext,\n agentId: string,\n action: 'connect' | 'disconnect',\n): Promise<void> {\n const storage = mastra.getStorage();\n const agentsStore = storage ? await storage.getStore('agents') : null;\n const stored = agentsStore ? await agentsStore.getById(agentId) : null;\n\n if (stored) {\n assertWriteAccess({\n requestContext,\n resource: 'agents',\n resourceId: agentId,\n action: 'edit',\n record: stored,\n });\n return;\n }\n\n // Not in stored-agents (or storage doesn't support it). Check the runtime\n // registry for a code-defined agent.\n const codeDefined = mastra.getAgentById(agentId);\n if (codeDefined) {\n // Code-defined agents have no owner/ACL — route's requiresAuth /\n // requiresPermission is the gate. Pass-through.\n return;\n }\n\n if (action === 'connect') {\n throw new HTTPException(404, { message: `Agent \"${agentId}\" not found` });\n }\n\n // Disconnect against an unknown agentId = orphan cleanup (stored agent was\n // deleted but the channel installation row is still around). Allow it, but\n // gate on channels:write so this isn't an \"any authenticated user\" backdoor.\n // Follow the same no-auth-configured pass-through as assertWriteAccess.\n const callerAuthorId = getCallerAuthorId(requestContext);\n if (!callerAuthorId && !requestContext.get(MASTRA_USER_KEY)) return;\n if (hasAdminBypass(requestContext, 'channels')) return;\n if (hasScopedPermission({ requestContext, resource: 'channels', action: 'write' })) return;\n\n throw new HTTPException(404, { message: 'Not found' });\n}\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\n/**\n * GET /channels/platforms - List available channel platforms\n */\nexport const LIST_CHANNEL_PLATFORMS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/platforms',\n responseType: 'json',\n responseSchema: listChannelPlatformsResponseSchema,\n summary: 'List channel platforms',\n description: 'Returns available channel platforms and their configuration status',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n assertChannelsAvailable();\n try {\n const channels = Object.values(mastra.channels ?? {});\n return channels.map(channel => {\n if (channel.getInfo) {\n return channel.getInfo();\n }\n return {\n id: channel.id,\n name: channel.id.charAt(0).toUpperCase() + channel.id.slice(1),\n isConfigured: true,\n };\n });\n } catch (error) {\n return handleError(error, 'Error listing channel platforms');\n }\n },\n});\n\n/**\n * GET /channels/:platform/installations - List installations for a platform\n */\nexport const LIST_CHANNEL_INSTALLATIONS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/:platform/installations',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n responseSchema: listChannelInstallationsResponseSchema,\n summary: 'List channel installations',\n description: 'Returns all active and pending installations for a channel platform',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, platform }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.listInstallations) {\n return [];\n }\n\n return await channel.listInstallations();\n } catch (error) {\n return handleError(error, 'Error listing channel installations');\n }\n },\n});\n\n/**\n * POST /channels/:platform/connect - Connect an agent to a platform\n */\nexport const CONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/connect',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n bodySchema: connectChannelBodySchema,\n responseSchema: connectChannelResponseSchema,\n summary: 'Connect agent to channel',\n description: 'Creates a platform app for the agent and returns an OAuth authorization URL',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId, options }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.connect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic connection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'connect');\n\n return await channel.connect(agentId, options);\n } catch (error) {\n return handleError(error, 'Error connecting agent to channel');\n }\n },\n});\n\n/**\n * POST /channels/:platform/:agentId/disconnect - Disconnect an agent from a platform\n */\nexport const DISCONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/:agentId/disconnect',\n responseType: 'json',\n pathParamSchema: channelAgentPathParams,\n responseSchema: disconnectChannelResponseSchema,\n summary: 'Disconnect agent from channel',\n description: 'Deletes the platform app and cleans up the installation',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.disconnect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic disconnection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'disconnect');\n\n await channel.disconnect(agentId);\n return { success: true };\n } catch (error) {\n return handleError(error, 'Error disconnecting agent from channel');\n }\n },\n});\n"],"mappings":";;;;;;;;AAMA,MAAa,4BAA4B,EAAE,OAAO,EAChD,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA6C,EAC7E,CAAC;AAED,MAAa,yBAAyB,EAAE,OAAO;CAC7C,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA6C;CAC3E,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,kBAAkB;AACjD,CAAC;AAMD,MAAa,2BAA2B,EAAE,OAAO;CAC/C,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,6BAA6B;CAC1D,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,sCAAsC;AACvG,CAAC;AAMD,MAAM,4BAA4B,EAAE,OAAO;CACzC,IAAI,EAAE,OAAO,CAAC,CAAC,SAAS,qBAAqB;CAC7C,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,8BAA8B;CACx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,UAAU,kBAAkB,QAAQ,QAAQ;GAElD,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,cAAc,KAAK,EAC3B,SAAS,YAAY,SAAS,4CAChC,CAAC;GAGH,MAAM,8BAA8B,QAAQ,gBAAgB,SAAS,SAAS;GAE9E,OAAO,MAAM,QAAQ,QAAQ,SAAS,OAAO;EAC/C,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,mCAAmC;EAC/D;CACF;AACF,CAAC;;;;AAKD,MAAa,2BAA2B,YAAY;CAClD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,UAAU;CACjB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,gBAAgB,UAAU,cAAc;EAChE,wBAAwB;EACxB,IAAI;GACF,MAAM,UAAU,kBAAkB,QAAQ,QAAQ;GAElD,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,cAAc,KAAK,EAC3B,SAAS,YAAY,SAAS,+CAChC,CAAC;GAGH,MAAM,8BAA8B,QAAQ,gBAAgB,SAAS,YAAY;GAEjF,MAAM,QAAQ,WAAW,OAAO;GAChC,OAAO,EAAE,SAAS,KAAK;EACzB,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,wCAAwC;EACpE;CACF;AACF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  const require_http_exception = require("./http-exception-CKDHupKw.cjs");
2
- const require_route_builder = require("./route-builder-C8n4ugUf.cjs");
2
+ const require_route_builder = require("./route-builder-DupY8fkI.cjs");
3
3
  require("./constants-4IJp_uzj.cjs");
4
4
  const require_server_handlers_error = require("./server/handlers/error.cjs");
5
5
  const require_server_handlers_authorship = require("./server/handlers/authorship.cjs");
@@ -227,4 +227,4 @@ Object.defineProperty(exports, "LIST_CHANNEL_PLATFORMS_ROUTE", {
227
227
  }
228
228
  });
229
229
 
230
- //# sourceMappingURL=channels-D8e5YDTn.cjs.map
230
+ //# sourceMappingURL=channels-CGDo0Prv.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"channels-D8e5YDTn.cjs","names":["z","coreFeatures","HTTPException","getCallerAuthorId","hasAdminBypass","hasScopedPermission","createRoute","handleError"],"sources":["../src/server/schemas/channels.ts","../src/server/handlers/channels.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n// ============================================================================\n// Path Parameter Schemas\n// ============================================================================\n\nexport const channelPlatformPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n});\n\nexport const channelAgentPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n agentId: z.string().describe('Agent identifier'),\n});\n\n// ============================================================================\n// Body Parameter Schemas\n// ============================================================================\n\nexport const connectChannelBodySchema = z.object({\n agentId: z.string().describe('Agent identifier to connect'),\n options: z.record(z.string(), z.unknown()).optional().describe('Platform-specific connection options'),\n});\n\n// ============================================================================\n// Response Schemas\n// ============================================================================\n\nconst channelPlatformInfoSchema = z.object({\n id: z.string().describe('Platform identifier'),\n name: z.string().describe('Human-readable platform name'),\n isConfigured: z.boolean().describe('Whether the platform is ready to connect agents'),\n connectOptionsSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for connect options'),\n});\n\nconst channelInstallationInfoSchema = z.object({\n id: z.string().describe('Installation identifier'),\n platform: z.string().describe('Platform identifier'),\n agentId: z.string().describe('Connected agent identifier'),\n status: z.enum(['active', 'pending']).describe('Installation status'),\n displayName: z.string().optional().describe('Platform-specific display name'),\n installedAt: z.coerce.date().optional().describe('Installation timestamp'),\n});\n\nconst channelConnectOAuthSchema = z.object({\n type: z.literal('oauth').describe('OAuth-based connection requiring browser redirect'),\n authorizationUrl: z.string().describe('OAuth authorization URL for user redirect'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectDeepLinkSchema = z.object({\n type: z.literal('deep_link').describe('Deep-link connection requiring native app interaction'),\n url: z.string().describe('Deep link URL to open in platform app'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectImmediateSchema = z.object({\n type: z.literal('immediate').describe('Immediate connection with no user interaction needed'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectResultSchema = z.discriminatedUnion('type', [\n channelConnectOAuthSchema,\n channelConnectDeepLinkSchema,\n channelConnectImmediateSchema,\n]);\n\nexport const listChannelPlatformsResponseSchema = z.array(channelPlatformInfoSchema);\n\nexport const listChannelInstallationsResponseSchema = z.array(channelInstallationInfoSchema);\n\nexport const connectChannelResponseSchema = channelConnectResultSchema;\n\nexport const disconnectChannelResponseSchema = z.object({\n success: z.boolean(),\n});\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\nimport type { RequestContext } from '@mastra/core/di';\nimport { coreFeatures } from '@mastra/core/features';\n\nimport { MASTRA_USER_KEY } from '../constants';\nimport { HTTPException } from '../http-exception';\nimport {\n channelPlatformPathParams,\n channelAgentPathParams,\n connectChannelBodySchema,\n listChannelPlatformsResponseSchema,\n listChannelInstallationsResponseSchema,\n connectChannelResponseSchema,\n disconnectChannelResponseSchema,\n} from '../schemas/channels';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { assertWriteAccess, getCallerAuthorId, hasAdminBypass, hasScopedPermission } from './authorship';\nimport { handleError } from './error';\n\n// ============================================================================\n// Feature gate + helpers\n// ============================================================================\n\nfunction assertChannelsAvailable(): void {\n if (!coreFeatures.has('channels')) {\n throw new HTTPException(501, { message: 'Channels require a newer version of @mastra/core' });\n }\n}\n\nfunction getChannelOrThrow(mastra: Mastra, platform: string): ChannelProvider {\n const channels = Object.values(mastra.channels ?? {});\n const channel = channels.find(c => c.id === platform);\n if (!channel) {\n const available = channels.map(c => c.id).join(', ');\n throw new HTTPException(404, {\n message: `Channel \"${platform}\" is not registered. Available: ${available || 'none'}`,\n });\n }\n return channel;\n}\n\n/**\n * Unified connect/disconnect authorization.\n *\n * - Stored agent exists → same write access as editing the agent record.\n * - Code-defined agent (no stored record) → route's `requiresAuth` is the gate.\n * - Agent doesn't exist anywhere:\n * - connect → 404 (can't connect a channel to a non-existent agent)\n * - disconnect → orphan cleanup, gated on `channels:write`\n */\nasync function assertChannelAgentWriteAccess(\n mastra: Mastra,\n requestContext: RequestContext,\n agentId: string,\n action: 'connect' | 'disconnect',\n): Promise<void> {\n const storage = mastra.getStorage();\n const agentsStore = storage ? await storage.getStore('agents') : null;\n const stored = agentsStore ? await agentsStore.getById(agentId) : null;\n\n if (stored) {\n assertWriteAccess({\n requestContext,\n resource: 'agents',\n resourceId: agentId,\n action: 'edit',\n record: stored,\n });\n return;\n }\n\n // Not in stored-agents (or storage doesn't support it). Check the runtime\n // registry for a code-defined agent.\n const codeDefined = mastra.getAgentById(agentId);\n if (codeDefined) {\n // Code-defined agents have no owner/ACL — route's requiresAuth /\n // requiresPermission is the gate. Pass-through.\n return;\n }\n\n if (action === 'connect') {\n throw new HTTPException(404, { message: `Agent \"${agentId}\" not found` });\n }\n\n // Disconnect against an unknown agentId = orphan cleanup (stored agent was\n // deleted but the channel installation row is still around). Allow it, but\n // gate on channels:write so this isn't an \"any authenticated user\" backdoor.\n // Follow the same no-auth-configured pass-through as assertWriteAccess.\n const callerAuthorId = getCallerAuthorId(requestContext);\n if (!callerAuthorId && !requestContext.get(MASTRA_USER_KEY)) return;\n if (hasAdminBypass(requestContext, 'channels')) return;\n if (hasScopedPermission({ requestContext, resource: 'channels', action: 'write' })) return;\n\n throw new HTTPException(404, { message: 'Not found' });\n}\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\n/**\n * GET /channels/platforms - List available channel platforms\n */\nexport const LIST_CHANNEL_PLATFORMS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/platforms',\n responseType: 'json',\n responseSchema: listChannelPlatformsResponseSchema,\n summary: 'List channel platforms',\n description: 'Returns available channel platforms and their configuration status',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n assertChannelsAvailable();\n try {\n const channels = Object.values(mastra.channels ?? {});\n return channels.map(channel => {\n if (channel.getInfo) {\n return channel.getInfo();\n }\n return {\n id: channel.id,\n name: channel.id.charAt(0).toUpperCase() + channel.id.slice(1),\n isConfigured: true,\n };\n });\n } catch (error) {\n return handleError(error, 'Error listing channel platforms');\n }\n },\n});\n\n/**\n * GET /channels/:platform/installations - List installations for a platform\n */\nexport const LIST_CHANNEL_INSTALLATIONS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/:platform/installations',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n responseSchema: listChannelInstallationsResponseSchema,\n summary: 'List channel installations',\n description: 'Returns all active and pending installations for a channel platform',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, platform }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.listInstallations) {\n return [];\n }\n\n return await channel.listInstallations();\n } catch (error) {\n return handleError(error, 'Error listing channel installations');\n }\n },\n});\n\n/**\n * POST /channels/:platform/connect - Connect an agent to a platform\n */\nexport const CONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/connect',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n bodySchema: connectChannelBodySchema,\n responseSchema: connectChannelResponseSchema,\n summary: 'Connect agent to channel',\n description: 'Creates a platform app for the agent and returns an OAuth authorization URL',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId, options }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.connect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic connection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'connect');\n\n return await channel.connect(agentId, options);\n } catch (error) {\n return handleError(error, 'Error connecting agent to channel');\n }\n },\n});\n\n/**\n * POST /channels/:platform/:agentId/disconnect - Disconnect an agent from a platform\n */\nexport const DISCONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/:agentId/disconnect',\n responseType: 'json',\n pathParamSchema: channelAgentPathParams,\n responseSchema: disconnectChannelResponseSchema,\n summary: 'Disconnect agent from channel',\n description: 'Deletes the platform app and cleans up the installation',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.disconnect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic disconnection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'disconnect');\n\n await channel.disconnect(agentId);\n return { success: true };\n } catch (error) {\n return handleError(error, 'Error disconnecting agent from channel');\n }\n },\n});\n"],"mappings":";;;;;;;;AAMA,MAAa,4BAA4BA,OAAAA,EAAE,OAAO,EAChD,UAAUA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA6C,EAC7E,CAAC;AAED,MAAa,yBAAyBA,OAAAA,EAAE,OAAO;CAC7C,UAAUA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA6C;CAC3E,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,kBAAkB;AACjD,CAAC;AAMD,MAAa,2BAA2BA,OAAAA,EAAE,OAAO;CAC/C,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,6BAA6B;CAC1D,SAASA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,sCAAsC;AACvG,CAAC;AAMD,MAAM,4BAA4BA,OAAAA,EAAE,OAAO;CACzC,IAAIA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,qBAAqB;CAC7C,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,8BAA8B;CACxD,cAAcA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS,iDAAiD;CACpF,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Exception","getCallerAuthorId","hasAdminBypass","hasScopedPermission","createRoute","handleError"],"sources":["../src/server/schemas/channels.ts","../src/server/handlers/channels.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n// ============================================================================\n// Path Parameter Schemas\n// ============================================================================\n\nexport const channelPlatformPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n});\n\nexport const channelAgentPathParams = z.object({\n platform: z.string().describe('Channel platform identifier (e.g., \"slack\")'),\n agentId: z.string().describe('Agent identifier'),\n});\n\n// ============================================================================\n// Body Parameter Schemas\n// ============================================================================\n\nexport const connectChannelBodySchema = z.object({\n agentId: z.string().describe('Agent identifier to connect'),\n options: z.record(z.string(), z.unknown()).optional().describe('Platform-specific connection options'),\n});\n\n// ============================================================================\n// Response Schemas\n// ============================================================================\n\nconst channelPlatformInfoSchema = z.object({\n id: z.string().describe('Platform identifier'),\n name: z.string().describe('Human-readable platform name'),\n isConfigured: z.boolean().describe('Whether the platform is ready to connect agents'),\n connectOptionsSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for connect options'),\n});\n\nconst channelInstallationInfoSchema = z.object({\n id: z.string().describe('Installation identifier'),\n platform: z.string().describe('Platform identifier'),\n agentId: z.string().describe('Connected agent identifier'),\n status: z.enum(['active', 'pending']).describe('Installation status'),\n displayName: z.string().optional().describe('Platform-specific display name'),\n installedAt: z.coerce.date().optional().describe('Installation timestamp'),\n});\n\nconst channelConnectOAuthSchema = z.object({\n type: z.literal('oauth').describe('OAuth-based connection requiring browser redirect'),\n authorizationUrl: z.string().describe('OAuth authorization URL for user redirect'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectDeepLinkSchema = z.object({\n type: z.literal('deep_link').describe('Deep-link connection requiring native app interaction'),\n url: z.string().describe('Deep link URL to open in platform app'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectImmediateSchema = z.object({\n type: z.literal('immediate').describe('Immediate connection with no user interaction needed'),\n installationId: z.string().describe('Installation identifier'),\n});\n\nconst channelConnectResultSchema = z.discriminatedUnion('type', [\n channelConnectOAuthSchema,\n channelConnectDeepLinkSchema,\n channelConnectImmediateSchema,\n]);\n\nexport const listChannelPlatformsResponseSchema = z.array(channelPlatformInfoSchema);\n\nexport const listChannelInstallationsResponseSchema = z.array(channelInstallationInfoSchema);\n\nexport const connectChannelResponseSchema = channelConnectResultSchema;\n\nexport const disconnectChannelResponseSchema = z.object({\n success: z.boolean(),\n});\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\nimport type { RequestContext } from '@mastra/core/di';\nimport { coreFeatures } from '@mastra/core/features';\n\nimport { MASTRA_USER_KEY } from '../constants';\nimport { HTTPException } from '../http-exception';\nimport {\n channelPlatformPathParams,\n channelAgentPathParams,\n connectChannelBodySchema,\n listChannelPlatformsResponseSchema,\n listChannelInstallationsResponseSchema,\n connectChannelResponseSchema,\n disconnectChannelResponseSchema,\n} from '../schemas/channels';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { assertWriteAccess, getCallerAuthorId, hasAdminBypass, hasScopedPermission } from './authorship';\nimport { handleError } from './error';\n\n// ============================================================================\n// Feature gate + helpers\n// ============================================================================\n\nfunction assertChannelsAvailable(): void {\n if (!coreFeatures.has('channels')) {\n throw new HTTPException(501, { message: 'Channels require a newer version of @mastra/core' });\n }\n}\n\nfunction getChannelOrThrow(mastra: Mastra, platform: string): ChannelProvider {\n const channels = Object.values(mastra.channels ?? {});\n const channel = channels.find(c => c.id === platform);\n if (!channel) {\n const available = channels.map(c => c.id).join(', ');\n throw new HTTPException(404, {\n message: `Channel \"${platform}\" is not registered. Available: ${available || 'none'}`,\n });\n }\n return channel;\n}\n\n/**\n * Unified connect/disconnect authorization.\n *\n * - Stored agent exists → same write access as editing the agent record.\n * - Code-defined agent (no stored record) → route's `requiresAuth` is the gate.\n * - Agent doesn't exist anywhere:\n * - connect → 404 (can't connect a channel to a non-existent agent)\n * - disconnect → orphan cleanup, gated on `channels:write`\n */\nasync function assertChannelAgentWriteAccess(\n mastra: Mastra,\n requestContext: RequestContext,\n agentId: string,\n action: 'connect' | 'disconnect',\n): Promise<void> {\n const storage = mastra.getStorage();\n const agentsStore = storage ? await storage.getStore('agents') : null;\n const stored = agentsStore ? await agentsStore.getById(agentId) : null;\n\n if (stored) {\n assertWriteAccess({\n requestContext,\n resource: 'agents',\n resourceId: agentId,\n action: 'edit',\n record: stored,\n });\n return;\n }\n\n // Not in stored-agents (or storage doesn't support it). Check the runtime\n // registry for a code-defined agent.\n const codeDefined = mastra.getAgentById(agentId);\n if (codeDefined) {\n // Code-defined agents have no owner/ACL — route's requiresAuth /\n // requiresPermission is the gate. Pass-through.\n return;\n }\n\n if (action === 'connect') {\n throw new HTTPException(404, { message: `Agent \"${agentId}\" not found` });\n }\n\n // Disconnect against an unknown agentId = orphan cleanup (stored agent was\n // deleted but the channel installation row is still around). Allow it, but\n // gate on channels:write so this isn't an \"any authenticated user\" backdoor.\n // Follow the same no-auth-configured pass-through as assertWriteAccess.\n const callerAuthorId = getCallerAuthorId(requestContext);\n if (!callerAuthorId && !requestContext.get(MASTRA_USER_KEY)) return;\n if (hasAdminBypass(requestContext, 'channels')) return;\n if (hasScopedPermission({ requestContext, resource: 'channels', action: 'write' })) return;\n\n throw new HTTPException(404, { message: 'Not found' });\n}\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\n/**\n * GET /channels/platforms - List available channel platforms\n */\nexport const LIST_CHANNEL_PLATFORMS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/platforms',\n responseType: 'json',\n responseSchema: listChannelPlatformsResponseSchema,\n summary: 'List channel platforms',\n description: 'Returns available channel platforms and their configuration status',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n assertChannelsAvailable();\n try {\n const channels = Object.values(mastra.channels ?? {});\n return channels.map(channel => {\n if (channel.getInfo) {\n return channel.getInfo();\n }\n return {\n id: channel.id,\n name: channel.id.charAt(0).toUpperCase() + channel.id.slice(1),\n isConfigured: true,\n };\n });\n } catch (error) {\n return handleError(error, 'Error listing channel platforms');\n }\n },\n});\n\n/**\n * GET /channels/:platform/installations - List installations for a platform\n */\nexport const LIST_CHANNEL_INSTALLATIONS_ROUTE = createRoute({\n method: 'GET',\n path: '/channels/:platform/installations',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n responseSchema: listChannelInstallationsResponseSchema,\n summary: 'List channel installations',\n description: 'Returns all active and pending installations for a channel platform',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, platform }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.listInstallations) {\n return [];\n }\n\n return await channel.listInstallations();\n } catch (error) {\n return handleError(error, 'Error listing channel installations');\n }\n },\n});\n\n/**\n * POST /channels/:platform/connect - Connect an agent to a platform\n */\nexport const CONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/connect',\n responseType: 'json',\n pathParamSchema: channelPlatformPathParams,\n bodySchema: connectChannelBodySchema,\n responseSchema: connectChannelResponseSchema,\n summary: 'Connect agent to channel',\n description: 'Creates a platform app for the agent and returns an OAuth authorization URL',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId, options }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.connect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic connection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'connect');\n\n return await channel.connect(agentId, options);\n } catch (error) {\n return handleError(error, 'Error connecting agent to channel');\n }\n },\n});\n\n/**\n * POST /channels/:platform/:agentId/disconnect - Disconnect an agent from a platform\n */\nexport const DISCONNECT_CHANNEL_ROUTE = createRoute({\n method: 'POST',\n path: '/channels/:platform/:agentId/disconnect',\n responseType: 'json',\n pathParamSchema: channelAgentPathParams,\n responseSchema: disconnectChannelResponseSchema,\n summary: 'Disconnect agent from channel',\n description: 'Deletes the platform app and cleans up the installation',\n tags: ['Channels'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, platform, agentId }) => {\n assertChannelsAvailable();\n try {\n const channel = getChannelOrThrow(mastra, platform);\n\n if (!channel.disconnect) {\n throw new HTTPException(400, {\n message: `Channel \"${platform}\" does not support programmatic disconnection`,\n });\n }\n\n await assertChannelAgentWriteAccess(mastra, requestContext, agentId, 'disconnect');\n\n await channel.disconnect(agentId);\n return { success: true };\n } catch (error) {\n return handleError(error, 'Error disconnecting agent from channel');\n }\n },\n});\n"],"mappings":";;;;;;;;AAMA,MAAa,4BAA4BA,OAAAA,EAAE,OAAO,EAChD,UAAUA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA6C,EAC7E,CAAC;AAED,MAAa,yBAAyBA,OAAAA,EAAE,OAAO;CAC7C,UAAUA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA6C;CAC3E,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,kBAAkB;AACjD,CAAC;AAMD,MAAa,2BAA2BA,OAAAA,EAAE,OAAO;CAC/C,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,6BAA6B;CAC1D,SAASA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,sCAAsC;AACvG,CAAC;AAMD,MAAM,4BAA4BA,OAAAA,EAAE,OAAO;CACzC,IAAIA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,qBAAqB;CAC7C,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,8BAA8B;CACxD,cAAcA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS,iDAAiD;CACpF,sBAAsBA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CA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CACN,cAAc;CACd,iBAAiB;CACjB,YAAY;CACZ,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,UAAU;CACjB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,gBAAgB,UAAU,SAAS,cAAc;EACzE,wBAAwB;EACxB,IAAI;GACF,MAAM,UAAU,kBAAkB,QAAQ,QAAQ;GAElD,IAAI,CAAC,QAAQ,SACX,MAAM,IAAIJ,uBAAAA,cAAc,KAAK,EAC3B,SAAS,YAAY,SAAS,4CAChC,CAAC;GAGH,MAAM,8BAA8B,QAAQ,gBAAgB,SAAS,SAAS;GAE9E,OAAO,MAAM,QAAQ,QAAQ,SAAS,OAAO;EAC/C,SAAS,OAAO;GACd,OAAOK,8BAAAA,YAAY,OAAO,mCAAmC;EAC/D;CACF;AACF,CAAC;;;;AAKD,MAAa,2BAA2BD,sBAAAA,YAAY;CAClD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,UAAU;CACjB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,gBAAgB,UAAU,cAAc;EAChE,wBAAwB;EACxB,IAAI;GACF,MAAM,UAAU,kBAAkB,QAAQ,QAAQ;GAElD,IAAI,CAAC,QAAQ,YACX,MAAM,IAAIJ,uBAAAA,cAAc,KAAK,EAC3B,SAAS,YAAY,SAAS,+CAChC,CAAC;GAGH,MAAM,8BAA8B,QAAQ,gBAAgB,SAAS,YAAY;GAEjF,MAAM,QAAQ,WAAW,OAAO;GAChC,OAAO,EAAE,SAAS,KAAK;EACzB,SAAS,OAAO;GACd,OAAOK,8BAAAA,YAAY,OAAO,wCAAwC;EACpE;CACF;AACF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { C as getThreadByIdResponseSchema } from "./memory-CjWJYFVI.js";
1
+ import { C as getThreadByIdResponseSchema } from "./memory-Cp3Yo-OX.js";
2
2
  import { n as conversationItemSchema } from "./responses-DJNJgCTg.js";
3
3
  import z from "zod";
4
4
  //#region src/server/schemas/conversations.ts
@@ -30,4 +30,4 @@ const conversationItemsListSchema = z.object({
30
30
  //#endregion
31
31
  export { createConversationBodySchema as a, conversationObjectSchema as i, conversationIdPathParams as n, conversationItemsListSchema as r, conversationDeletedSchema as t };
32
32
 
33
- //# sourceMappingURL=conversations-D89Io31L.js.map
33
+ //# sourceMappingURL=conversations-Bs-k9f9N.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"conversations-D89Io31L.js","names":[],"sources":["../src/server/schemas/conversations.ts"],"sourcesContent":["import z from 'zod';\nimport { getThreadByIdResponseSchema } from './memory';\nimport { conversationItemSchema } from './responses';\n\nexport const conversationIdPathParams = z.object({\n conversationId: z.string().describe('Unique identifier for the conversation thread'),\n});\n\nexport const createConversationBodySchema = z.object({\n agent_id: z.string().describe('Mastra agent ID used to create the conversation thread'),\n conversation_id: z.string().optional().describe('Optional conversation ID to use as the raw threadId'),\n resource_id: z.string().optional().describe('Optional resource ID to associate with the conversation'),\n title: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type CreateConversationBody = z.infer<typeof createConversationBodySchema>;\n\nexport const conversationObjectSchema = z.object({\n id: z.string(),\n object: z.literal('conversation'),\n thread: getThreadByIdResponseSchema,\n});\n\nexport const conversationDeletedSchema = z.object({\n id: z.string(),\n object: z.literal('conversation.deleted'),\n deleted: z.literal(true),\n});\n\nexport const conversationItemsListSchema = z.object({\n object: z.literal('list'),\n data: z.array(conversationItemSchema),\n first_id: z.string().nullable(),\n last_id: z.string().nullable(),\n has_more: z.boolean(),\n});\n\nexport type ConversationObject = z.infer<typeof conversationObjectSchema>;\nexport type ConversationItemsList = z.infer<typeof conversationItemsListSchema>;\nexport type ConversationDeleted = z.infer<typeof conversationDeletedSchema>;\n"],"mappings":";;;;AAIA,MAAa,2BAA2B,EAAE,OAAO,EAC/C,gBAAgB,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA+C,EACrF,CAAC;AAED,MAAa,+BAA+B,EAAE,OAAO;CACnD,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS,wDAAwD;CACtF,iBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,qDAAqD;CACrG,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CACrG,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC;AAID,MAAa,2BAA2B,EAAE,OAAO;CAC/C,IAAI,EAAE,OAAO;CACb,QAAQ,EAAE,QAAQ,cAAc;CAChC,QAAQ;AACV,CAAC;AAED,MAAa,4BAA4B,EAAE,OAAO;CAChD,IAAI,EAAE,OAAO;CACb,QAAQ,EAAE,QAAQ,sBAAsB;CACxC,SAAS,EAAE,QAAQ,IAAI;AACzB,CAAC;AAED,MAAa,8BAA8B,EAAE,OAAO;CAClD,QAAQ,EAAE,QAAQ,MAAM;CACxB,MAAM,EAAE,MAAM,sBAAsB;CACpC,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,UAAU,EAAE,QAAQ;AACtB,CAAC"}
1
+ {"version":3,"file":"conversations-Bs-k9f9N.js","names":[],"sources":["../src/server/schemas/conversations.ts"],"sourcesContent":["import z from 'zod';\nimport { getThreadByIdResponseSchema } from './memory';\nimport { conversationItemSchema } from './responses';\n\nexport const conversationIdPathParams = z.object({\n conversationId: z.string().describe('Unique identifier for the conversation thread'),\n});\n\nexport const createConversationBodySchema = z.object({\n agent_id: z.string().describe('Mastra agent ID used to create the conversation thread'),\n conversation_id: z.string().optional().describe('Optional conversation ID to use as the raw threadId'),\n resource_id: z.string().optional().describe('Optional resource ID to associate with the conversation'),\n title: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type CreateConversationBody = z.infer<typeof createConversationBodySchema>;\n\nexport const conversationObjectSchema = z.object({\n id: z.string(),\n object: z.literal('conversation'),\n thread: getThreadByIdResponseSchema,\n});\n\nexport const conversationDeletedSchema = z.object({\n id: z.string(),\n object: z.literal('conversation.deleted'),\n deleted: z.literal(true),\n});\n\nexport const conversationItemsListSchema = z.object({\n object: z.literal('list'),\n data: z.array(conversationItemSchema),\n first_id: z.string().nullable(),\n last_id: z.string().nullable(),\n has_more: z.boolean(),\n});\n\nexport type ConversationObject = z.infer<typeof conversationObjectSchema>;\nexport type ConversationItemsList = z.infer<typeof conversationItemsListSchema>;\nexport type ConversationDeleted = z.infer<typeof conversationDeletedSchema>;\n"],"mappings":";;;;AAIA,MAAa,2BAA2B,EAAE,OAAO,EAC/C,gBAAgB,EAAE,OAAO,CAAC,CAAC,SAAS,+CAA+C,EACrF,CAAC;AAED,MAAa,+BAA+B,EAAE,OAAO;CACnD,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS,wDAAwD;CACtF,iBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,qDAAqD;CACrG,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CACrG,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC;AAID,MAAa,2BAA2B,EAAE,OAAO;CAC/C,IAAI,EAAE,OAAO;CACb,QAAQ,EAAE,QAAQ,cAAc;CAChC,QAAQ;AACV,CAAC;AAED,MAAa,4BAA4B,EAAE,OAAO;CAChD,IAAI,EAAE,OAAO;CACb,QAAQ,EAAE,QAAQ,sBAAsB;CACxC,SAAS,EAAE,QAAQ,IAAI;AACzB,CAAC;AAED,MAAa,8BAA8B,EAAE,OAAO;CAClD,QAAQ,EAAE,QAAQ,MAAM;CACxB,MAAM,EAAE,MAAM,sBAAsB;CACpC,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,UAAU,EAAE,QAAQ;AACtB,CAAC"}
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-Bd6kNlEP.cjs");
2
- const require_memory = require("./memory-CVODqy7m.cjs");
2
+ const require_memory = require("./memory-CE6rUGmo.cjs");
3
3
  const require_responses = require("./responses-CKNdSRkS.cjs");
4
4
  let zod = require("zod");
5
5
  zod = require_rolldown_runtime.__toESM(zod, 1);
@@ -61,4 +61,4 @@ Object.defineProperty(exports, "createConversationBodySchema", {
61
61
  }
62
62
  });
63
63
 
64
- //# sourceMappingURL=conversations-DJybpnE5.cjs.map
64
+ //# sourceMappingURL=conversations-o3AEJjRo.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"conversations-DJybpnE5.cjs","names":["z","getThreadByIdResponseSchema","conversationItemSchema"],"sources":["../src/server/schemas/conversations.ts"],"sourcesContent":["import z from 'zod';\nimport { getThreadByIdResponseSchema } from './memory';\nimport { conversationItemSchema } from './responses';\n\nexport const conversationIdPathParams = z.object({\n conversationId: z.string().describe('Unique identifier for the conversation thread'),\n});\n\nexport const createConversationBodySchema = z.object({\n agent_id: z.string().describe('Mastra agent ID used to create the conversation thread'),\n conversation_id: z.string().optional().describe('Optional conversation ID to use as the raw threadId'),\n resource_id: z.string().optional().describe('Optional resource ID to associate with the conversation'),\n title: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type CreateConversationBody = z.infer<typeof createConversationBodySchema>;\n\nexport const conversationObjectSchema = z.object({\n id: z.string(),\n object: z.literal('conversation'),\n thread: getThreadByIdResponseSchema,\n});\n\nexport const conversationDeletedSchema = z.object({\n id: z.string(),\n object: z.literal('conversation.deleted'),\n deleted: z.literal(true),\n});\n\nexport const conversationItemsListSchema = z.object({\n object: z.literal('list'),\n data: z.array(conversationItemSchema),\n first_id: z.string().nullable(),\n last_id: z.string().nullable(),\n has_more: z.boolean(),\n});\n\nexport type ConversationObject = z.infer<typeof conversationObjectSchema>;\nexport type ConversationItemsList = z.infer<typeof conversationItemsListSchema>;\nexport type ConversationDeleted = z.infer<typeof conversationDeletedSchema>;\n"],"mappings":";;;;;;AAIA,MAAa,2BAA2BA,IAAAA,QAAE,OAAO,EAC/C,gBAAgBA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,+CAA+C,EACrF,CAAC;AAED,MAAa,+BAA+BA,IAAAA,QAAE,OAAO;CACnD,UAAUA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,wDAAwD;CACtF,iBAAiBA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,qDAAqD;CACrG,aAAaA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CACrG,OAAOA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAAA,QAAE,OAAOA,IAAAA,QAAE,OAAO,GAAGA,IAAAA,QAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC;AAID,MAAa,2BAA2BA,IAAAA,QAAE,OAAO;CAC/C,IAAIA,IAAAA,QAAE,OAAO;CACb,QAAQA,IAAAA,QAAE,QAAQ,cAAc;CAChC,QAAQC,eAAAA;AACV,CAAC;AAED,MAAa,4BAA4BD,IAAAA,QAAE,OAAO;CAChD,IAAIA,IAAAA,QAAE,OAAO;CACb,QAAQA,IAAAA,QAAE,QAAQ,sBAAsB;CACxC,SAASA,IAAAA,QAAE,QAAQ,IAAI;AACzB,CAAC;AAED,MAAa,8BAA8BA,IAAAA,QAAE,OAAO;CAClD,QAAQA,IAAAA,QAAE,QAAQ,MAAM;CACxB,MAAMA,IAAAA,QAAE,MAAME,kBAAAA,sBAAsB;CACpC,UAAUF,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,SAASA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,UAAUA,IAAAA,QAAE,QAAQ;AACtB,CAAC"}
1
+ {"version":3,"file":"conversations-o3AEJjRo.cjs","names":["z","getThreadByIdResponseSchema","conversationItemSchema"],"sources":["../src/server/schemas/conversations.ts"],"sourcesContent":["import z from 'zod';\nimport { getThreadByIdResponseSchema } from './memory';\nimport { conversationItemSchema } from './responses';\n\nexport const conversationIdPathParams = z.object({\n conversationId: z.string().describe('Unique identifier for the conversation thread'),\n});\n\nexport const createConversationBodySchema = z.object({\n agent_id: z.string().describe('Mastra agent ID used to create the conversation thread'),\n conversation_id: z.string().optional().describe('Optional conversation ID to use as the raw threadId'),\n resource_id: z.string().optional().describe('Optional resource ID to associate with the conversation'),\n title: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type CreateConversationBody = z.infer<typeof createConversationBodySchema>;\n\nexport const conversationObjectSchema = z.object({\n id: z.string(),\n object: z.literal('conversation'),\n thread: getThreadByIdResponseSchema,\n});\n\nexport const conversationDeletedSchema = z.object({\n id: z.string(),\n object: z.literal('conversation.deleted'),\n deleted: z.literal(true),\n});\n\nexport const conversationItemsListSchema = z.object({\n object: z.literal('list'),\n data: z.array(conversationItemSchema),\n first_id: z.string().nullable(),\n last_id: z.string().nullable(),\n has_more: z.boolean(),\n});\n\nexport type ConversationObject = z.infer<typeof conversationObjectSchema>;\nexport type ConversationItemsList = z.infer<typeof conversationItemsListSchema>;\nexport type ConversationDeleted = z.infer<typeof conversationDeletedSchema>;\n"],"mappings":";;;;;;AAIA,MAAa,2BAA2BA,IAAAA,QAAE,OAAO,EAC/C,gBAAgBA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,+CAA+C,EACrF,CAAC;AAED,MAAa,+BAA+BA,IAAAA,QAAE,OAAO;CACnD,UAAUA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,wDAAwD;CACtF,iBAAiBA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,qDAAqD;CACrG,aAAaA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CACrG,OAAOA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAAA,QAAE,OAAOA,IAAAA,QAAE,OAAO,GAAGA,IAAAA,QAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC;AAID,MAAa,2BAA2BA,IAAAA,QAAE,OAAO;CAC/C,IAAIA,IAAAA,QAAE,OAAO;CACb,QAAQA,IAAAA,QAAE,QAAQ,cAAc;CAChC,QAAQC,eAAAA;AACV,CAAC;AAED,MAAa,4BAA4BD,IAAAA,QAAE,OAAO;CAChD,IAAIA,IAAAA,QAAE,OAAO;CACb,QAAQA,IAAAA,QAAE,QAAQ,sBAAsB;CACxC,SAASA,IAAAA,QAAE,QAAQ,IAAI;AACzB,CAAC;AAED,MAAa,8BAA8BA,IAAAA,QAAE,OAAO;CAClD,QAAQA,IAAAA,QAAE,QAAQ,MAAM;CACxB,MAAMA,IAAAA,QAAE,MAAME,kBAAAA,sBAAsB;CACpC,UAAUF,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,SAASA,IAAAA,QAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,UAAUA,IAAAA,QAAE,QAAQ;AACtB,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { o as __toESM$1, t as __commonJSMin$1 } from "./rolldown-runtime-maW3aOIk.js";
2
- import { n as standardSchemaToJSONSchema, r as toStandardSchema$1, t as isStandardSchemaWithJSON$1 } from "./schema-Bv9OdW1f-DLSJSqQv.js";
3
- import "./schema-CGeYTFwm.js";
2
+ import { n as standardSchemaToJSONSchema, r as toStandardSchema$1, t as isStandardSchemaWithJSON$1 } from "./schema-D_ikovK6-BzTeMhWf.js";
3
+ import "./schema-BF_cZG0Y.js";
4
4
  import { t as require_sync } from "./sync-BG15Yae1.js";
5
5
  import { openai } from "./dist-DoTDZ7wF.js";
6
6
  import { createRequire } from "module";
@@ -4693,7 +4693,7 @@ function splitLines(text) {
4693
4693
  return result;
4694
4694
  }
4695
4695
  //#endregion
4696
- //#region ../memory/dist/src-BNyqEQlx.js
4696
+ //#region ../memory/dist/src-TN3MwGgP.js
4697
4697
  var __defProp$3 = Object.defineProperty;
4698
4698
  var __exportAll = (all, no_symbols) => {
4699
4699
  let target = {};
@@ -34738,8 +34738,35 @@ const DEFAULT_TOP_K = 4;
34738
34738
  const VECTOR_DELETE_BATCH_SIZE = 100;
34739
34739
  const DEFAULT_EMBEDDING_CACHE_MAX_SIZE = 1e3;
34740
34740
  /**
34741
- * Concrete implementation of MastraMemory that adds support for thread configuration
34742
- * and message injection.
34741
+ * Gives Mastra agents conversation history, with optional working memory,
34742
+ * semantic recall, and observational memory.
34743
+ *
34744
+ * @remarks
34745
+ * Configure storage on this instance or its Mastra instance before use.
34746
+ * See the bundled docs for setup and conversation identifiers.
34747
+ *
34748
+ * @example
34749
+ * Attach memory to an agent; `yourModel` is your configured model.
34750
+ * ```typescript
34751
+ * import { Agent } from '@mastra/core/agent';
34752
+ * import { Memory } from '@mastra/memory';
34753
+ *
34754
+ * const agent = new Agent({
34755
+ * id: 'assistant',
34756
+ * name: 'Assistant',
34757
+ * instructions: 'You are a helpful assistant.',
34758
+ * model: yourModel,
34759
+ * memory: new Memory(),
34760
+ * });
34761
+ * ```
34762
+ *
34763
+ * @see For documentation bundled with your installed package, locate
34764
+ * `@mastra/memory/package.json` with your project's resolver or package-manager
34765
+ * tooling, then read `dist/docs/SKILL.md` from that package root and follow its
34766
+ * reference links. Use package-manager tools for virtual or archived packages.
34767
+ *
34768
+ * @see [Memory documentation](https://mastra.ai/docs/memory/overview)
34769
+ * if packaged docs are unavailable.
34743
34770
  */
34744
34771
  var Memory = class Memory extends MastraMemory {
34745
34772
  _omEngine;
@@ -36338,18 +36365,40 @@ Notes:
36338
36365
  * ```
36339
36366
  */
36340
36367
  async cloneThread(args, memoryConfig) {
36341
- const memoryStore = await this.getMemoryStore();
36342
- const config = this.getMergedThreadConfig(memoryConfig);
36343
- const requestedHydrate = args.options?.hydrateMessages ?? true;
36344
- const effectiveHydrate = requestedHydrate || Boolean(this.vector && this.embedder && config.semanticRecall);
36345
- const result = await memoryStore.cloneThread(effectiveHydrate === requestedHydrate ? args : {
36346
- ...args,
36347
- options: {
36348
- ...args.options,
36349
- hydrateMessages: effectiveHydrate
36368
+ const result = await this.copyThread(args, memoryConfig);
36369
+ const { messages } = await (await this.getMemoryStore()).listMessages({
36370
+ threadId: result.thread.id,
36371
+ resourceId: result.thread.resourceId,
36372
+ perPage: false,
36373
+ orderBy: {
36374
+ field: "createdAt",
36375
+ direction: "ASC"
36350
36376
  }
36351
36377
  });
36378
+ return {
36379
+ ...result,
36380
+ clonedMessages: messages
36381
+ };
36382
+ }
36383
+ /**
36384
+ * Copies a thread with all its messages to a new thread without returning the
36385
+ * message payloads. Working memory, observational memory, and semantic-recall
36386
+ * embeddings are carried over exactly as with `cloneThread`; the only difference
36387
+ * is that message content never has to be held in the Node heap at once.
36388
+ *
36389
+ * Use this instead of `cloneThread` when only the new thread id is needed
36390
+ * (e.g. forking a conversation for a subagent).
36391
+ *
36392
+ * @param args - Clone parameters, same as `cloneThread`
36393
+ * @param memoryConfig - Optional memory configuration override
36394
+ * @returns The newly created thread and the source→new message id map
36395
+ */
36396
+ async copyThread(args, memoryConfig) {
36397
+ const memoryStore = await this.getMemoryStore();
36398
+ const config = this.getMergedThreadConfig(memoryConfig);
36399
+ const result = await memoryStore.copyThread(args);
36352
36400
  const sourceResourceId = (await this.getThreadById({ threadId: args.sourceThreadId }))?.resourceId;
36401
+ let priorDestinationResourceWm;
36353
36402
  if (config.workingMemory?.enabled) {
36354
36403
  const scope = config.workingMemory.scope || "resource";
36355
36404
  if (scope === "thread" || scope === "resource" && args.resourceId && args.resourceId !== sourceResourceId) {
@@ -36358,28 +36407,125 @@ Notes:
36358
36407
  resourceId: sourceResourceId,
36359
36408
  memoryConfig
36360
36409
  });
36361
- if (sourceWm) await this.updateWorkingMemory({
36362
- threadId: result.thread.id,
36363
- resourceId: result.thread.resourceId,
36364
- workingMemory: sourceWm,
36365
- memoryConfig
36366
- });
36410
+ if (sourceWm) {
36411
+ if (scope === "resource") priorDestinationResourceWm = (await memoryStore.getResourceById({ resourceId: result.thread.resourceId }))?.workingMemory ?? null;
36412
+ await this.updateWorkingMemory({
36413
+ threadId: result.thread.id,
36414
+ resourceId: result.thread.resourceId,
36415
+ workingMemory: sourceWm,
36416
+ memoryConfig
36417
+ });
36418
+ }
36367
36419
  }
36368
36420
  }
36369
36421
  if (memoryStore.supportsObservationalMemory && sourceResourceId) try {
36370
36422
  await this.cloneObservationalMemory(memoryStore, args.sourceThreadId, sourceResourceId, result);
36371
36423
  } catch (error) {
36372
- try {
36373
- await memoryStore.deleteThread({ threadId: result.thread.id });
36374
- } catch (rollbackError) {
36375
- this.logger.error("Failed to rollback cloned thread after OM clone failure", rollbackError);
36376
- }
36424
+ await this.rollbackCopiedThread(memoryStore, result.thread, "OM clone", false, priorDestinationResourceWm);
36425
+ throw error;
36426
+ }
36427
+ if (this.vector && this.embedder && config.semanticRecall) try {
36428
+ await this.embedCopiedMessagesInBatches(memoryStore, result, config);
36429
+ } catch (error) {
36430
+ await this.rollbackCopiedThread(memoryStore, result.thread, "embedding", true, priorDestinationResourceWm);
36377
36431
  throw error;
36378
36432
  }
36379
- if (this.vector && config.semanticRecall && result.clonedMessages.length > 0) await this.embedClonedMessages(result.clonedMessages, config);
36380
36433
  return result;
36381
36434
  }
36382
36435
  /**
36436
+ * Best-effort compensation when a later step of copyThread fails after the destination thread
36437
+ * was persisted. deleteThread removes the thread, its messages and thread-scoped working memory.
36438
+ * `priorDestinationResourceWm` is the destination resource's working memory before the copy
36439
+ * overwrote it (`null` = none existed); when defined it is restored. When `afterOmClone` is set the OM step already succeeded, so the thread-scoped OM record and
36440
+ * any vectors written so far are dropped too. Resource-scoped OM is left alone: it may be
36441
+ * shared with a pre-existing resource and isn't safe to clear blindly.
36442
+ */
36443
+ async rollbackCopiedThread(memoryStore, thread, failedStep, afterOmClone, priorDestinationResourceWm) {
36444
+ const threadId = thread.id;
36445
+ try {
36446
+ await memoryStore.deleteThread({ threadId });
36447
+ } catch (rollbackError) {
36448
+ this.logger.error(`Failed to rollback copied thread after ${failedStep} failure`, rollbackError);
36449
+ }
36450
+ if (priorDestinationResourceWm !== void 0) try {
36451
+ await memoryStore.updateResource({
36452
+ resourceId: thread.resourceId,
36453
+ workingMemory: priorDestinationResourceWm ?? ""
36454
+ });
36455
+ } catch (rollbackError) {
36456
+ this.logger.error(`Failed to restore resource working memory after ${failedStep} failure`, rollbackError);
36457
+ }
36458
+ if (!afterOmClone) return;
36459
+ if (memoryStore.supportsObservationalMemory) try {
36460
+ await memoryStore.clearObservationalMemory(threadId, thread.resourceId);
36461
+ } catch (rollbackError) {
36462
+ this.logger.error(`Failed to rollback copied thread OM after ${failedStep} failure`, rollbackError);
36463
+ }
36464
+ try {
36465
+ const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
36466
+ await Promise.all(messageIndexes.map((indexName) => this.vector.deleteVectors({
36467
+ indexName,
36468
+ filter: { thread_id: threadId }
36469
+ })));
36470
+ } catch (rollbackError) {
36471
+ this.logger.error(`Failed to rollback copied thread vectors after ${failedStep} failure`, rollbackError);
36472
+ }
36473
+ }
36474
+ static CLONE_EMBED_PAGE_SIZE = 100;
36475
+ async embedCopiedMessagesInBatches(memoryStore, copied, config) {
36476
+ const size = Memory.CLONE_EMBED_PAGE_SIZE;
36477
+ const copiedIds = Object.values(copied.messageIdMap ?? {});
36478
+ if (copiedIds.length > 0) {
36479
+ for (let i = 0; i < copiedIds.length; i += size) {
36480
+ const { messages } = await memoryStore.listMessagesById({ messageIds: copiedIds.slice(i, i + size) });
36481
+ if (messages.length > 0) await this.embedClonedMessages(messages, config);
36482
+ }
36483
+ return;
36484
+ }
36485
+ const { messages } = await memoryStore.listMessages({
36486
+ threadId: copied.thread.id,
36487
+ resourceId: copied.thread.resourceId,
36488
+ perPage: false,
36489
+ includeTotal: false
36490
+ });
36491
+ for (let i = 0; i < messages.length; i += size) await this.embedClonedMessages(messages.slice(i, i + size), config);
36492
+ }
36493
+ async updateThreadResourceId({ threadId, resourceId, memoryConfig }) {
36494
+ const memoryStore = await this.getMemoryStore();
36495
+ const config = this.getMergedThreadConfig(memoryConfig);
36496
+ const migratesVectors = Boolean(this.vector && this.embedder && config.semanticRecall);
36497
+ if (!migratesVectors) {
36498
+ const existing = await memoryStore.getThreadById({ threadId });
36499
+ if (existing && existing.resourceId === resourceId) return existing;
36500
+ }
36501
+ const thread = await memoryStore.updateThreadResourceId({
36502
+ threadId,
36503
+ resourceId
36504
+ });
36505
+ if (migratesVectors) try {
36506
+ const { messages } = await memoryStore.listMessages({
36507
+ threadId,
36508
+ perPage: false
36509
+ });
36510
+ const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
36511
+ await Promise.all(messageIndexes.map(async (indexName) => {
36512
+ await this.vector.deleteVectors({
36513
+ indexName,
36514
+ filter: { thread_id: threadId }
36515
+ });
36516
+ }));
36517
+ if (messages.length > 0) await this.embedClonedMessages(messages, config);
36518
+ } catch (error) {
36519
+ this.logger.error("Failed to migrate semantic-recall vectors during thread transfer", {
36520
+ threadId,
36521
+ resourceId,
36522
+ error: error instanceof Error ? error.message : String(error)
36523
+ });
36524
+ throw new Error(`Thread "${threadId}" was transferred to resource "${resourceId}", but migrating its semantic-recall vectors failed. The thread's messages may not surface under resource-scoped recall until the vectors are re-indexed. Cause: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
36525
+ }
36526
+ return thread;
36527
+ }
36528
+ /**
36383
36529
  * Clone observational memory records when cloning a thread.
36384
36530
  * Thread-scoped: always cloned to the new thread.
36385
36531
  * Resource-scoped: cloned only when the resourceId changes (same resourceId shares OM naturally).
@@ -47062,4 +47208,4 @@ const agentBuilderWorkflows = {
47062
47208
  //#endregion
47063
47209
  export { agentBuilderWorkflows };
47064
47210
 
47065
- //# sourceMappingURL=dist-B8gYiHIX.js.map
47211
+ //# sourceMappingURL=dist-Bw-Zrv4_.js.map