'use strict';

var chunkT5KH32UA_cjs = require('../../chunk-T5KH32UA.cjs');
var chunkWK2FRQEW_cjs = require('../../chunk-WK2FRQEW.cjs');
var chunkKPDZYFEE_cjs = require('../../chunk-KPDZYFEE.cjs');
var chunkOGSBJMPX_cjs = require('../../chunk-OGSBJMPX.cjs');
var chunkT4ZBRGJU_cjs = require('../../chunk-T4ZBRGJU.cjs');
var chunk2HOMKKY4_cjs = require('../../chunk-2HOMKKY4.cjs');
var chunkSEE2MAOJ_cjs = require('../../chunk-SEE2MAOJ.cjs');
var chunkHDGF45K7_cjs = require('../../chunk-HDGF45K7.cjs');
var chunkJRM3DWRM_cjs = require('../../chunk-JRM3DWRM.cjs');
var chunkXI35WFHZ_cjs = require('../../chunk-XI35WFHZ.cjs');
var chunkAV3VZ6S3_cjs = require('../../chunk-AV3VZ6S3.cjs');
var chunkE2JHVKGO_cjs = require('../../chunk-E2JHVKGO.cjs');
var chunkAAHPYUEC_cjs = require('../../chunk-AAHPYUEC.cjs');
var chunkCAPYNS3W_cjs = require('../../chunk-CAPYNS3W.cjs');
var chunk2ABZICAN_cjs = require('../../chunk-2ABZICAN.cjs');
var chunkRGMLSZHU_cjs = require('../../chunk-RGMLSZHU.cjs');
var chunkLHQBSFTY_cjs = require('../../chunk-LHQBSFTY.cjs');
var chunkZWYF2ADF_cjs = require('../../chunk-ZWYF2ADF.cjs');
var chunkGQJJSFM3_cjs = require('../../chunk-GQJJSFM3.cjs');
var chunk4LVJBXI2_cjs = require('../../chunk-4LVJBXI2.cjs');
var requestContext = require('@mastra/core/request-context');
var server = require('@mastra/core/server');

// src/server/server-adapter/routes/a2a.ts
var A2A_ROUTES = [chunkCAPYNS3W_cjs.GET_AGENT_CARD_ROUTE, chunkCAPYNS3W_cjs.AGENT_EXECUTION_ROUTE];

// src/server/server-adapter/routes/agent-builder.ts
var AGENT_BUILDER_ROUTES = [
  chunk2ABZICAN_cjs.LIST_AGENT_BUILDER_ACTIONS_ROUTE,
  chunk2ABZICAN_cjs.GET_AGENT_BUILDER_ACTION_BY_ID_ROUTE,
  chunk2ABZICAN_cjs.LIST_AGENT_BUILDER_ACTION_RUNS_ROUTE,
  chunk2ABZICAN_cjs.GET_AGENT_BUILDER_ACTION_RUN_BY_ID_ROUTE,
  chunk2ABZICAN_cjs.CREATE_AGENT_BUILDER_ACTION_RUN_ROUTE,
  chunk2ABZICAN_cjs.STREAM_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.START_ASYNC_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.START_AGENT_BUILDER_ACTION_RUN_ROUTE,
  chunk2ABZICAN_cjs.OBSERVE_STREAM_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.RESUME_ASYNC_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.RESUME_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.RESUME_STREAM_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.CANCEL_AGENT_BUILDER_ACTION_RUN_ROUTE
];

