'use strict';

var chunk7VXUWPHS_cjs = require('../../chunk-7VXUWPHS.cjs');
var chunkMROI3O6S_cjs = require('../../chunk-MROI3O6S.cjs');
var chunkOGEXISZT_cjs = require('../../chunk-OGEXISZT.cjs');
var chunkQ2N5GR7X_cjs = require('../../chunk-Q2N5GR7X.cjs');
var chunkBMWSQ6HM_cjs = require('../../chunk-BMWSQ6HM.cjs');
var chunkLVGLLXRY_cjs = require('../../chunk-LVGLLXRY.cjs');
var chunkS7REEERK_cjs = require('../../chunk-S7REEERK.cjs');
var chunk2QNJHTKM_cjs = require('../../chunk-2QNJHTKM.cjs');
var chunk245BXYGJ_cjs = require('../../chunk-245BXYGJ.cjs');
var chunkEETF75CE_cjs = require('../../chunk-EETF75CE.cjs');
var chunkVGR4DSXQ_cjs = require('../../chunk-VGR4DSXQ.cjs');
var chunkOLPARCPM_cjs = require('../../chunk-OLPARCPM.cjs');
var chunkWFVK6ZXR_cjs = require('../../chunk-WFVK6ZXR.cjs');
var chunkCKZMJIUO_cjs = require('../../chunk-CKZMJIUO.cjs');
var chunk5KM5P23Q_cjs = require('../../chunk-5KM5P23Q.cjs');
var chunkB346SGRP_cjs = require('../../chunk-B346SGRP.cjs');
var chunkUOWUXTUO_cjs = require('../../chunk-UOWUXTUO.cjs');
var chunkTNNU7IZK_cjs = require('../../chunk-TNNU7IZK.cjs');
var chunk33WVA4ZN_cjs = require('../../chunk-33WVA4ZN.cjs');
var chunkNO3V76EI_cjs = require('../../chunk-NO3V76EI.cjs');
var chunkJGHGC64S_cjs = require('../../chunk-JGHGC64S.cjs');
var chunkOGV23F3H_cjs = require('../../chunk-OGV23F3H.cjs');
var chunkJOC7WKJ2_cjs = require('../../chunk-JOC7WKJ2.cjs');
var chunkEBKNX5RM_cjs = require('../../chunk-EBKNX5RM.cjs');
var chunkEFP5PJBY_cjs = require('../../chunk-EFP5PJBY.cjs');
var chunkIA7PNRIA_cjs = require('../../chunk-IA7PNRIA.cjs');
var chunkHWK6K3DW_cjs = require('../../chunk-HWK6K3DW.cjs');
var chunkH4HRQ7ZN_cjs = require('../../chunk-H4HRQ7ZN.cjs');
var chunkPSQNWPPT_cjs = require('../../chunk-PSQNWPPT.cjs');
var chunkVR623NIZ_cjs = require('../../chunk-VR623NIZ.cjs');
var chunk5BXP7S4P_cjs = require('../../chunk-5BXP7S4P.cjs');
var chunkKBD6NZE2_cjs = require('../../chunk-KBD6NZE2.cjs');
var chunkR4DZSQYI_cjs = require('../../chunk-R4DZSQYI.cjs');
var chunkYJQYJ5WD_cjs = require('../../chunk-YJQYJ5WD.cjs');
var chunkI3BHHWHT_cjs = require('../../chunk-I3BHHWHT.cjs');
var chunk2MWLNHBG_cjs = require('../../chunk-2MWLNHBG.cjs');
var chunk5UKYK7YK_cjs = require('../../chunk-5UKYK7YK.cjs');
var chunkB34S64RC_cjs = require('../../chunk-B34S64RC.cjs');
var requestContext = require('@mastra/core/request-context');
var server = require('@mastra/core/server');
var hono = require('hono');
var v4 = require('zod/v4');

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

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

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

// src/server/server-adapter/routes/background-tasks.ts
var BACKGROUND_TASK_ROUTES = [
  chunkCKZMJIUO_cjs.BACKGROUND_TASK_STREAM_ROUTE,
  chunkCKZMJIUO_cjs.LIST_BACKGROUND_TASKS_ROUTE,
  chunkCKZMJIUO_cjs.GET_BACKGROUND_TASK_ROUTE
];

// src/server/server-adapter/routes/conversations.ts
var CONVERSATIONS_ROUTES = [
  chunkIA7PNRIA_cjs.CREATE_CONVERSATION_ROUTE,
  chunkIA7PNRIA_cjs.GET_CONVERSATION_ROUTE,
  chunkIA7PNRIA_cjs.GET_CONVERSATION_ITEMS_ROUTE,
  chunkIA7PNRIA_cjs.DELETE_CONVERSATION_ROUTE
];

