'use strict';

var chunkHDIYJI2Z_cjs = require('./chunk-HDIYJI2Z.cjs');
var chunkSXKQ7CSX_cjs = require('./chunk-SXKQ7CSX.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var features = require('@mastra/core/features');
var v4 = require('zod/v4');

var channelPlatformPathParams = v4.z.object({
  platform: v4.z.string().describe('Channel platform identifier (e.g., "slack")')
});
var channelAgentPathParams = v4.z.object({
  platform: v4.z.string().describe('Channel platform identifier (e.g., "slack")'),
  agentId: v4.z.string().describe("Agent identifier")
});
var connectChannelBodySchema = v4.z.object({
  agentId: v4.z.string().describe("Agent identifier to connect"),
  options: v4.z.record(v4.z.string(), v4.z.unknown()).optional().describe("Platform-specific connection options")
});
var channelPlatformInfoSchema = v4.z.object({
  id: v4.z.string().describe("Platform identifier"),
  name: v4.z.string().describe("Human-readable platform name"),
  isConfigured: v4.z.boolean().describe("Whether the platform is ready to connect agents"),
  connectOptionsSchema: v4.z.record(v4.z.string(), v4.z.unknown()).optional().describe("JSON Schema for connect options")
});
var channelInstallationInfoSchema = v4.z.object({
  id: v4.z.string().describe("Installation identifier"),
  platform: v4.z.string().describe("Platform identifier"),
  agentId: v4.z.string().describe("Connected agent identifier"),
  status: v4.z.enum(["active", "pending"]).describe("Installation status"),
  displayName: v4.z.string().optional().describe("Platform-specific display name"),
  installedAt: v4.z.coerce.date().optional().describe("Installation timestamp")
});
var channelConnectOAuthSchema = v4.z.object({
  type: v4.z.literal("oauth").describe("OAuth-based connection requiring browser redirect"),
  authorizationUrl: v4.z.string().describe("OAuth authorization URL for user redirect"),
  installationId: v4.z.string().describe("Installation identifier")
});
var channelConnectDeepLinkSchema = v4.z.object({
  type: v4.z.literal("deep_link").describe("Deep-link connection requiring native app interaction"),
  url: v4.z.string().describe("Deep link URL to open in platform app"),
  installationId: v4.z.string().describe("Installation identifier")
});
var channelConnectImmediateSchema = v4.z.object({
  type: v4.z.literal("immediate").describe("Immediate connection with no user interaction needed"),
  installationId: v4.z.string().describe("Installation identifier")
});
var channelConnectResultSchema = v4.z.discriminatedUnion("type", [
  channelConnectOAuthSchema,
  channelConnectDeepLinkSchema,
  channelConnectImmediateSchema
]);
var listChannelPlatformsResponseSchema = v4.z.array(channelPlatformInfoSchema);
var listChannelInstallationsResponseSchema = v4.z.array(channelInstallationInfoSchema);
var connectChannelResponseSchema = channelConnectResultSchema;
var disconnectChannelResponseSchema = v4.z.object({
  success: v4.z.boolean()
});

// src/server/handlers/channels.ts
function assertChannelsAvailable() {
  if (!features.coreFeatures.has("channels")) {
    throw new chunk64ITUOXI_cjs.HTTPException(501, { message: "Channels require a newer version of @mastra/core" });
  }
}
function getChannelOrThrow(mastra, platform) {
  const channels = Object.values(mastra.channels ?? {});
  const channel = channels.find((c) => c.id === platform);
  if (!channel) {
    const available = channels.map((c) => c.id).join(", ");
    throw new chunk64ITUOXI_cjs.HTTPException(404, {
      message: `Channel "${platform}" is not registered. Available: ${available || "none"}`
    });
  }
  return channel;
}
async function assertChannelAgentWriteAccess(mastra, requestContext, agentId, action) {
  const storage = mastra.getStorage();
  const agentsStore = storage ? await storage.getStore("agents") : null;
  const stored = agentsStore ? await agentsStore.getById(agentId) : null;
  if (stored) {
    chunkHDIYJI2Z_cjs.assertWriteAccess({
      requestContext,
      resource: "agents",
      resourceId: agentId,
      action: "edit",
      record: stored
    });
    return;
  }
  const codeDefined = mastra.getAgentById(agentId);
  if (codeDefined) {
    return;
  }
  if (action === "connect") {
    throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent "${agentId}" not found` });
  }
  const callerAuthorId = chunkHDIYJI2Z_cjs.getCallerAuthorId(requestContext);
  if (!callerAuthorId && !requestContext.get(chunkSXKQ7CSX_cjs.MASTRA_USER_KEY)) return;
  if (chunkHDIYJI2Z_cjs.hasAdminBypass(requestContext, "channels")) return;
  if (chunkHDIYJI2Z_cjs.hasScopedPermission({ requestContext, resource: "channels", action: "write" })) return;
  throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Not found" });
}
var LIST_CHANNEL_PLATFORMS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/channels/platforms",
  responseType: "json",
  responseSchema: listChannelPlatformsResponseSchema,
  summary: "List channel platforms",
  description: "Returns available channel platforms and their configuration status",
  tags: ["Channels"],
  requiresAuth: true,
  handler: async ({ mastra }) => {
    assertChannelsAvailable();
    try {
      const channels = Object.values(mastra.channels ?? {});
      return channels.map((channel) => {
        if (channel.getInfo) {
          return channel.getInfo();
        }
        return {
          id: channel.id,
          name: channel.id.charAt(0).toUpperCase() + channel.id.slice(1),
          isConfigured: true
        };
      });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing channel platforms");
    }
  }
});
var LIST_CHANNEL_INSTALLATIONS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/channels/:platform/installations",
  responseType: "json",
  pathParamSchema: channelPlatformPathParams,
  responseSchema: listChannelInstallationsResponseSchema,
  summary: "List channel installations",
  description: "Returns all active and pending installations for a channel platform",
  tags: ["Channels"],
  requiresAuth: true,
  handler: async ({ mastra, platform }) => {
    assertChannelsAvailable();
    try {
      const channel = getChannelOrThrow(mastra, platform);
      if (!channel.listInstallations) {
        return [];
      }
      return await channel.listInstallations();
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing channel installations");
    }
  }
});
var CONNECT_CHANNEL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/channels/:platform/connect",
  responseType: "json",
  pathParamSchema: channelPlatformPathParams,
  bodySchema: connectChannelBodySchema,
  responseSchema: connectChannelResponseSchema,
  summary: "Connect agent to channel",
  description: "Creates a platform app for the agent and returns an OAuth authorization URL",
  tags: ["Channels"],
  requiresAuth: true,
  handler: async ({ mastra, requestContext, platform, agentId, options }) => {
    assertChannelsAvailable();
    try {
      const channel = getChannelOrThrow(mastra, platform);
      if (!channel.connect) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: `Channel "${platform}" does not support programmatic connection`
        });
      }
      await assertChannelAgentWriteAccess(mastra, requestContext, agentId, "connect");
      return await channel.connect(agentId, options);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error connecting agent to channel");
    }
  }
});
var DISCONNECT_CHANNEL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/channels/:platform/:agentId/disconnect",
  responseType: "json",
  pathParamSchema: channelAgentPathParams,
  responseSchema: disconnectChannelResponseSchema,
  summary: "Disconnect agent from channel",
  description: "Deletes the platform app and cleans up the installation",
  tags: ["Channels"],
  requiresAuth: true,
  handler: async ({ mastra, requestContext, platform, agentId }) => {
    assertChannelsAvailable();
    try {
      const channel = getChannelOrThrow(mastra, platform);
      if (!channel.disconnect) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: `Channel "${platform}" does not support programmatic disconnection`
        });
      }
      await assertChannelAgentWriteAccess(mastra, requestContext, agentId, "disconnect");
      await channel.disconnect(agentId);
      return { success: true };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error disconnecting agent from channel");
    }
  }
});

exports.CONNECT_CHANNEL_ROUTE = CONNECT_CHANNEL_ROUTE;
exports.DISCONNECT_CHANNEL_ROUTE = DISCONNECT_CHANNEL_ROUTE;
exports.LIST_CHANNEL_INSTALLATIONS_ROUTE = LIST_CHANNEL_INSTALLATIONS_ROUTE;
exports.LIST_CHANNEL_PLATFORMS_ROUTE = LIST_CHANNEL_PLATFORMS_ROUTE;
//# sourceMappingURL=chunk-WGEIHQXI.cjs.map
//# sourceMappingURL=chunk-WGEIHQXI.cjs.map