// src/server/server-adapter/routes/agents.ts
var AGENTS_ROUTES = [
  // ============================================================================
  // Agent Core Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.LIST_AGENTS_ROUTE,
  chunkGQJJSFM3_cjs.GET_PROVIDERS_ROUTE,
  chunkGQJJSFM3_cjs.GET_AGENT_BY_ID_ROUTE,
  // ============================================================================
  // Voice Routes
  // ============================================================================
  chunkSEE2MAOJ_cjs.GET_SPEAKERS_ROUTE,
  chunkSEE2MAOJ_cjs.GET_SPEAKERS_DEPRECATED_ROUTE,
  // ============================================================================
  // Agent Execution Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.GENERATE_AGENT_ROUTE,
  chunkGQJJSFM3_cjs.GENERATE_AGENT_VNEXT_ROUTE,
  chunkGQJJSFM3_cjs.STREAM_GENERATE_ROUTE,
  chunkGQJJSFM3_cjs.STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE,
  // ============================================================================
  // Tool Routes
  // ============================================================================
  chunkT4ZBRGJU_cjs.EXECUTE_AGENT_TOOL_ROUTE,
  chunkGQJJSFM3_cjs.APPROVE_TOOL_CALL_ROUTE,
  chunkGQJJSFM3_cjs.DECLINE_TOOL_CALL_ROUTE,
  chunkGQJJSFM3_cjs.APPROVE_TOOL_CALL_GENERATE_ROUTE,
  chunkGQJJSFM3_cjs.DECLINE_TOOL_CALL_GENERATE_ROUTE,
  chunkGQJJSFM3_cjs.APPROVE_NETWORK_TOOL_CALL_ROUTE,
  chunkGQJJSFM3_cjs.DECLINE_NETWORK_TOOL_CALL_ROUTE,
  // ============================================================================
  // Network Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.STREAM_NETWORK_ROUTE,
  // ============================================================================
  // Model Management Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.UPDATE_AGENT_MODEL_ROUTE,
  chunkGQJJSFM3_cjs.RESET_AGENT_MODEL_ROUTE,
  chunkGQJJSFM3_cjs.REORDER_AGENT_MODEL_LIST_ROUTE,
  chunkGQJJSFM3_cjs.UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE,
  // ============================================================================
  // Instruction Enhancement Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.ENHANCE_INSTRUCTIONS_ROUTE,
  // ============================================================================
  // Agent Tool Routes
  // ============================================================================
  chunkT4ZBRGJU_cjs.GET_AGENT_TOOL_ROUTE,
  // ============================================================================
  // Agent Skill Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.GET_AGENT_SKILL_ROUTE,
  // ============================================================================
  // Voice/Speech Routes
  // ============================================================================
  chunkSEE2MAOJ_cjs.GENERATE_SPEECH_ROUTE,
  chunkSEE2MAOJ_cjs.GENERATE_SPEECH_DEPRECATED_ROUTE,
  chunkSEE2MAOJ_cjs.TRANSCRIBE_SPEECH_ROUTE,
  chunkSEE2MAOJ_cjs.TRANSCRIBE_SPEECH_DEPRECATED_ROUTE,
  chunkSEE2MAOJ_cjs.GET_LISTENER_ROUTE,
  // ============================================================================
  // Deprecated Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.STREAM_VNEXT_DEPRECATED_ROUTE,
  chunkGQJJSFM3_cjs.STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE,
  chunkGQJJSFM3_cjs.STREAM_UI_MESSAGE_DEPRECATED_ROUTE
];

// src/server/server-adapter/routes/legacy.ts
var LEGACY_ROUTES = [
  // ============================================================================
  // Legacy Agent Routes
  // ============================================================================
  chunkGQJJSFM3_cjs.GENERATE_LEGACY_ROUTE,
  chunkGQJJSFM3_cjs.STREAM_GENERATE_LEGACY_ROUTE,
  // ============================================================================
  // Legacy Workflow Routes
  // ============================================================================
  chunkRGMLSZHU_cjs.STREAM_LEGACY_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE,
  // ============================================================================
  // Legacy Agent Builder Routes
  // ============================================================================
  chunk2ABZICAN_cjs.STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE,
  chunk2ABZICAN_cjs.OBSERVE_STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE
];

// src/server/server-adapter/routes/logs.ts
var LOGS_ROUTES = [
  chunkHDGF45K7_cjs.LIST_LOG_TRANSPORTS_ROUTE,
  chunkHDGF45K7_cjs.LIST_LOGS_ROUTE,
  chunkHDGF45K7_cjs.LIST_LOGS_BY_RUN_ID_ROUTE
];