// src/server/server-adapter/routes/datasets.ts
var DATASETS_ROUTES = [
  // Dataset CRUD
  chunk5KM5P23Q_cjs.LIST_DATASETS_ROUTE,
  chunk5KM5P23Q_cjs.CREATE_DATASET_ROUTE,
  chunk5KM5P23Q_cjs.GET_DATASET_ROUTE,
  chunk5KM5P23Q_cjs.UPDATE_DATASET_ROUTE,
  chunk5KM5P23Q_cjs.DELETE_DATASET_ROUTE,
  // Item list and add
  chunk5KM5P23Q_cjs.LIST_ITEMS_ROUTE,
  chunk5KM5P23Q_cjs.ADD_ITEM_ROUTE,
  // Batch operations - MUST come before item-specific routes to avoid /items/batch matching /items/:itemId
  chunk5KM5P23Q_cjs.BATCH_INSERT_ITEMS_ROUTE,
  chunk5KM5P23Q_cjs.BATCH_DELETE_ITEMS_ROUTE,
  // Item-specific CRUD (uses :itemId param)
  chunk5KM5P23Q_cjs.GET_ITEM_ROUTE,
  chunk5KM5P23Q_cjs.UPDATE_ITEM_ROUTE,
  chunk5KM5P23Q_cjs.DELETE_ITEM_ROUTE,
  // Version operations
  chunk5KM5P23Q_cjs.LIST_DATASET_VERSIONS_ROUTE,
  chunk5KM5P23Q_cjs.LIST_ITEM_VERSIONS_ROUTE,
  chunk5KM5P23Q_cjs.GET_ITEM_VERSION_ROUTE,
  // All experiments (cross-dataset) - MUST come before dataset-scoped experiments
  chunk5KM5P23Q_cjs.LIST_ALL_EXPERIMENTS_ROUTE,
  // Experiment review summary (cross-dataset) - MUST come before dataset-scoped experiments
  chunk5KM5P23Q_cjs.EXPERIMENT_REVIEW_SUMMARY_ROUTE,
  // Experiment operations (dataset-scoped)
  chunk5KM5P23Q_cjs.LIST_EXPERIMENTS_ROUTE,
  chunk5KM5P23Q_cjs.TRIGGER_EXPERIMENT_ROUTE,
  chunk5KM5P23Q_cjs.GET_EXPERIMENT_ROUTE,
  chunk5KM5P23Q_cjs.LIST_EXPERIMENT_RESULTS_ROUTE,
  chunk5KM5P23Q_cjs.UPDATE_EXPERIMENT_RESULT_ROUTE,
  // Analytics
  chunk5KM5P23Q_cjs.COMPARE_EXPERIMENTS_ROUTE,
  // AI generation
  chunk5KM5P23Q_cjs.GENERATE_ITEMS_ROUTE,
  // Failure analysis
  chunk5KM5P23Q_cjs.CLUSTER_FAILURES_ROUTE
];

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

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

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

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

// src/server/server-adapter/routes/observability.ts
var OBSERVABILITY_ROUTES = [
  // Legacy
  chunkEBKNX5RM_cjs.LIST_TRACES_ROUTE,
  chunkEBKNX5RM_cjs.GET_TRACE_ROUTE,
  chunkEBKNX5RM_cjs.GET_TRACE_LIGHT_ROUTE,
  chunkEBKNX5RM_cjs.GET_SPAN_ROUTE,
  chunkEBKNX5RM_cjs.GET_TRACE_TRAJECTORY_ROUTE,
  chunkEBKNX5RM_cjs.SCORE_TRACES_ROUTE,
  chunkEBKNX5RM_cjs.LIST_SCORES_BY_SPAN_ROUTE,
  // New (17 routes)
  chunkEFP5PJBY_cjs.LIST_LOGS,
  chunkEFP5PJBY_cjs.LIST_SCORES,
  chunkEFP5PJBY_cjs.CREATE_SCORE,
  chunkEFP5PJBY_cjs.GET_SCORE_AGGREGATE,
  chunkEFP5PJBY_cjs.GET_SCORE_BREAKDOWN,
  chunkEFP5PJBY_cjs.GET_SCORE_TIME_SERIES,
  chunkEFP5PJBY_cjs.GET_SCORE_PERCENTILES,
  chunkEFP5PJBY_cjs.LIST_FEEDBACK,
  chunkEFP5PJBY_cjs.CREATE_FEEDBACK,
  chunkEFP5PJBY_cjs.GET_FEEDBACK_AGGREGATE,
  chunkEFP5PJBY_cjs.GET_FEEDBACK_BREAKDOWN,
  chunkEFP5PJBY_cjs.GET_FEEDBACK_TIME_SERIES,
  chunkEFP5PJBY_cjs.GET_FEEDBACK_PERCENTILES,
  chunkEFP5PJBY_cjs.GET_METRIC_AGGREGATE,
  chunkEFP5PJBY_cjs.GET_METRIC_BREAKDOWN,
  chunkEFP5PJBY_cjs.GET_METRIC_TIME_SERIES,
  chunkEFP5PJBY_cjs.GET_METRIC_PERCENTILES,
  chunkEFP5PJBY_cjs.GET_METRIC_NAMES,
  chunkEFP5PJBY_cjs.GET_METRIC_LABEL_KEYS,
  chunkEFP5PJBY_cjs.GET_METRIC_LABEL_VALUES,
  chunkEFP5PJBY_cjs.GET_ENTITY_TYPES,
  chunkEFP5PJBY_cjs.GET_ENTITY_NAMES,
  chunkEFP5PJBY_cjs.GET_SERVICE_NAMES,
  chunkEFP5PJBY_cjs.GET_ENVIRONMENTS,
  chunkEFP5PJBY_cjs.GET_TAGS
];

// src/server/server-adapter/routes/processor-providers.ts
var PROCESSOR_PROVIDER_ROUTES = [chunkOLPARCPM_cjs.LIST_PROCESSOR_PROVIDERS_ROUTE, chunkOLPARCPM_cjs.GET_PROCESSOR_PROVIDER_ROUTE];

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

