import { assertWriteAccess, getCallerAuthorId, hasAdminBypass, hasScopedPermission } from './chunk-SXZS6VZ3.js';
import { MASTRA_USER_KEY } from './chunk-5FOSK5R3.js';
import { handleError } from './chunk-7ZWJX3AN.js';
import { createRoute } from './chunk-PIKPS6Q6.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { coreFeatures } from '@mastra/core/features';
import { z } from 'zod/v4';

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

// src/server/handlers/channels.ts
function assertChannelsAvailable() {
  if (!coreFeatures.has("channels")) {
    throw new 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 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) {
    assertWriteAccess({
      requestContext,
      resource: "agents",
      resourceId: agentId,
      action: "edit",
      record: stored
    });
    return;
  }
  const codeDefined = mastra.getAgentById(agentId);
  if (codeDefined) {
    return;
  }
  if (action === "connect") {
    throw new HTTPException(404, { message: `Agent "${agentId}" not found` });
  }
  const callerAuthorId = getCallerAuthorId(requestContext);
  if (!callerAuthorId && !requestContext.get(MASTRA_USER_KEY)) return;
  if (hasAdminBypass(requestContext, "channels")) return;
  if (hasScopedPermission({ requestContext, resource: "channels", action: "write" })) return;
  throw new HTTPException(404, { message: "Not found" });
}
var LIST_CHANNEL_PLATFORMS_ROUTE = 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 handleError(error, "Error listing channel platforms");
    }
  }
});
var LIST_CHANNEL_INSTALLATIONS_ROUTE = 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 handleError(error, "Error listing channel installations");
    }
  }
});
var CONNECT_CHANNEL_ROUTE = 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 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 handleError(error, "Error connecting agent to channel");
    }
  }
});
var DISCONNECT_CHANNEL_ROUTE = 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 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 handleError(error, "Error disconnecting agent from channel");
    }
  }
});

export { CONNECT_CHANNEL_ROUTE, DISCONNECT_CHANNEL_ROUTE, LIST_CHANNEL_INSTALLATIONS_ROUTE, LIST_CHANNEL_PLATFORMS_ROUTE };
//# sourceMappingURL=chunk-Z5DHV2QW.js.map
//# sourceMappingURL=chunk-Z5DHV2QW.js.map