// src/server/server-adapter/routes/mcp.ts
var MCP_ROUTES = [
  // ============================================================================
  // MCP Server Registry Routes
  // ============================================================================
  chunkJRM3DWRM_cjs.LIST_MCP_SERVERS_ROUTE,
  chunkJRM3DWRM_cjs.GET_MCP_SERVER_DETAIL_ROUTE,
  // ============================================================================
  // MCP Server Tool Routes
  // ============================================================================
  chunkJRM3DWRM_cjs.LIST_MCP_SERVER_TOOLS_ROUTE,
  chunkJRM3DWRM_cjs.GET_MCP_SERVER_TOOL_DETAIL_ROUTE,
  chunkJRM3DWRM_cjs.EXECUTE_MCP_SERVER_TOOL_ROUTE,
  // ============================================================================
  // MCP Transport Routes (handled by adapters)
  // ============================================================================
  chunkJRM3DWRM_cjs.MCP_HTTP_TRANSPORT_ROUTE,
  chunkJRM3DWRM_cjs.MCP_SSE_TRANSPORT_ROUTE,
  chunkJRM3DWRM_cjs.MCP_SSE_MESSAGES_ROUTE
];

// src/server/server-adapter/routes/memory.ts
var MEMORY_ROUTES = [
  chunkXI35WFHZ_cjs.GET_MEMORY_STATUS_ROUTE,
  chunkXI35WFHZ_cjs.GET_MEMORY_CONFIG_ROUTE,
  chunkXI35WFHZ_cjs.GET_OBSERVATIONAL_MEMORY_ROUTE,
  chunkXI35WFHZ_cjs.LIST_THREADS_ROUTE,
  chunkXI35WFHZ_cjs.GET_THREAD_BY_ID_ROUTE,
  chunkXI35WFHZ_cjs.LIST_MESSAGES_ROUTE,
  chunkXI35WFHZ_cjs.GET_WORKING_MEMORY_ROUTE,
  chunkXI35WFHZ_cjs.SAVE_MESSAGES_ROUTE,
  chunkXI35WFHZ_cjs.CREATE_THREAD_ROUTE,
  chunkXI35WFHZ_cjs.UPDATE_THREAD_ROUTE,
  chunkXI35WFHZ_cjs.DELETE_THREAD_ROUTE,
  chunkXI35WFHZ_cjs.CLONE_THREAD_ROUTE,
  chunkXI35WFHZ_cjs.UPDATE_WORKING_MEMORY_ROUTE,
  chunkXI35WFHZ_cjs.DELETE_MESSAGES_ROUTE,
  chunkXI35WFHZ_cjs.SEARCH_MEMORY_ROUTE,
  chunkXI35WFHZ_cjs.GET_MEMORY_STATUS_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.LIST_THREADS_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.GET_THREAD_BY_ID_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.LIST_MESSAGES_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.SAVE_MESSAGES_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.CREATE_THREAD_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.UPDATE_THREAD_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.DELETE_THREAD_NETWORK_ROUTE,
  chunkXI35WFHZ_cjs.DELETE_MESSAGES_NETWORK_ROUTE
];

// src/server/server-adapter/routes/observability.ts
var OBSERVABILITY_ROUTES = [
  chunkAV3VZ6S3_cjs.LIST_TRACES_ROUTE,
  chunkAV3VZ6S3_cjs.GET_TRACE_ROUTE,
  chunkAV3VZ6S3_cjs.SCORE_TRACES_ROUTE,
  chunkAV3VZ6S3_cjs.LIST_SCORES_BY_SPAN_ROUTE
];

// src/server/server-adapter/routes/processors.ts
var PROCESSORS_ROUTES = [
  chunkKPDZYFEE_cjs.LIST_PROCESSORS_ROUTE,
  chunkKPDZYFEE_cjs.GET_PROCESSOR_BY_ID_ROUTE,
  chunkKPDZYFEE_cjs.EXECUTE_PROCESSOR_ROUTE
];

// src/server/server-adapter/routes/scorers.ts
var SCORES_ROUTES = [
  chunkE2JHVKGO_cjs.LIST_SCORERS_ROUTE,
  chunkE2JHVKGO_cjs.GET_SCORER_ROUTE,
  chunkE2JHVKGO_cjs.LIST_SCORES_BY_RUN_ID_ROUTE,
  chunkE2JHVKGO_cjs.LIST_SCORES_BY_SCORER_ID_ROUTE,
  chunkE2JHVKGO_cjs.LIST_SCORES_BY_ENTITY_ID_ROUTE,
  chunkE2JHVKGO_cjs.SAVE_SCORE_ROUTE
];

