{"version":3,"file":"channels-BRoq3VKR.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,I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