// src/server/server-adapter/routes/responses.ts
var RESPONSES_ROUTES = [chunkNO3V76EI_cjs.CREATE_RESPONSE_ROUTE, chunkNO3V76EI_cjs.GET_RESPONSE_ROUTE, chunkNO3V76EI_cjs.DELETE_RESPONSE_ROUTE];

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

// src/server/server-adapter/routes/stored-agents.ts
var STORED_AGENTS_ROUTES = [
  // ============================================================================
  // Stored Agents CRUD Routes
  // IMPORTANT: Routes with literal paths (e.g., /preview-instructions) must come
  // BEFORE routes with path parameters (e.g., /:storedAgentId) to ensure correct matching.
  // ============================================================================
  chunk245BXYGJ_cjs.LIST_STORED_AGENTS_ROUTE,
  chunk245BXYGJ_cjs.PREVIEW_INSTRUCTIONS_ROUTE,
  // Must be before GET_STORED_AGENT_ROUTE
  chunk245BXYGJ_cjs.GET_STORED_AGENT_ROUTE,
  chunk245BXYGJ_cjs.CREATE_STORED_AGENT_ROUTE,
  chunk245BXYGJ_cjs.UPDATE_STORED_AGENT_ROUTE,
  chunk245BXYGJ_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.
  // ============================================================================
  chunk2MWLNHBG_cjs.LIST_AGENT_VERSIONS_ROUTE,
  chunk2MWLNHBG_cjs.CREATE_AGENT_VERSION_ROUTE,
  chunk2MWLNHBG_cjs.COMPARE_AGENT_VERSIONS_ROUTE,
  // Must be before GET_AGENT_VERSION_ROUTE
  chunk2MWLNHBG_cjs.GET_AGENT_VERSION_ROUTE,
  chunk2MWLNHBG_cjs.ACTIVATE_AGENT_VERSION_ROUTE,
  chunk2MWLNHBG_cjs.RESTORE_AGENT_VERSION_ROUTE,
  chunk2MWLNHBG_cjs.DELETE_AGENT_VERSION_ROUTE
];

// src/server/server-adapter/routes/stored-mcp-clients.ts
var STORED_MCP_CLIENTS_ROUTES = [
  // Stored MCP Clients CRUD Routes
  chunkEETF75CE_cjs.LIST_STORED_MCP_CLIENTS_ROUTE,
  chunkEETF75CE_cjs.GET_STORED_MCP_CLIENT_ROUTE,
  chunkEETF75CE_cjs.CREATE_STORED_MCP_CLIENT_ROUTE,
  chunkEETF75CE_cjs.UPDATE_STORED_MCP_CLIENT_ROUTE,
  chunkEETF75CE_cjs.DELETE_STORED_MCP_CLIENT_ROUTE,
  // MCP Client Versions Routes
  // IMPORTANT: Routes with literal paths (e.g., /compare) must come BEFORE
  // routes with path parameters (e.g., /:versionId) to ensure correct matching.
  chunkVGR4DSXQ_cjs.LIST_MCP_CLIENT_VERSIONS_ROUTE,
  chunkVGR4DSXQ_cjs.CREATE_MCP_CLIENT_VERSION_ROUTE,
  chunkVGR4DSXQ_cjs.COMPARE_MCP_CLIENT_VERSIONS_ROUTE,
  chunkVGR4DSXQ_cjs.GET_MCP_CLIENT_VERSION_ROUTE,
  chunkVGR4DSXQ_cjs.ACTIVATE_MCP_CLIENT_VERSION_ROUTE,
  chunkVGR4DSXQ_cjs.RESTORE_MCP_CLIENT_VERSION_ROUTE,
  chunkVGR4DSXQ_cjs.DELETE_MCP_CLIENT_VERSION_ROUTE
];

// src/server/server-adapter/routes/stored-prompt-blocks.ts
var STORED_PROMPT_BLOCKS_ROUTES = [
  // Stored Prompt Blocks CRUD Routes
  chunk7VXUWPHS_cjs.LIST_STORED_PROMPT_BLOCKS_ROUTE,
  chunk7VXUWPHS_cjs.GET_STORED_PROMPT_BLOCK_ROUTE,
  chunk7VXUWPHS_cjs.CREATE_STORED_PROMPT_BLOCK_ROUTE,
  chunk7VXUWPHS_cjs.UPDATE_STORED_PROMPT_BLOCK_ROUTE,
  chunk7VXUWPHS_cjs.DELETE_STORED_PROMPT_BLOCK_ROUTE,
  // Prompt Block Versions Routes
  // IMPORTANT: Routes with literal paths (e.g., /compare) must come BEFORE
  // routes with path parameters (e.g., /:versionId) to ensure correct matching.
  chunkS7REEERK_cjs.LIST_PROMPT_BLOCK_VERSIONS_ROUTE,
  chunkS7REEERK_cjs.CREATE_PROMPT_BLOCK_VERSION_ROUTE,
  chunkS7REEERK_cjs.COMPARE_PROMPT_BLOCK_VERSIONS_ROUTE,
  chunkS7REEERK_cjs.GET_PROMPT_BLOCK_VERSION_ROUTE,
  chunkS7REEERK_cjs.ACTIVATE_PROMPT_BLOCK_VERSION_ROUTE,
  chunkS7REEERK_cjs.RESTORE_PROMPT_BLOCK_VERSION_ROUTE,
  chunkS7REEERK_cjs.DELETE_PROMPT_BLOCK_VERSION_ROUTE
];