// src/server/server-adapter/routes/stored-agents.ts
var STORED_AGENTS_ROUTES = [
  // ============================================================================
  // Stored Agents CRUD Routes
  // ============================================================================
  chunkOGSBJMPX_cjs.LIST_STORED_AGENTS_ROUTE,
  chunkOGSBJMPX_cjs.GET_STORED_AGENT_ROUTE,
  chunkOGSBJMPX_cjs.CREATE_STORED_AGENT_ROUTE,
  chunkOGSBJMPX_cjs.UPDATE_STORED_AGENT_ROUTE,
  chunkOGSBJMPX_cjs.DELETE_STORED_AGENT_ROUTE,
  // ============================================================================
  // Agent Versions Routes
  // IMPORTANT: Routes with literal paths (e.g., /compare) must come BEFORE
  // routes with path parameters (e.g., /:versionId) to ensure correct matching.
  // ============================================================================
  chunkZWYF2ADF_cjs.LIST_AGENT_VERSIONS_ROUTE,
  chunkZWYF2ADF_cjs.CREATE_AGENT_VERSION_ROUTE,
  chunkZWYF2ADF_cjs.COMPARE_AGENT_VERSIONS_ROUTE,
  // Must be before GET_AGENT_VERSION_ROUTE
  chunkZWYF2ADF_cjs.GET_AGENT_VERSION_ROUTE,
  chunkZWYF2ADF_cjs.ACTIVATE_AGENT_VERSION_ROUTE,
  chunkZWYF2ADF_cjs.RESTORE_AGENT_VERSION_ROUTE,
  chunkZWYF2ADF_cjs.DELETE_AGENT_VERSION_ROUTE
];

// src/server/server-adapter/routes/system.ts
var SYSTEM_ROUTES = [chunkT5KH32UA_cjs.GET_SYSTEM_PACKAGES_ROUTE];

// src/server/server-adapter/routes/tools.ts
var TOOLS_ROUTES = [chunkT4ZBRGJU_cjs.LIST_TOOLS_ROUTE, chunkT4ZBRGJU_cjs.GET_TOOL_BY_ID_ROUTE, chunkT4ZBRGJU_cjs.EXECUTE_TOOL_ROUTE];

// src/server/server-adapter/routes/vectors.ts
var VECTORS_ROUTES = [
  chunk2HOMKKY4_cjs.UPSERT_VECTORS_ROUTE,
  chunk2HOMKKY4_cjs.CREATE_INDEX_ROUTE,
  chunk2HOMKKY4_cjs.QUERY_VECTORS_ROUTE,
  chunk2HOMKKY4_cjs.LIST_INDEXES_ROUTE,
  chunk2HOMKKY4_cjs.DESCRIBE_INDEX_ROUTE,
  chunk2HOMKKY4_cjs.DELETE_INDEX_ROUTE
];

// src/server/server-adapter/routes/workflows.ts
var WORKFLOWS_ROUTES = [
  chunkRGMLSZHU_cjs.LIST_WORKFLOWS_ROUTE,
  chunkRGMLSZHU_cjs.GET_WORKFLOW_BY_ID_ROUTE,
  chunkRGMLSZHU_cjs.LIST_WORKFLOW_RUNS_ROUTE,
  chunkRGMLSZHU_cjs.GET_WORKFLOW_RUN_BY_ID_ROUTE,
  chunkRGMLSZHU_cjs.DELETE_WORKFLOW_RUN_BY_ID_ROUTE,
  chunkRGMLSZHU_cjs.CREATE_WORKFLOW_RUN_ROUTE,
  chunkRGMLSZHU_cjs.STREAM_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.RESUME_STREAM_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.START_ASYNC_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.START_WORKFLOW_RUN_ROUTE,
  chunkRGMLSZHU_cjs.OBSERVE_STREAM_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.RESUME_ASYNC_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.RESUME_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.CANCEL_WORKFLOW_RUN_ROUTE,
  chunkRGMLSZHU_cjs.TIME_TRAVEL_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.TIME_TRAVEL_STREAM_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.RESTART_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.RESTART_ASYNC_WORKFLOW_ROUTE,
  chunkRGMLSZHU_cjs.RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE,
  chunkRGMLSZHU_cjs.RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE
];

