import { LIST_WORKSPACES_ROUTE, GET_WORKSPACE_ROUTE, WORKSPACE_FS_ROUTES, WORKSPACE_SEARCH_ROUTES, WORKSPACE_SKILLS_ROUTES, WORKSPACE_SKILLS_SH_ROUTES } from '../../chunk-EVZKLTS4.js';
import { LIST_STORED_AGENTS_ROUTE, GET_STORED_AGENT_ROUTE, CREATE_STORED_AGENT_ROUTE, UPDATE_STORED_AGENT_ROUTE, DELETE_STORED_AGENT_ROUTE } from '../../chunk-TEE5OFYW.js';
import { GET_SYSTEM_PACKAGES_ROUTE } from '../../chunk-SVB5WZDR.js';
import { AUTH_ROUTES } from '../../chunk-W2TTIJIE.js';
import { LIST_PROCESSORS_ROUTE, GET_PROCESSOR_BY_ID_ROUTE, EXECUTE_PROCESSOR_ROUTE } from '../../chunk-OMOE6NPR.js';
import { EXECUTE_AGENT_TOOL_ROUTE, GET_AGENT_TOOL_ROUTE, LIST_TOOLS_ROUTE, GET_TOOL_BY_ID_ROUTE, EXECUTE_TOOL_ROUTE } from '../../chunk-HTAKUG4C.js';
import { UPSERT_VECTORS_ROUTE, CREATE_INDEX_ROUTE, QUERY_VECTORS_ROUTE, LIST_INDEXES_ROUTE, DESCRIBE_INDEX_ROUTE, DELETE_INDEX_ROUTE } from '../../chunk-ARP7GTZU.js';
import { GET_SPEAKERS_ROUTE, GET_SPEAKERS_DEPRECATED_ROUTE, GENERATE_SPEECH_ROUTE, GENERATE_SPEECH_DEPRECATED_ROUTE, TRANSCRIBE_SPEECH_ROUTE, TRANSCRIBE_SPEECH_DEPRECATED_ROUTE, GET_LISTENER_ROUTE } from '../../chunk-3WQCUEWC.js';
import { LIST_LOG_TRANSPORTS_ROUTE, LIST_LOGS_ROUTE, LIST_LOGS_BY_RUN_ID_ROUTE } from '../../chunk-77SCZWVU.js';
import { LIST_MCP_SERVERS_ROUTE, GET_MCP_SERVER_DETAIL_ROUTE, LIST_MCP_SERVER_TOOLS_ROUTE, GET_MCP_SERVER_TOOL_DETAIL_ROUTE, EXECUTE_MCP_SERVER_TOOL_ROUTE, MCP_HTTP_TRANSPORT_ROUTE, MCP_SSE_TRANSPORT_ROUTE, MCP_SSE_MESSAGES_ROUTE } from '../../chunk-J5GKDQLX.js';
import { GET_MEMORY_STATUS_ROUTE, GET_MEMORY_CONFIG_ROUTE, LIST_THREADS_ROUTE, GET_THREAD_BY_ID_ROUTE, LIST_MESSAGES_ROUTE, GET_WORKING_MEMORY_ROUTE, SAVE_MESSAGES_ROUTE, CREATE_THREAD_ROUTE, UPDATE_THREAD_ROUTE, DELETE_THREAD_ROUTE, CLONE_THREAD_ROUTE, UPDATE_WORKING_MEMORY_ROUTE, DELETE_MESSAGES_ROUTE, SEARCH_MEMORY_ROUTE, GET_MEMORY_STATUS_NETWORK_ROUTE, LIST_THREADS_NETWORK_ROUTE, GET_THREAD_BY_ID_NETWORK_ROUTE, LIST_MESSAGES_NETWORK_ROUTE, SAVE_MESSAGES_NETWORK_ROUTE, CREATE_THREAD_NETWORK_ROUTE, UPDATE_THREAD_NETWORK_ROUTE, DELETE_THREAD_NETWORK_ROUTE, DELETE_MESSAGES_NETWORK_ROUTE } from '../../chunk-LU2HDW7X.js';
import { LIST_TRACES_ROUTE, GET_TRACE_ROUTE, SCORE_TRACES_ROUTE, LIST_SCORES_BY_SPAN_ROUTE } from '../../chunk-NR6U3X76.js';
import { LIST_SCORERS_ROUTE, GET_SCORER_ROUTE, LIST_SCORES_BY_RUN_ID_ROUTE, LIST_SCORES_BY_SCORER_ID_ROUTE, LIST_SCORES_BY_ENTITY_ID_ROUTE, SAVE_SCORE_ROUTE } from '../../chunk-I5CKVVOL.js';
import { isDevPlaygroundRequest, canAccessPublicly, checkRules, defaultAuthConfig } from '../../chunk-FKZEQP3O.js';
import { GET_AGENT_CARD_ROUTE, AGENT_EXECUTION_ROUTE } from '../../chunk-JBEXZSCD.js';
import { LIST_AGENT_BUILDER_ACTIONS_ROUTE, GET_AGENT_BUILDER_ACTION_BY_ID_ROUTE, LIST_AGENT_BUILDER_ACTION_RUNS_ROUTE, GET_AGENT_BUILDER_ACTION_RUN_BY_ID_ROUTE, CREATE_AGENT_BUILDER_ACTION_RUN_ROUTE, STREAM_AGENT_BUILDER_ACTION_ROUTE, START_ASYNC_AGENT_BUILDER_ACTION_ROUTE, START_AGENT_BUILDER_ACTION_RUN_ROUTE, OBSERVE_STREAM_AGENT_BUILDER_ACTION_ROUTE, RESUME_ASYNC_AGENT_BUILDER_ACTION_ROUTE, RESUME_AGENT_BUILDER_ACTION_ROUTE, RESUME_STREAM_AGENT_BUILDER_ACTION_ROUTE, CANCEL_AGENT_BUILDER_ACTION_RUN_ROUTE, STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE, OBSERVE_STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE } from '../../chunk-NVXBYWQE.js';
import { LIST_WORKFLOWS_ROUTE, GET_WORKFLOW_BY_ID_ROUTE, LIST_WORKFLOW_RUNS_ROUTE, GET_WORKFLOW_RUN_BY_ID_ROUTE, DELETE_WORKFLOW_RUN_BY_ID_ROUTE, CREATE_WORKFLOW_RUN_ROUTE, STREAM_WORKFLOW_ROUTE, RESUME_STREAM_WORKFLOW_ROUTE, START_ASYNC_WORKFLOW_ROUTE, START_WORKFLOW_RUN_ROUTE, OBSERVE_STREAM_WORKFLOW_ROUTE, RESUME_ASYNC_WORKFLOW_ROUTE, RESUME_WORKFLOW_ROUTE, CANCEL_WORKFLOW_RUN_ROUTE, TIME_TRAVEL_WORKFLOW_ROUTE, TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE, TIME_TRAVEL_STREAM_WORKFLOW_ROUTE, RESTART_WORKFLOW_ROUTE, RESTART_ASYNC_WORKFLOW_ROUTE, RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE, RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE, STREAM_LEGACY_WORKFLOW_ROUTE, OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE } from '../../chunk-ES5OZHJ4.js';
import { normalizeRoutePath } from '../../chunk-ED6NQBHF.js';
export { WorkflowRegistry, normalizeRoutePath } from '../../chunk-ED6NQBHF.js';
import { LIST_AGENT_VERSIONS_ROUTE, CREATE_AGENT_VERSION_ROUTE, COMPARE_AGENT_VERSIONS_ROUTE, GET_AGENT_VERSION_ROUTE, ACTIVATE_AGENT_VERSION_ROUTE, RESTORE_AGENT_VERSION_ROUTE, DELETE_AGENT_VERSION_ROUTE } from '../../chunk-SYLEQ6LR.js';
import { LIST_AGENTS_ROUTE, GET_PROVIDERS_ROUTE, GET_AGENT_BY_ID_ROUTE, GENERATE_AGENT_ROUTE, GENERATE_AGENT_VNEXT_ROUTE, STREAM_GENERATE_ROUTE, STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE, APPROVE_TOOL_CALL_ROUTE, DECLINE_TOOL_CALL_ROUTE, APPROVE_TOOL_CALL_GENERATE_ROUTE, DECLINE_TOOL_CALL_GENERATE_ROUTE, APPROVE_NETWORK_TOOL_CALL_ROUTE, DECLINE_NETWORK_TOOL_CALL_ROUTE, STREAM_NETWORK_ROUTE, UPDATE_AGENT_MODEL_ROUTE, RESET_AGENT_MODEL_ROUTE, REORDER_AGENT_MODEL_LIST_ROUTE, UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE, ENHANCE_INSTRUCTIONS_ROUTE, GET_AGENT_SKILL_ROUTE, STREAM_VNEXT_DEPRECATED_ROUTE, STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE, STREAM_UI_MESSAGE_DEPRECATED_ROUTE, GENERATE_LEGACY_ROUTE, STREAM_GENERATE_LEGACY_ROUTE } from '../../chunk-FTIE33GO.js';
import { generateOpenAPIDocument, convertCustomRoutesToOpenAPIPaths } from '../../chunk-OQ5GQJAS.js';
export { createPublicRoute, createRoute, generateOpenAPIDocument, jsonQueryParam, pickParams, wrapSchemaForQueryParams } from '../../chunk-OQ5GQJAS.js';
import { RequestContext } from '@mastra/core/request-context';
import { MastraServerBase } from '@mastra/core/server';

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

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

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

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

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

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

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

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

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

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