// src/server/server-adapter/routes/stored-scorers.ts
var STORED_SCORERS_ROUTES = [
  // Stored Scorers CRUD Routes
  chunkMROI3O6S_cjs.LIST_STORED_SCORERS_ROUTE,
  chunkMROI3O6S_cjs.GET_STORED_SCORER_ROUTE,
  chunkMROI3O6S_cjs.CREATE_STORED_SCORER_ROUTE,
  chunkMROI3O6S_cjs.UPDATE_STORED_SCORER_ROUTE,
  chunkMROI3O6S_cjs.DELETE_STORED_SCORER_ROUTE,
  // Scorer Versions Routes
  // IMPORTANT: Routes with literal paths (e.g., /compare) must come BEFORE
  // routes with path parameters (e.g., /:versionId) to ensure correct matching.
  chunk2QNJHTKM_cjs.LIST_SCORER_VERSIONS_ROUTE,
  chunk2QNJHTKM_cjs.CREATE_SCORER_VERSION_ROUTE,
  chunk2QNJHTKM_cjs.COMPARE_SCORER_VERSIONS_ROUTE,
  chunk2QNJHTKM_cjs.GET_SCORER_VERSION_ROUTE,
  chunk2QNJHTKM_cjs.ACTIVATE_SCORER_VERSION_ROUTE,
  chunk2QNJHTKM_cjs.RESTORE_SCORER_VERSION_ROUTE,
  chunk2QNJHTKM_cjs.DELETE_SCORER_VERSION_ROUTE
];

// src/server/server-adapter/routes/stored-skills.ts
var STORED_SKILLS_ROUTES = [
  // Stored Skills CRUD Routes
  chunkOGEXISZT_cjs.LIST_STORED_SKILLS_ROUTE,
  chunkOGEXISZT_cjs.GET_STORED_SKILL_ROUTE,
  chunkOGEXISZT_cjs.CREATE_STORED_SKILL_ROUTE,
  chunkOGEXISZT_cjs.UPDATE_STORED_SKILL_ROUTE,
  chunkOGEXISZT_cjs.DELETE_STORED_SKILL_ROUTE,
  // Publish
  chunkOGEXISZT_cjs.PUBLISH_STORED_SKILL_ROUTE
];

// src/server/server-adapter/routes/stored-workspaces.ts
var STORED_WORKSPACES_ROUTES = [
  // Stored Workspaces CRUD Routes
  chunkQ2N5GR7X_cjs.LIST_STORED_WORKSPACES_ROUTE,
  chunkQ2N5GR7X_cjs.GET_STORED_WORKSPACE_ROUTE,
  chunkQ2N5GR7X_cjs.CREATE_STORED_WORKSPACE_ROUTE,
  chunkQ2N5GR7X_cjs.UPDATE_STORED_WORKSPACE_ROUTE,
  chunkQ2N5GR7X_cjs.DELETE_STORED_WORKSPACE_ROUTE
];

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

// src/server/server-adapter/routes/tool-providers.ts
var TOOL_PROVIDER_ROUTES = [
  chunkLVGLLXRY_cjs.LIST_TOOL_PROVIDERS_ROUTE,
  chunkLVGLLXRY_cjs.LIST_TOOL_PROVIDER_TOOLKITS_ROUTE,
  chunkLVGLLXRY_cjs.LIST_TOOL_PROVIDER_TOOLS_ROUTE,
  chunkLVGLLXRY_cjs.GET_TOOL_PROVIDER_TOOL_SCHEMA_ROUTE
];

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

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

// src/server/server-adapter/routes/workflows.ts
var WORKFLOWS_ROUTES = [
  chunkR4DZSQYI_cjs.LIST_WORKFLOWS_ROUTE,
  chunkR4DZSQYI_cjs.GET_WORKFLOW_BY_ID_ROUTE,
  chunkR4DZSQYI_cjs.LIST_WORKFLOW_RUNS_ROUTE,
  chunkR4DZSQYI_cjs.GET_WORKFLOW_RUN_BY_ID_ROUTE,
  chunkR4DZSQYI_cjs.DELETE_WORKFLOW_RUN_BY_ID_ROUTE,
  chunkR4DZSQYI_cjs.CREATE_WORKFLOW_RUN_ROUTE,
  chunkR4DZSQYI_cjs.STREAM_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.RESUME_STREAM_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.START_ASYNC_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.START_WORKFLOW_RUN_ROUTE,
  chunkR4DZSQYI_cjs.OBSERVE_STREAM_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.RESUME_ASYNC_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.RESUME_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.CANCEL_WORKFLOW_RUN_ROUTE,
  chunkR4DZSQYI_cjs.TIME_TRAVEL_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.TIME_TRAVEL_STREAM_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.RESTART_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.RESTART_ASYNC_WORKFLOW_ROUTE,
  chunkR4DZSQYI_cjs.RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE,
  chunkR4DZSQYI_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)
  chunkTNNU7IZK_cjs.LIST_WORKSPACES_ROUTE,
  // Get workspace route (at /api/workspaces/:workspaceId)
  chunkTNNU7IZK_cjs.GET_WORKSPACE_ROUTE,
  // Filesystem routes (at /api/workspaces/:workspaceId/fs/*)
  ...chunkTNNU7IZK_cjs.WORKSPACE_FS_ROUTES,
  // Search routes (at /api/workspaces/:workspaceId/search, /api/workspaces/:workspaceId/index)
  ...chunkTNNU7IZK_cjs.WORKSPACE_SEARCH_ROUTES,
  // Skills routes (search must come before parameterized routes)
  ...chunkTNNU7IZK_cjs.WORKSPACE_SKILLS_ROUTES,
  // skills.sh proxy routes (at /api/workspaces/:workspaceId/skills-sh/*)
  ...chunkTNNU7IZK_cjs.WORKSPACE_SKILLS_SH_ROUTES
];