// src/server/server-adapter/routes/workspace.ts
var WORKSPACE_ROUTES = [
  // List all workspaces route (at /api/workspaces)
  chunkWK2FRQEW_cjs.LIST_WORKSPACES_ROUTE,
  // Get workspace route (at /api/workspaces/:workspaceId)
  chunkWK2FRQEW_cjs.GET_WORKSPACE_ROUTE,
  // Filesystem routes (at /api/workspaces/:workspaceId/fs/*)
  ...chunkWK2FRQEW_cjs.WORKSPACE_FS_ROUTES,
  // Search routes (at /api/workspaces/:workspaceId/search, /api/workspaces/:workspaceId/index)
  ...chunkWK2FRQEW_cjs.WORKSPACE_SEARCH_ROUTES,
  // Skills routes (search must come before parameterized routes)
  ...chunkWK2FRQEW_cjs.WORKSPACE_SKILLS_ROUTES,
  // skills.sh proxy routes (at /api/workspaces/:workspaceId/skills-sh/*)
  ...chunkWK2FRQEW_cjs.WORKSPACE_SKILLS_SH_ROUTES
];

// src/server/server-adapter/routes/index.ts
var SERVER_ROUTES = [
  ...AGENTS_ROUTES,
  ...WORKFLOWS_ROUTES,
  ...TOOLS_ROUTES,
  ...PROCESSORS_ROUTES,
  ...MEMORY_ROUTES,
  ...SCORES_ROUTES,
  ...OBSERVABILITY_ROUTES,
  ...LOGS_ROUTES,
  ...VECTORS_ROUTES,
  ...A2A_ROUTES,
  ...AGENT_BUILDER_ROUTES,
  ...WORKSPACE_ROUTES,
  ...LEGACY_ROUTES,
  ...MCP_ROUTES,
  ...STORED_AGENTS_ROUTES,
  ...SYSTEM_ROUTES
];

// src/server/server-adapter/redact.ts
function redactV2Payload(payload) {
  const redactedPayload = { ...payload };
  if (redactedPayload.metadata && typeof redactedPayload.metadata === "object") {
    const { request, ...metadataRest } = redactedPayload.metadata;
    redactedPayload.metadata = metadataRest;
  }
  if (redactedPayload.output && typeof redactedPayload.output === "object") {
    const output = { ...redactedPayload.output };
    if (Array.isArray(output.steps)) {
      output.steps = output.steps.map((step) => {
        if (step && typeof step === "object") {
          const { request, ...stepRest } = step;
          return stepRest;
        }
        return step;
      });
    }
    redactedPayload.output = output;
  }
  return redactedPayload;
}
function redactStreamChunk(chunk) {
  if (!chunk || typeof chunk !== "object") {
    return chunk;
  }
  const typedChunk = chunk;
  switch (chunk.type) {
    case "step-start": {
      if ("payload" in typedChunk && typedChunk.payload && typeof typedChunk.payload === "object") {
        const { payload, ...rest } = typedChunk;
        const { request, ...payloadRest } = payload;
        return {
          ...rest,
          type: "step-start",
          payload: {
            ...payloadRest,
            // Keep an empty request object to maintain structure but remove body
            request: {}
          }
        };
      } else if ("request" in typedChunk) {
        const { request, ...rest } = typedChunk;
        return {
          ...rest,
          type: "step-start",
          // Keep an empty request object to maintain structure
          request: {}
        };
      }
      return chunk;
    }
    case "step-finish": {
      if ("payload" in typedChunk && typedChunk.payload && typeof typedChunk.payload === "object") {
        const { payload, ...rest } = typedChunk;
        return {
          ...rest,
          type: "step-finish",
          payload: redactV2Payload(payload)
        };
      } else if ("request" in typedChunk) {
        const { request, ...rest } = typedChunk;
        return {
          ...rest,
          type: "step-finish"
        };
      }
      return chunk;
    }
    case "finish": {
      if ("payload" in typedChunk && typedChunk.payload && typeof typedChunk.payload === "object") {
        const { payload, ...rest } = typedChunk;
        return {
          ...rest,
          type: "finish",
          payload: redactV2Payload(payload)
        };
      } else if ("request" in typedChunk) {
        const { request, ...rest } = typedChunk;
        return {
          ...rest,
          type: "finish"
        };
      }
      return chunk;
    }
    default:
      return chunk;
  }
}

