'use strict';

var chunkVBPYR5ZH_cjs = require('./chunk-VBPYR5ZH.cjs');
var chunkEFJCOPJ3_cjs = require('./chunk-EFJCOPJ3.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');

// src/server/utils/resolve-builder-model-policy.ts
async function resolveBuilderModelPolicy(editor) {
  if (!editor) return { active: false };
  if (typeof editor.resolveBuilder !== "function") return { active: false };
  if (typeof editor.hasEnabledBuilderConfig === "function" && !editor.hasEnabledBuilderConfig()) {
    return { active: false };
  }
  try {
    const builder = await editor.resolveBuilder();
    const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');
    return builderToModelPolicy(builder);
  } catch {
    return { active: false };
  }
}

// src/server/handlers/editor-builder.ts
async function resolveBuilderFeatures(mastra) {
  const editor = mastra.getEditor();
  if (!editor || typeof editor.resolveBuilder !== "function") return null;
  if (!editor.hasEnabledBuilderConfig?.()) return null;
  const builder = await editor.resolveBuilder();
  if (!builder || !builder.enabled) return null;
  const features = builder.getFeatures?.()?.agent;
  if (!features) return null;
  const parsed = chunkVBPYR5ZH_cjs.agentFeaturesSchema.safeParse(features);
  return parsed.success ? parsed.data : null;
}
async function isBuilderFeatureEnabled(mastra, feature) {
  const features = await resolveBuilderFeatures(mastra);
  return features?.[feature] === true;
}
async function requireBuilderFeature(mastra, feature) {
  if (!await isBuilderFeatureEnabled(mastra, feature)) {
    throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Not Found" });
  }
}
var GET_EDITOR_BUILDER_SETTINGS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/editor/builder/settings",
  responseType: "json",
  responseSchema: chunkVBPYR5ZH_cjs.builderSettingsResponseSchema,
  summary: "Get agent builder settings",
  description: "Returns the agent builder feature flags and configuration for UI gating",
  tags: ["Editor"],
  requiresAuth: true,
  requiresPermission: "stored-agents:read",
  handler: async ({ mastra }) => {
    try {
      const editor = mastra.getEditor();
      if (!editor) {
        return { enabled: false, modelPolicy: { active: false } };
      }
      if (typeof editor.resolveBuilder !== "function") {
        return { enabled: false, modelPolicy: { active: false } };
      }
      if (!editor.hasEnabledBuilderConfig?.()) {
        return { enabled: false, modelPolicy: { active: false } };
      }
      const builder = await editor.resolveBuilder();
      if (!builder || !builder.enabled) {
        return { enabled: false, modelPolicy: { active: false } };
      }
      const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];
      const configuration = builder.getConfiguration();
      const collectAliases = (registry) => Object.entries(registry).map(([key, entity]) => ({
        id: entity.id || key,
        key
      }));
      const toolAliases = collectAliases(mastra.listTools() ?? {});
      const agentAliases = collectAliases(mastra.listAgents() ?? {});
      const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});
      const toResponseKey = (aliases, byId) => {
        const map = /* @__PURE__ */ new Map();
        for (const a of aliases) {
          map.set(a.id, byId === "id" ? a.id : a.key);
          map.set(a.key, byId === "id" ? a.id : a.key);
        }
        return map;
      };
      const toolKeyMap = toResponseKey(toolAliases, "key");
      const agentKeyMap = toResponseKey(agentAliases, "id");
      const workflowKeyMap = toResponseKey(workflowAliases, "key");
      const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');
      const picker = resolvePickerVisibility({
        config: configuration?.agent,
        registeredToolIds: toolAliases.flatMap((a) => [a.id, a.key]),
        registeredAgentIds: agentAliases.flatMap((a) => [a.id, a.key]),
        registeredWorkflowIds: workflowAliases.flatMap((a) => [a.id, a.key])
      });
      const normalize = (visible, map) => {
        if (visible === null) return null;
        const out = [];
        const seen = /* @__PURE__ */ new Set();
        for (const id of visible) {
          const mapped = map.get(id);
          if (mapped && !seen.has(mapped)) {
            seen.add(mapped);
            out.push(mapped);
          }
        }
        return out;
      };
      const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];
      return {
        enabled: true,
        features: builder.getFeatures(),
        configuration,
        modelPolicy: builderToModelPolicy(builder),
        picker: {
          visibleTools: normalize(picker.visibleTools, toolKeyMap),
          visibleAgents: normalize(picker.visibleAgents, agentKeyMap),
          visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap)
        },
        ...modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting builder settings");
    }
  }
});
var GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/editor/builder/models/available",
  responseType: "json",
  responseSchema: chunkVBPYR5ZH_cjs.builderAvailableModelsResponseSchema,
  summary: "List builder-available AI models",
  description: "Returns AI providers/models filtered by the active agent-builder model policy.",
  tags: ["Editor"],
  requiresAuth: true,
  requiresPermission: "stored-agents:read",
  handler: async ({ mastra }) => {
    try {
      const providers = (await chunkEFJCOPJ3_cjs.buildProvidersList(mastra)).filter((provider) => provider.connected);
      const policy = await resolveBuilderModelPolicy(mastra.getEditor());
      if (!policy.active || !policy.allowed || policy.allowed.length === 0) {
        return { providers };
      }
      const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');
      const filtered = providers.map((provider) => ({
        ...provider,
        models: provider.models.filter((modelId) => isModelAllowed(policy.allowed, { provider: provider.id, modelId }))
      })).filter((provider) => provider.models.length > 0);
      return { providers: filtered };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error fetching available models");
    }
  }
});
var GET_INFRASTRUCTURE_STATUS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/editor/builder/infrastructure",
  responseType: "json",
  responseSchema: chunkVBPYR5ZH_cjs.infrastructureStatusResponseSchema,
  summary: "Get infrastructure status",
  description: "Agent Builder infrastructure configuration and lightweight runtime status.",
  tags: ["Editor"],
  requiresAuth: true,
  requiresPermission: "infrastructure:read",
  handler: async ({ mastra }) => {
    try {
      const formatConfigValue = (value) => {
        if (value === null || value === void 0) return "not set";
        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
        if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? "" : "s"}`;
        return value.constructor?.name && value.constructor.name !== "Object" ? value.constructor.name : "configured";
      };
      const getProviderName = (value) => {
        if (!value) return null;
        if (typeof value === "object" && "provider" in value && typeof value.provider === "string")
          return value.provider;
        if (typeof value === "object" && "constructor" in value) {
          const name = value.constructor?.name;
          return name && name !== "Object" ? name : "configured";
        }
        return null;
      };
      const getConfigEntries = (config, omittedKeys = []) => Object.entries(config).filter(([key, value]) => !omittedKeys.includes(key) && value !== void 0 && value !== null).map(([key, value]) => ({ key, value: formatConfigValue(value) }));
      const channelProviders = mastra.getChannelProviders() ?? {};
      const channels = {
        providers: Object.entries(channelProviders).map(([id, provider]) => {
          const info = provider.getInfo?.();
          const routes = provider.getRoutes?.() ?? [];
          return {
            id: info?.id ?? id,
            name: info?.name ?? id,
            isConfigured: info?.isConfigured ?? false,
            routeCount: routes.length
          };
        }).filter((provider) => provider.isConfigured)
      };
      const editor = mastra.getEditor();
      let browser = {
        type: null,
        provider: null,
        env: null,
        registered: false,
        availableProviders: [],
        config: []
      };
      let workspace = {
        type: null,
        workspaceId: null,
        name: null,
        source: null,
        registered: false,
        hasFilesystem: false,
        hasSandbox: false,
        filesystemProvider: null,
        sandboxProvider: null,
        config: []
      };
      let registries = {
        skillsSh: { enabled: false }
      };
      if (editor?.resolveBuilder) {
        const browsers = editor.__browsers;
        const builder = await editor.resolveBuilder();
        const builderRegistries = builder?.getRegistries?.();
        registries = {
          skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true }
        };
        const configuration = builder?.getConfiguration?.()?.agent;
        const browserRef = configuration?.browser;
        const browserConfig = browserRef?.config ?? {};
        const providerId = browserConfig.provider ?? null;
        browser = {
          type: browserRef?.type ?? null,
          provider: providerId,
          env: browserConfig.env ?? null,
          registered: providerId ? !!browsers?.has(providerId) : false,
          availableProviders: browsers ? Array.from(browsers.keys()) : [],
          config: getConfigEntries(browserConfig, ["provider", "env"])
        };
        const workspaceRef = configuration?.workspace;
        const workspaceConfig = workspaceRef?.config ?? {};
        const registeredWorkspaces = mastra.listWorkspaces();
        const registeredWorkspace = workspaceRef?.workspaceId ? registeredWorkspaces[workspaceRef.workspaceId] : void 0;
        const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;
        const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;
        const filesystemConfig = typeof workspaceConfig.filesystem === "object" && workspaceConfig.filesystem && "config" in workspaceConfig.filesystem ? workspaceConfig.filesystem.config : {};
        const sandboxConfig = typeof workspaceConfig.sandbox === "object" && workspaceConfig.sandbox && "config" in workspaceConfig.sandbox ? workspaceConfig.sandbox.config : {};
        workspace = {
          type: workspaceRef?.type ?? null,
          workspaceId: workspaceRef?.workspaceId ?? null,
          name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,
          source: registeredWorkspace?.source ?? null,
          registered: !!registeredWorkspace,
          hasFilesystem: !!filesystem,
          hasSandbox: !!sandbox,
          filesystemProvider: getProviderName(filesystem),
          sandboxProvider: getProviderName(sandbox),
          config: [
            ...getConfigEntries(filesystemConfig).map((entry) => ({ ...entry, key: `filesystem.${entry.key}` })),
            ...getConfigEntries(sandboxConfig).map((entry) => ({ ...entry, key: `sandbox.${entry.key}` }))
          ]
        };
      }
      return { channels, browser, workspace, registries };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting infrastructure status");
    }
  }
});

exports.GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE;
exports.GET_EDITOR_BUILDER_SETTINGS_ROUTE = GET_EDITOR_BUILDER_SETTINGS_ROUTE;
exports.GET_INFRASTRUCTURE_STATUS_ROUTE = GET_INFRASTRUCTURE_STATUS_ROUTE;
exports.isBuilderFeatureEnabled = isBuilderFeatureEnabled;
exports.requireBuilderFeature = requireBuilderFeature;
//# sourceMappingURL=chunk-KSN5CWZ7.cjs.map
//# sourceMappingURL=chunk-KSN5CWZ7.cjs.map