// src/server/server-adapter/routes/stored-agents.ts
var STORED_AGENTS_ROUTES = [
  // ============================================================================
  // Stored Agents CRUD Routes
  // ============================================================================
  LIST_STORED_AGENTS_ROUTE,
  GET_STORED_AGENT_ROUTE,
  CREATE_STORED_AGENT_ROUTE,
  UPDATE_STORED_AGENT_ROUTE,
  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.
  // ============================================================================
  LIST_AGENT_VERSIONS_ROUTE,
  CREATE_AGENT_VERSION_ROUTE,
  COMPARE_AGENT_VERSIONS_ROUTE,
  // Must be before GET_AGENT_VERSION_ROUTE
  GET_AGENT_VERSION_ROUTE,
  ACTIVATE_AGENT_VERSION_ROUTE,
  RESTORE_AGENT_VERSION_ROUTE,
  DELETE_AGENT_VERSION_ROUTE
];

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

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

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

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

// src/server/server-adapter/routes/workspace.ts
var WORKSPACE_ROUTES = [
  // List all workspaces route (at /api/workspaces)
  LIST_WORKSPACES_ROUTE,
  // Get workspace route (at /api/workspaces/:workspaceId)
  GET_WORKSPACE_ROUTE,
  // Filesystem routes (at /api/workspaces/:workspaceId/fs/*)
  ...WORKSPACE_FS_ROUTES,
  // Search routes (at /api/workspaces/:workspaceId/search, /api/workspaces/:workspaceId/index)
  ...WORKSPACE_SEARCH_ROUTES,
  // Skills routes (search must come before parameterized routes)
  ...WORKSPACE_SKILLS_ROUTES,
  // skills.sh proxy routes (at /api/workspaces/:workspaceId/skills-sh/*)
  ...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,
  ...AUTH_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 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 = 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 = new RequestContext();
    if (bodyRequestContext) {
      for (const [key, value] of Object.entries(bodyRequestContext)) {
        requestContext.set(key, value);
      }
    }
    if (paramsRequestContext) {
      for (const [key, value] of Object.entries(paramsRequestContext)) {
        requestContext.set(key, value);
      }
    }
    return requestContext;
  }
  /**
   * 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 (isDevPlaygroundRequest(context.path, context.method, context.getHeader, authConfig)) {
      return null;
    }
    if (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;
    }
    let user;
    try {
      if (typeof authConfig.authenticateToken === "function") {
        user = await authConfig.authenticateToken(token ?? "", context.request);
      } else {
        return { status: 401, error: "No token verification method configured" };
      }
      if (!user) {
        return { status: 401, error: "Authentication required" };
      }
      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 checkRules(authConfig.rules, context.path, context.method, user);
      if (isAuthorized) {
        return null;
      }
      return { status: 403, error: "Access denied" };
    }
    if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {
      const isAuthorized = await checkRules(defaultAuthConfig.rules, context.path, context.method, user);
      if (isAuthorized) {
        return null;
      }
    }
    return { status: 403, error: "Access denied" };
  }
  /**
   * 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 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();
    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 = generateOpenAPIDocument(SERVER_ROUTES, {
      title,
      version,
      description
    });
    if (this.customApiRoutes && this.customApiRoutes.length > 0) {
      const customPaths = 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);
  }
};

export { MastraServer, SERVER_ROUTES, deriveAction, derivePermission, extractResource, getEffectivePermission, normalizeQueryParams, redactStreamChunk };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map