// src/server/server-adapter/index.ts
function normalizeQueryParams(rawQuery) {
  const queryParams = {};
  for (const [key, value] of Object.entries(rawQuery)) {
    if (typeof value === "string") {
      queryParams[key] = value;
    } else if (Array.isArray(value)) {
      const stringValues = value.filter((v) => typeof v === "string");
      queryParams[key] = stringValues.length === 1 ? stringValues[0] : stringValues;
    }
  }
  return queryParams;
}
var MastraServer = class extends server.MastraServerBase {
  mastra;
  bodyLimitOptions;
  tools;
  prefix;
  openapiPath;
  taskStore;
  customRouteAuthConfig;
  streamOptions;
  customApiRoutes;
  mcpOptions;
  constructor({
    app,
    mastra,
    bodyLimitOptions,
    tools,
    prefix = "/api",
    openapiPath = "",
    taskStore,
    customRouteAuthConfig,
    streamOptions,
    customApiRoutes,
    mcpOptions
  }) {
    super({ app, name: "MastraServer" });
    this.mastra = mastra;
    this.bodyLimitOptions = bodyLimitOptions;
    this.tools = tools;
    this.prefix = chunkLHQBSFTY_cjs.normalizeRoutePath(prefix);
    this.openapiPath = openapiPath;
    this.taskStore = taskStore;
    this.customRouteAuthConfig = customRouteAuthConfig;
    this.streamOptions = { redact: true, ...streamOptions };
    this.customApiRoutes = customApiRoutes;
    this.mcpOptions = mcpOptions;
    mastra.setMastraServer(this);
  }
  mergeRequestContext({
    paramsRequestContext,
    bodyRequestContext
  }) {
    const requestContext$1 = new requestContext.RequestContext();
    if (bodyRequestContext) {
      for (const [key, value] of Object.entries(bodyRequestContext)) {
        requestContext$1.set(key, value);
      }
    }
    if (paramsRequestContext) {
      for (const [key, value] of Object.entries(paramsRequestContext)) {
        requestContext$1.set(key, value);
      }
    }
    return requestContext$1;
  }
  /**
   * Check if the current request should be authenticated/authorized.
   * Returns null if auth passes, or an error response if it fails.
   *
   * This method encapsulates the complete auth flow:
   * 1. Check if route requires auth (route.requiresAuth)
   * 2. Check if it's a dev playground request
   * 3. Check if path is publicly accessible
   * 4. Perform authentication (verify token)
   * 5. Perform authorization (check rules, authorizeUser, authorize)
   */
  async checkRouteAuth(route, context) {
    const authConfig = this.mastra.getServer()?.auth;
    if (!authConfig) {
      return null;
    }
    if (route.requiresAuth === false) {
      return null;
    }
    if (chunkAAHPYUEC_cjs.isDevPlaygroundRequest(context.path, context.method, context.getHeader, authConfig)) {
      return null;
    }
    if (chunkAAHPYUEC_cjs.canAccessPublicly(context.path, context.method, authConfig)) {
      return null;
    }
    const authHeader = context.getHeader("authorization");
    let token = authHeader ? authHeader.replace("Bearer ", "") : null;
    if (!token) {
      token = context.getQuery("apiKey") || null;
    }
    if (!token) {
      return { status: 401, error: "Authentication required" };
    }
    let user;
    try {
      if (typeof authConfig.authenticateToken === "function") {
        user = await authConfig.authenticateToken(token, null);
      } else {
        return { status: 401, error: "No token verification method configured" };
      }
      if (!user) {
        return { status: 401, error: "Invalid or expired token" };
      }
      context.requestContext.set("user", user);
    } catch (err) {
      console.error(err);
      return { status: 401, error: "Invalid or expired token" };
    }
    if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") {
      try {
        const isAuthorized = await authConfig.authorizeUser(user, null);
        if (!isAuthorized) {
          return { status: 403, error: "Access denied" };
        }
        return null;
      } catch (err) {
        console.error(err);
        return { status: 500, error: "Authorization error" };
      }
    }
    if ("authorize" in authConfig && typeof authConfig.authorize === "function") {
      try {
        const isAuthorized = await authConfig.authorize(context.path, context.method, user, null);
        if (!isAuthorized) {
          return { status: 403, error: "Access denied" };
        }
        return null;
      } catch (err) {
        console.error(err);
        return { status: 500, error: "Authorization error" };
      }
    }
    if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) {
      const isAuthorized = await chunkAAHPYUEC_cjs.checkRules(authConfig.rules, context.path, context.method, user);
      if (isAuthorized) {
        return null;
      }
      return { status: 403, error: "Access denied" };
    }
    if (chunkAAHPYUEC_cjs.defaultAuthConfig.rules && chunkAAHPYUEC_cjs.defaultAuthConfig.rules.length > 0) {
      const isAuthorized = await chunkAAHPYUEC_cjs.checkRules(chunkAAHPYUEC_cjs.defaultAuthConfig.rules, context.path, context.method, user);
      if (isAuthorized) {
        return null;
      }
    }
    return { status: 403, error: "Access denied" };
  }
  async init() {
    this.registerContextMiddleware();
    this.registerAuthMiddleware();
    await this.registerRoutes();
  }
  async registerOpenAPIRoute(app, config = {}, { prefix }) {
    const {
      title = "Mastra API",
      version = "1.0.0",
      description = "Mastra Server API",
      path = "/openapi.json"
    } = config;
    const openApiSpec = chunk4LVJBXI2_cjs.generateOpenAPIDocument(SERVER_ROUTES, {
      title,
      version,
      description
    });
    if (this.customApiRoutes && this.customApiRoutes.length > 0) {
      const customPaths = chunk4LVJBXI2_cjs.convertCustomRoutesToOpenAPIPaths(this.customApiRoutes);
      openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };
    }
    const openApiRoute = {
      method: "GET",
      path,
      responseType: "json",
      handler: async () => openApiSpec
    };
    await this.registerRoute(app, openApiRoute, { prefix });
  }
  async registerRoutes() {
    for (const route of SERVER_ROUTES) {
      await this.registerRoute(this.app, route, { prefix: this.prefix });
    }
    if (this.openapiPath) {
      await this.registerOpenAPIRoute(
        this.app,
        {
          title: "Mastra API",
          version: "1.0.0",
          description: "Mastra Server API",
          path: this.openapiPath
        },
        { prefix: this.prefix }
      );
    }
  }
  async parsePathParams(route, params) {
    const pathParamSchema = route.pathParamSchema;
    if (!pathParamSchema) {
      return params;
    }
    return pathParamSchema.parseAsync(params);
  }
  async parseQueryParams(route, params) {
    const queryParamSchema = route.queryParamSchema;
    if (!queryParamSchema) {
      return params;
    }
    return queryParamSchema.parseAsync(params);
  }
  async parseBody(route, body) {
    const bodySchema = route.bodySchema;
    if (!bodySchema) {
      return body;
    }
    return bodySchema.parseAsync(body);
  }
};