// src/server/server-adapter/routes/permissions.ts
var METHOD_TO_ACTION = {
  GET: "read",
  POST: "write",
  // Default for POST, may be overridden to 'execute'
  PUT: "write",
  PATCH: "write",
  DELETE: "delete"
};
var EXECUTE_PATTERNS = [
  "/generate",
  "/stream",
  "/execute",
  "/start",
  "/resume",
  "/restart",
  "/cancel",
  "/approve",
  "/decline",
  "/speak",
  "/listen",
  "/query",
  "/search",
  "/observe",
  "/time-travel",
  "/enhance",
  "/clone"
];
function extractResource(path) {
  const segments = path.replace(/^\//, "").split("/");
  if (segments.length === 0) {
    return null;
  }
  const firstSegment = segments[0];
  if (firstSegment === "stored" && segments[1] === "agents") {
    return "stored-agents";
  }
  if (firstSegment === ".well-known") {
    return "a2a";
  }
  return firstSegment || null;
}
function deriveAction(method, path) {
  const upperMethod = method.toUpperCase();
  if (upperMethod === "POST") {
    const isExecuteOperation = EXECUTE_PATTERNS.some((pattern) => path.includes(pattern));
    return isExecuteOperation ? "execute" : "write";
  }
  return METHOD_TO_ACTION[upperMethod] || "read";
}
function derivePermission(route) {
  if (route.method === "ALL") {
    return null;
  }
  const resource = extractResource(route.path);
  if (!resource) {
    return null;
  }
  const action = deriveAction(route.method, route.path);
  return `${resource}:${action}`;
}
function getEffectivePermission(route) {
  if (route.requiresAuth === false) {
    return null;
  }
  if (route.requiresPermission) {
    return route.requiresPermission;
  }
  return derivePermission(route);
}

// src/server/server-adapter/routes/index.ts
var SERVER_ROUTES = [
  ...AGENTS_ROUTES,
  ...chunkPSQNWPPT_cjs.AUTH_ROUTES,
  ...WORKFLOWS_ROUTES,
  ...TOOLS_ROUTES,
  ...PROCESSORS_ROUTES,
  ...RESPONSES_ROUTES,
  ...CONVERSATIONS_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,
  ...STORED_MCP_CLIENTS_ROUTES,
  ...STORED_PROMPT_BLOCKS_ROUTES,
  ...STORED_SCORERS_ROUTES,
  ...STORED_WORKSPACES_ROUTES,
  ...STORED_SKILLS_ROUTES,
  ...TOOL_PROVIDER_ROUTES,
  ...PROCESSOR_PROVIDER_ROUTES,
  ...SYSTEM_ROUTES,
  ...DATASETS_ROUTES,
  ...BACKGROUND_TASK_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 getSchemaTypeName(schema) {
  const schemaDef = schema?._def ?? schema?.def;
  return schemaDef?.typeName ?? schemaDef?.type;
}
function unwrapOptionalNullable(schema) {
  let inner = schema;
  let typeName = getSchemaTypeName(inner);
  while (typeName === "ZodOptional" || typeName === "ZodNullable" || typeName === "optional" || typeName === "nullable") {
    const innerDef = inner?._def ?? inner?.def;
    if (!innerDef?.innerType) {
      return inner;
    }
    inner = innerDef.innerType;
    typeName = getSchemaTypeName(inner);
  }
  return inner;
}
function parseComplexQueryParams(queryParamSchema, params) {
  if (!(queryParamSchema instanceof v4.z.ZodObject)) {
    return params;
  }
  const parsedParams = { ...params };
  const shape = queryParamSchema.shape;
  for (const [key, fieldSchema] of Object.entries(shape)) {
    const rawValue = parsedParams[key];
    if (typeof rawValue !== "string") {
      continue;
    }
    const unwrappedField = unwrapOptionalNullable(fieldSchema);
    const typeName = getSchemaTypeName(unwrappedField);
    const isComplex = typeName === "ZodObject" || typeName === "ZodArray" || typeName === "ZodRecord" || typeName === "object" || typeName === "array" || typeName === "record";
    if (!isComplex) {
      continue;
    }
    try {
      parsedParams[key] = JSON.parse(rawValue);
    } catch {
    }
  }
  return parsedParams;
}
function normalizeQueryParams(rawQuery) {
  const queryParams = {};
  const bracketGroups = {};
  for (const [key, value] of Object.entries(rawQuery)) {
    const bracketMatch = key.match(/^([^[]+)\[([^\]]+)\]$/);
    if (bracketMatch) {
      const parent = bracketMatch[1];
      const child = bracketMatch[2];
      const strValue = Array.isArray(value) ? value.filter((v) => typeof v === "string")[0] : typeof value === "string" ? value : void 0;
      if (strValue !== void 0) {
        if (!bracketGroups[parent]) {
          bracketGroups[parent] = {};
        }
        bracketGroups[parent][child] = strValue;
      }
    } else 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;
    }
  }
  for (const [parent, children] of Object.entries(bracketGroups)) {
    if (!(parent in queryParams)) {
      queryParams[parent] = JSON.stringify(children);
    }
  }
  return queryParams;
}
var MastraServer = class _MastraServer extends server.MastraServerBase {
  mastra;
  bodyLimitOptions;
  tools;
  prefix;
  openapiPath;
  taskStore;
  customRouteAuthConfig;
  streamOptions;
  httpLoggingConfig;
  customApiRoutes;
  mcpOptions;
  customRouteHandler = null;
  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 = chunkYJQYJ5WD_cjs.normalizeRoutePath(prefix);
    this.openapiPath = openapiPath;
    this.taskStore = taskStore;
    this.customRouteAuthConfig = customRouteAuthConfig;
    this.streamOptions = { redact: true, ...streamOptions };
    this.customApiRoutes = customApiRoutes;
    this.mcpOptions = mcpOptions;
    const serverConfig = mastra.getServer();
    this.httpLoggingConfig = this.parseLoggingConfig(serverConfig?.build?.apiReqLogs);
    mastra.setMastraServer(this);
  }
  /**
   * Parses the apiReqLogs configuration into a normalized HttpLoggingConfig.
   * @param config - The raw config value from server.build.apiReqLogs
   * @returns Normalized HttpLoggingConfig or undefined if disabled
   */
  parseLoggingConfig(config) {
    if (config === true) {
      return {
        enabled: true,
        level: "info",
        redactHeaders: ["authorization", "cookie"]
      };
    }
    if (typeof config === "object" && config.enabled) {
      return {
        enabled: true,
        level: config.level || "info",
        excludePaths: config.excludePaths,
        includeHeaders: config.includeHeaders,
        includeQueryParams: config.includeQueryParams,
        redactHeaders: [.../* @__PURE__ */ new Set([...["authorization", "cookie"], ...config.redactHeaders || []])]
      };
    }
    return void 0;
  }
  /**
   * Determines if a request to the given path should be logged.
   * @param path - The request path to check
   * @returns true if the request should be logged, false otherwise
   */
  shouldLogRequest(path) {
    if (!this.httpLoggingConfig?.enabled) {
      return false;
    }
    const excludePaths = this.httpLoggingConfig.excludePaths || [];
    return !excludePaths.some((excluded) => path === excluded || path.startsWith(excluded + "/"));
  }
  static RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([chunkI3BHHWHT_cjs.MASTRA_RESOURCE_ID_KEY, chunkI3BHHWHT_cjs.MASTRA_THREAD_ID_KEY]);
  mergeRequestContext({
    paramsRequestContext,
    bodyRequestContext
  }) {
    const requestContext$1 = new requestContext.RequestContext();
    if (bodyRequestContext) {
      for (const [key, value] of Object.entries(bodyRequestContext)) {
        if (_MastraServer.RESERVED_CONTEXT_KEYS.has(key)) continue;
        requestContext$1.set(key, value);
      }
    }
    if (paramsRequestContext) {
      for (const [key, value] of Object.entries(paramsRequestContext)) {
        if (_MastraServer.RESERVED_CONTEXT_KEYS.has(key)) continue;
        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 is a thin wrapper around coreAuthMiddleware that:
   * 1. Handles route-level requiresAuth opt-out (not available in global middleware)
   * 2. Delegates all other auth logic to coreAuthMiddleware
   * 3. Translates the AuthResult into the {status, error} format adapters expect
   */
  async checkRouteAuth(route, context) {
    const authConfig = this.mastra.getServer()?.auth;
    if (!authConfig) {
      return null;
    }
    if (route.requiresAuth === false) {
      return null;
    }
    const authHeader = context.getHeader("authorization");
    let token = authHeader ? authHeader.replace("Bearer ", "") : null;
    if (!token) {
      token = context.getQuery("apiKey") || null;
    }
    const result = await chunk5BXP7S4P_cjs.coreAuthMiddleware({
      path: context.path,
      method: context.method,
      getHeader: context.getHeader,
      mastra: this.mastra,
      authConfig,
      customRouteAuthConfig: this.customRouteAuthConfig,
      requestContext: context.requestContext,
      rawRequest: context.request,
      token,
      buildAuthorizeContext: context.buildAuthorizeContext ?? (() => null)
    });
    if (result.action === "next") {
      if (result.headers) {
        return { status: 200, error: "", headers: result.headers };
      }
      return null;
    }
    const errorBody = result.body;
    return { status: result.status, error: errorBody?.error ?? "Access denied", headers: result.headers };
  }
  /**
   * Check if the user has the required permission for a route.
   *
   * Uses convention-based permission derivation:
   * 1. If route has explicit `requiresPermission`, use that
   * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)
   * 3. Routes with `requiresAuth: false` skip permission checks
   *
   * @param route - The route being accessed
   * @param userPermissions - The user's permissions from the request context
   * @returns Error response if permission denied, null if allowed
   */
  checkRoutePermission(route, userPermissions, hasPermissionFn) {
    const rbacProvider = this.mastra.getServer()?.rbac;
    if (!rbacProvider) {
      return null;
    }
    const requiredPermission = getEffectivePermission(route);
    if (!requiredPermission) {
      return null;
    }
    if (!userPermissions || !hasPermissionFn(userPermissions, requiredPermission)) {
      return {
        status: 403,
        error: "Forbidden",
        message: `Missing required permission: ${requiredPermission}`
      };
    }
    return null;
  }
  async init() {
    this.registerContextMiddleware();
    this.registerAuthMiddleware();
    this.registerHttpLoggingMiddleware();
    await this.validateEELicense();
    await this.registerCustomApiRoutes();
    await this.registerRoutes();
  }
  /**
   * Validate that EE features have a valid license in production.
   * Throws if RBAC is configured without a valid license outside dev/test environments.
   */
  async validateEELicense() {
    const rbacProvider = this.mastra.getServer()?.rbac;
    if (!rbacProvider) return;
    try {
      const { isEEEnabled } = await import('@mastra/core/auth/ee');
      if (!isEEEnabled()) {
        throw new Error(
          "[mastra/auth-ee] RBAC is configured but no valid EE license was found.\nRBAC requires a Mastra Enterprise License for production use.\nSet the MASTRA_EE_LICENSE environment variable with your license key.\nLearn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE"
        );
      }
    } catch (err) {
      if (err instanceof Error && err.message.startsWith("[mastra/auth-ee]")) {
        throw err;
      }
      throw new Error(
        "[mastra/auth-ee] RBAC is configured but the EE module (@mastra/core/auth/ee) could not be loaded.\nEnsure @mastra/core is updated to a version that includes EE support."
      );
    }
  }
  /**
   * Override in adapters to register custom API routes defined via registerApiRoute().
   * Called by init() between registerAuthMiddleware() and registerRoutes().
   */
  async registerCustomApiRoutes() {
  }
  /**
   * Validates that no custom route path collides with the built-in route prefix.
   * Throws if any route path starts with the server's `apiPrefix`.
   */
  validateCustomRoutePaths(routes) {
    const prefix = this.prefix ?? "";
    if (!prefix) return;
    for (const route of routes) {
      if (route.path.startsWith(`${prefix}/`) || route.path === prefix) {
        throw new Error(
          `Custom API route "${route.path}" must not start with "${prefix}" \u2014 that path is reserved for built-in Mastra routes. Choose a different path (e.g. "${route.path.replace(prefix, "/custom")}").`
        );
      }
    }
  }
  /**
   * Creates an internal Hono sub-app with all custom API routes registered.
   * Stores the handler on this instance for use by handleCustomRouteRequest().
   * Returns true if custom routes were found and registered.
   */
  async buildCustomRouteHandler() {
    const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;
    if (!routes || routes.length === 0) return false;
    const NOT_FOUND_HEADER = "x-mastra-custom-route-not-found";
    const mastra = this.mastra;
    const app = new hono.Hono();
    app.use("*", async (c, next) => {
      c.set("mastra", mastra);
      c.set("requestContext", c.env?.requestContext ?? new requestContext.RequestContext());
      await next();
    });
    const serverOnError = this.mastra.getServer()?.onError;
    app.onError((err, c) => {
      if (serverOnError) {
        return serverOnError(err, c);
      }
      return c.json({ error: "Internal Server Error" }, 500);
    });
    this.validateCustomRoutePaths(routes);
    for (const route of routes) {
      const handler = "handler" in route && route.handler ? route.handler : "createHandler" in route ? await route.createHandler({ mastra }) : void 0;
      if (!handler) continue;
      const middlewares = [];
      if (route.middleware) {
        middlewares.push(...Array.isArray(route.middleware) ? route.middleware : [route.middleware]);
      }
      const allHandlers = [...middlewares, handler];
      if (route.method === "ALL") {
        app.all(route.path, allHandlers[0], ...allHandlers.slice(1));
      } else {
        app.on(route.method, route.path, allHandlers[0], ...allHandlers.slice(1));
      }
    }
    app.notFound(() => new Response(null, { status: 404, headers: { [NOT_FOUND_HEADER]: "true" } }));
    this.customRouteHandler = async (request, env) => app.fetch(request, env);
    return true;
  }
  /**
   * Forwards a request to the internal custom route handler.
   * Returns the Response if a custom route matched, or null to fall through.
   */
  async handleCustomRouteRequest(url, method, headers, body, requestContext) {
    if (!this.customRouteHandler) return null;
    const fetchHeaders = new Headers();
    for (const [key, value] of Object.entries(headers)) {
      if (typeof value === "string") fetchHeaders.set(key, value);
      else if (Array.isArray(value))
        value.forEach((v) => {
          fetchHeaders.append(key, v);
        });
    }
    const init = { method, headers: fetchHeaders };
    if (["POST", "PUT", "PATCH"].includes(method) && body !== void 0) {
      if (body instanceof ArrayBuffer || body instanceof Uint8Array || body instanceof ReadableStream) {
        init.body = body;
        if (body instanceof ReadableStream) {
          init.duplex = "half";
        }
      } else {
        const contentType = (typeof headers["content-type"] === "string" ? headers["content-type"] : "") || "";
        if (contentType.includes("application/json")) {
          init.body = JSON.stringify(body);
        } else if (typeof body === "string") {
          init.body = body;
        }
      }
    }
    const request = new globalThis.Request(url, init);
    const response = await this.customRouteHandler(request, { requestContext });
    if (response.headers.get("x-mastra-custom-route-not-found") === "true") return null;
    return response;
  }
  /**
   * Pipes a custom route Response to a Node.js ServerResponse (http.ServerResponse).
   * Works with Koa (ctx.res), Express (res), and Fastify (reply.raw).
   */
  async writeCustomRouteResponse(response, nodeRes) {
    const headers = {};
    response.headers.forEach((value, key) => {
      if (key.toLowerCase() !== "set-cookie") {
        headers[key] = value;
      }
    });
    const setCookies = response.headers.getSetCookie?.();
    if (setCookies && setCookies.length > 0) {
      headers["set-cookie"] = setCookies;
    }
    nodeRes.writeHead(response.status, headers);
    if (response.body) {
      const reader = response.body.getReader();
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          nodeRes.write(value);
        }
      } finally {
        nodeRes.end();
      }
    } else {
      nodeRes.end(await response.text());
    }
  }
  /**
   * Builds the OpenAPI spec object with servers field and custom route paths.
   */
  buildOpenAPISpec(config, prefix) {
    const openApiSpec = chunk5UKYK7YK_cjs.generateOpenAPIDocument(SERVER_ROUTES, config);
    if (prefix) {
      openApiSpec.servers = [{ url: prefix }];
    }
    const allCustomRoutes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;
    if (allCustomRoutes && allCustomRoutes.length > 0) {
      const customPaths = chunk5UKYK7YK_cjs.convertCustomRoutesToOpenAPIPaths(allCustomRoutes);
      if (prefix) {
        for (const pathKey of Object.keys(customPaths)) {
          if (!customPaths[pathKey].servers) {
            customPaths[pathKey].servers = [{ url: "/" }];
          }
        }
      }
      openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };
    }
    return openApiSpec;
  }
  async registerOpenAPIRoute(app, config = {}, { prefix }) {
    const {
      title = "Mastra API",
      version = "1.0.0",
      description = "Mastra Server API",
      path = "/openapi.json"
    } = config;
    const openApiSpec = this.buildOpenAPISpec({ title, version, description }, prefix);
    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) {
      const specConfig = {
        title: "Mastra API",
        version: "1.0.0",
        description: "Mastra Server API"
      };
      await this.registerOpenAPIRoute(this.app, { ...specConfig, 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;
    }
    const normalizedParams = parseComplexQueryParams(queryParamSchema, params);
    return queryParamSchema.parseAsync(normalizedParams);
  }
  async parseBody(route, body) {
    const bodySchema = route.bodySchema;
    if (!bodySchema) {
      return body;
    }
    return bodySchema.parseAsync(body);
  }
  static CONTEXT_LABELS = {
    query: "query parameters",
    body: "request body",
    path: "path parameters"
  };
  resolveValidationError(route, error, context) {
    const hook = route.onValidationError ?? this.mastra.getServer()?.onValidationError;
    if (hook) {
      try {
        const result = hook(error, context);
        if (result) {
          return result;
        }
      } catch (hookError) {
        this.mastra.getLogger()?.error("Error in custom onValidationError hook", {
          error: hookError instanceof Error ? { message: hookError.message, stack: hookError.stack } : hookError
        });
      }
    }
    return {
      status: 400,
      body: chunkB34S64RC_cjs.formatZodError(error, _MastraServer.CONTEXT_LABELS[context])
    };
  }
};

Object.defineProperty(exports, "WorkflowRegistry", {
  enumerable: true,
  get: function () { return chunkYJQYJ5WD_cjs.WorkflowRegistry; }
});
Object.defineProperty(exports, "normalizeRoutePath", {
  enumerable: true,
  get: function () { return chunkYJQYJ5WD_cjs.normalizeRoutePath; }
});
Object.defineProperty(exports, "createPublicRoute", {
  enumerable: true,
  get: function () { return chunk5UKYK7YK_cjs.createPublicRoute; }
});
Object.defineProperty(exports, "createRoute", {
  enumerable: true,
  get: function () { return chunk5UKYK7YK_cjs.createRoute; }
});
Object.defineProperty(exports, "generateOpenAPIDocument", {
  enumerable: true,
  get: function () { return chunk5UKYK7YK_cjs.generateOpenAPIDocument; }
});
Object.defineProperty(exports, "jsonQueryParam", {
  enumerable: true,
  get: function () { return chunk5UKYK7YK_cjs.jsonQueryParam; }
});
Object.defineProperty(exports, "pickParams", {
  enumerable: true,
  get: function () { return chunk5UKYK7YK_cjs.pickParams; }
});
Object.defineProperty(exports, "wrapSchemaForQueryParams", {
  enumerable: true,
  get: function () { return chunk5UKYK7YK_cjs.wrapSchemaForQueryParams; }
});
exports.MastraServer = MastraServer;
exports.SERVER_ROUTES = SERVER_ROUTES;
exports.deriveAction = deriveAction;
exports.derivePermission = derivePermission;
exports.extractResource = extractResource;
exports.getEffectivePermission = getEffectivePermission;
exports.normalizeQueryParams = normalizeQueryParams;
exports.redactStreamChunk = redactStreamChunk;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map