Object.defineProperty(exports, "WorkflowRegistry", {
  enumerable: true,
  get: function () { return chunkLHQBSFTY_cjs.WorkflowRegistry; }
});
Object.defineProperty(exports, "normalizeRoutePath", {
  enumerable: true,
  get: function () { return chunkLHQBSFTY_cjs.normalizeRoutePath; }
});
Object.defineProperty(exports, "createRoute", {
  enumerable: true,
  get: function () { return chunk4LVJBXI2_cjs.createRoute; }
});
Object.defineProperty(exports, "generateOpenAPIDocument", {
  enumerable: true,
  get: function () { return chunk4LVJBXI2_cjs.generateOpenAPIDocument; }
});
Object.defineProperty(exports, "jsonQueryParam", {
  enumerable: true,
  get: function () { return chunk4LVJBXI2_cjs.jsonQueryParam; }
});
Object.defineProperty(exports, "pickParams", {
  enumerable: true,
  get: function () { return chunk4LVJBXI2_cjs.pickParams; }
});
Object.defineProperty(exports, "wrapSchemaForQueryParams", {
  enumerable: true,
  get: function () { return chunk4LVJBXI2_cjs.wrapSchemaForQueryParams; }
});
exports.MastraServer = MastraServer;
exports.SERVER_ROUTES = SERVER_ROUTES;
exports.normalizeQueryParams = normalizeQueryParams;
exports.redactStreamChunk = redactStreamChunk;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map