'use strict';

var chunkPTPMBE6M_cjs = require('./chunk-PTPMBE6M.cjs');
var chunkZQ4GVMYG_cjs = require('./chunk-ZQ4GVMYG.cjs');
var chunk42M6Y2OD_cjs = require('./chunk-42M6Y2OD.cjs');
var chunkDIG2K5CV_cjs = require('./chunk-DIG2K5CV.cjs');
var chunkDRDVJ35H_cjs = require('./chunk-DRDVJ35H.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var stream = require('@mastra/core/stream');
var v4 = require('zod/v4');

// src/server/handlers/workflows.ts
var workflows_exports = {};
chunkO7I5CWRX_cjs.__export(workflows_exports, {
  CANCEL_WORKFLOW_RUN_ROUTE: () => CANCEL_WORKFLOW_RUN_ROUTE,
  CREATE_WORKFLOW_RUN_ROUTE: () => CREATE_WORKFLOW_RUN_ROUTE,
  DELETE_WORKFLOW_RUN_BY_ID_ROUTE: () => DELETE_WORKFLOW_RUN_BY_ID_ROUTE,
  EXECUTE_WORKFLOW_STEP_ROUTE: () => EXECUTE_WORKFLOW_STEP_ROUTE,
  GET_WORKFLOW_BY_ID_ROUTE: () => GET_WORKFLOW_BY_ID_ROUTE,
  GET_WORKFLOW_RUN_BY_ID_ROUTE: () => GET_WORKFLOW_RUN_BY_ID_ROUTE,
  LIST_WORKFLOWS_ROUTE: () => LIST_WORKFLOWS_ROUTE,
  LIST_WORKFLOW_RUNS_ROUTE: () => LIST_WORKFLOW_RUNS_ROUTE,
  OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE: () => OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE,
  OBSERVE_STREAM_WORKFLOW_ROUTE: () => OBSERVE_STREAM_WORKFLOW_ROUTE,
  RECEIVE_WORKFLOW_EVENT_ROUTE: () => RECEIVE_WORKFLOW_EVENT_ROUTE,
  RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE: () => RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE,
  RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE: () => RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE,
  RESTART_ASYNC_WORKFLOW_ROUTE: () => RESTART_ASYNC_WORKFLOW_ROUTE,
  RESTART_WORKFLOW_ROUTE: () => RESTART_WORKFLOW_ROUTE,
  RESUME_ASYNC_WORKFLOW_ROUTE: () => RESUME_ASYNC_WORKFLOW_ROUTE,
  RESUME_NO_WAIT_WORKFLOW_ROUTE: () => RESUME_NO_WAIT_WORKFLOW_ROUTE,
  RESUME_STREAM_WORKFLOW_ROUTE: () => RESUME_STREAM_WORKFLOW_ROUTE,
  RESUME_WORKFLOW_ROUTE: () => RESUME_WORKFLOW_ROUTE,
  START_ASYNC_WORKFLOW_ROUTE: () => START_ASYNC_WORKFLOW_ROUTE,
  START_WORKFLOW_RUN_ROUTE: () => START_WORKFLOW_RUN_ROUTE,
  STREAM_LEGACY_WORKFLOW_ROUTE: () => STREAM_LEGACY_WORKFLOW_ROUTE,
  STREAM_WORKFLOW_ROUTE: () => STREAM_WORKFLOW_ROUTE,
  TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE: () => TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE,
  TIME_TRAVEL_STREAM_WORKFLOW_ROUTE: () => TIME_TRAVEL_STREAM_WORKFLOW_ROUTE,
  TIME_TRAVEL_WORKFLOW_ROUTE: () => TIME_TRAVEL_WORKFLOW_ROUTE
});
async function listWorkflowsFromSystem({ mastra, workflowId }) {
  const logger = mastra.getLogger();
  if (!workflowId) {
    throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
  }
  let workflow;
  workflow = chunkDRDVJ35H_cjs.WorkflowRegistry.getWorkflow(workflowId);
  if (!workflow) {
    try {
      workflow = mastra.getWorkflowById(workflowId);
    } catch (error) {
      logger.debug("Error getting workflow, searching agents for workflow", error);
    }
  }
  if (!workflow) {
    logger.debug("Workflow not found, searching agents for workflow", { workflowId });
    const agents = mastra.listAgents();
    if (Object.keys(agents || {}).length) {
      for (const [_, agent] of Object.entries(agents)) {
        try {
          const workflows = await agent.listWorkflows();
          if (workflows[workflowId]) {
            workflow = workflows[workflowId];
            break;
          }
        } catch (error) {
          logger.debug("Error getting workflow from agent", error);
        }
      }
    }
  }
  if (!workflow) {
    throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
  }
  return { workflow };
}
var LIST_WORKFLOWS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/workflows",
  responseType: "json",
  queryParamSchema: v4.z.object({
    partial: v4.z.string().optional()
  }),
  responseSchema: chunkPTPMBE6M_cjs.listWorkflowsResponseSchema,
  summary: "List all workflows",
  description: "Returns a list of all available workflows in the system",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: (async ({ mastra, partial, requestContext }) => {
    try {
      const workflows = mastra.listWorkflows({ serialized: false });
      const isPartial = partial === "true";
      const _workflows = Object.entries(workflows).reduce((acc, [key, workflow]) => {
        acc[key] = chunkDRDVJ35H_cjs.getWorkflowInfo(workflow, isPartial);
        return acc;
      }, {});
      const fgaProvider = mastra.getServer?.()?.fga;
      const user = requestContext?.get("user");
      if (fgaProvider) {
        if (!user) {
          return {};
        }
        const workflowList = Object.entries(_workflows).map(([id, w]) => ({ id, ...w }));
        const accessible = await fgaProvider.filterAccessible(
          user,
          workflowList,
          "workflow",
          chunk42M6Y2OD_cjs.MastraFGAPermissions.WORKFLOWS_READ
        );
        const accessibleSet = new Set(accessible.map((w) => w.id));
        for (const id of Object.keys(_workflows)) {
          if (!accessibleSet.has(id)) {
            delete _workflows[id];
          }
        }
      }
      return _workflows;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting workflows");
    }
  })
});
var GET_WORKFLOW_BY_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/workflows/:workflowId",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  responseSchema: chunkPTPMBE6M_cjs.workflowInfoSchema,
  summary: "Get workflow by ID",
  description: "Returns details for a specific workflow",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: (async ({ mastra, workflowId }) => {
    try {
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      return chunkDRDVJ35H_cjs.getWorkflowInfo(workflow);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting workflow");
    }
  })
});
var LIST_WORKFLOW_RUNS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/workflows/:workflowId/runs",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkPTPMBE6M_cjs.listWorkflowRunsQuerySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowRunsResponseSchema,
  summary: "List workflow runs",
  description: "Returns a paginated list of execution runs for the specified workflow",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({
    mastra,
    workflowId,
    fromDate,
    toDate,
    page,
    perPage,
    limit,
    offset,
    resourceId,
    status,
    requestContext
  }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      let finalPage = page;
      let finalPerPage = perPage;
      if (finalPerPage === void 0 && limit !== void 0) {
        finalPerPage = limit;
      }
      if (finalPage === void 0 && offset !== void 0 && finalPerPage !== void 0 && finalPerPage > 0) {
        finalPage = Math.floor(offset / finalPerPage);
      }
      if (finalPerPage !== void 0 && (typeof finalPerPage !== "number" || !Number.isInteger(finalPerPage) || finalPerPage <= 0)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "perPage must be a positive integer" });
      }
      if (finalPage !== void 0 && (!Number.isInteger(finalPage) || finalPage < 0)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "page must be a non-negative integer" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const workflowRuns = await workflow.listWorkflowRuns({
        fromDate: fromDate ? typeof fromDate === "string" ? new Date(fromDate) : fromDate : void 0,
        toDate: toDate ? typeof toDate === "string" ? new Date(toDate) : toDate : void 0,
        perPage: finalPerPage,
        page: finalPage,
        resourceId: effectiveResourceId,
        status
      }) || {
        runs: [],
        total: 0
      };
      return workflowRuns;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting workflow runs");
    }
  }
});
var GET_WORKFLOW_RUN_BY_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/workflows/:workflowId/runs/:runId",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowRunPathParams,
  queryParamSchema: chunkPTPMBE6M_cjs.workflowRunResultQuerySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowRunResultSchema,
  summary: "Get workflow run by ID",
  description: "Returns a workflow run with metadata and processed execution state. Use the fields query parameter to reduce payload size by requesting only specific fields (e.g., ?fields=status,result,metadata)",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, fields, withNestedWorkflows, requestContext }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const fieldList = fields ? fields.split(",").map((f) => f.trim()) : void 0;
      const run = await workflow.getWorkflowRunById(runId, {
        withNestedWorkflows: withNestedWorkflows !== "false",
        // Default to true unless explicitly 'false'
        fields: fieldList
      });
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      return run;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting workflow run");
    }
  }
});
var DELETE_WORKFLOW_RUN_BY_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "DELETE",
  path: "/workflows/:workflowId/runs/:runId",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowRunPathParams,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Delete workflow run by ID",
  description: "Deletes a specific workflow run by ID",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      await workflow.deleteWorkflowRunById(runId);
      return { message: "Workflow run deleted" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error deleting workflow run");
    }
  }
});
var CREATE_WORKFLOW_RUN_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/create-run",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.optionalRunIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.createWorkflowRunBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.createWorkflowRunResponseSchema,
  summary: "Create workflow run",
  description: "Creates a new workflow execution instance with an optional custom run ID",
  tags: ["Workflows"],
  requiresAuth: true,
  // Creating a run is part of the execute flow (Studio/UI calls this before
  // starting/streaming a workflow), so allow either permission. `write` is kept
  // for back-compat with roles that already grant it.
  requiresPermission: ["workflows:write", "workflows:execute"],
  handler: async ({ mastra, workflowId, runId, resourceId, disableScorers, requestContext }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.createRun({ runId, resourceId: effectiveResourceId, disableScorers });
      return { runId: run.runId };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error creating workflow run");
    }
  }
});
var STREAM_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/stream",
  responseType: "stream",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.streamWorkflowBodySchema,
  summary: "Stream workflow execution",
  description: "Executes a workflow and streams the results in real-time",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to stream workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const serverCache = mastra.getServerCache();
      const run = await workflow.createRun({ runId, resourceId: effectiveResourceId });
      const result = run.stream({ ...params, requestContext });
      if (serverCache) {
        const { transform } = stream.createCachingTransformStream({
          cache: serverCache,
          cacheKey: runId
        });
        return result.fullStream.pipeThrough(transform);
      }
      return result.fullStream;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error streaming workflow");
    }
  }
});
var RESUME_STREAM_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume-stream",
  responseType: "stream",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.resumeBodySchema,
  responseSchema: chunkZQ4GVMYG_cjs.streamResponseSchema,
  summary: "Resume workflow stream",
  description: "Resumes a suspended workflow execution and continues streaming results",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const serverCache = mastra.getServerCache();
      const resumeResult = _run.resumeStream({ ...params, requestContext });
      if (serverCache) {
        const { transform } = stream.createCachingTransformStream({
          cache: serverCache,
          cacheKey: runId
        });
        return resumeResult.fullStream.pipeThrough(transform);
      }
      return resumeResult.fullStream;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error resuming workflow");
    }
  }
});
var START_ASYNC_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/start-async",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.optionalRunIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.startAsyncWorkflowBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowExecutionResultSchema,
  summary: "Start workflow asynchronously",
  description: "Starts a workflow execution asynchronously without streaming results",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const _run = await workflow.createRun({ runId, resourceId: effectiveResourceId });
      const result = await _run.start({ ...params, requestContext });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error starting async workflow");
    }
  }
});
var START_WORKFLOW_RUN_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/start",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.startAsyncWorkflowBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Start specific workflow run",
  description: "Starts execution of a specific workflow run by ID",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to start run" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      void _run.start({
        ...params,
        requestContext
      });
      return { message: "Workflow run started" };
    } catch (e) {
      return chunkZ7LCIYK7_cjs.handleError(e, "Error starting workflow run");
    }
  }
});
var OBSERVE_STREAM_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/observe",
  responseType: "stream",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkPTPMBE6M_cjs.observeWorkflowQuerySchema,
  responseSchema: chunkZQ4GVMYG_cjs.streamResponseSchema,
  summary: "Observe workflow stream",
  description: "Observes and streams updates from an already running workflow execution. Supports position-based resume with offset for efficient reconnection.",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, offset, requestContext }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to observe workflow stream" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const serverCache = mastra.getServerCache();
      if (!serverCache) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Server cache not found" });
      }
      const startIndex = offset ?? 0;
      const cachedRunChunks = await serverCache.listFromTo(runId, startIndex);
      const liveStream = _run.observeStream();
      return stream.createReplayStream({
        history: cachedRunChunks,
        liveSource: liveStream
      });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error observing workflow stream");
    }
  }
});
var RESUME_ASYNC_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume-async",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.resumeBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowExecutionResultSchema,
  summary: "Resume workflow asynchronously",
  description: "Resumes a suspended workflow execution asynchronously without streaming",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.resume({ ...params, requestContext });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error resuming workflow step");
    }
  }
});
var RESUME_NO_WAIT_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume-no-wait",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.resumeBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.createWorkflowRunResponseSchema,
  summary: "Resume workflow without waiting",
  description: "Resumes a suspended workflow execution without waiting (fire-and-forget) and returns immediately with the runId. The workflow continues executing in the background.",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.resumeAsync({ ...params, requestContext });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error resuming workflow step");
    }
  }
});
var RESUME_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.resumeBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Resume workflow",
  description: "Resumes a suspended workflow execution from a specific step",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      void _run.resume({ ...params, requestContext });
      return { message: "Workflow run resumed" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error resuming workflow");
    }
  }
});
var RESTART_ASYNC_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart-async",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.restartBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowExecutionResultSchema,
  summary: "Restart workflow asynchronously",
  description: "Restarts an active workflow execution asynchronously",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to restart workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.restart({ ...params, requestContext });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error restarting workflow");
    }
  }
});
var RESTART_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.restartBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Restart workflow",
  description: "Restarts an active workflow execution",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to restart workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      void _run.restart({ ...params, requestContext });
      return { message: "Workflow run restarted" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error restarting workflow");
    }
  }
});
var RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart-all-active-workflow-runs-async",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Restart all active workflow runs asynchronously",
  description: "Restarts all active workflow runs asynchronously",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId }) => {
    try {
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      await workflow.restartAllActiveWorkflowRuns();
      return { message: "All active workflow runs restarted" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error restarting workflow");
    }
  }
});
var RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart-all-active-workflow-runs",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Restart all active workflow runs",
  description: "Restarts all active workflow runs",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId }) => {
    try {
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      void workflow.restartAllActiveWorkflowRuns();
      return { message: "All active workflow runs restarted" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error restarting workflow");
    }
  }
});
var TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/time-travel-async",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.timeTravelBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowExecutionResultSchema,
  summary: "Time travel workflow asynchronously",
  description: "Time travels a workflow run asynchronously without streaming",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to time travel workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.timeTravel({ ...params, requestContext });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error time traveling workflow");
    }
  }
});
var TIME_TRAVEL_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/time-travel",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.timeTravelBodySchema,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Time travel workflow",
  description: "Time travels a workflow run, starting from a specific step",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to time travel workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      void _run.timeTravel({ ...params, requestContext });
      return { message: "Workflow run time travel started" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error time traveling workflow");
    }
  }
});
var TIME_TRAVEL_STREAM_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/time-travel-stream",
  responseType: "stream",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.timeTravelBodySchema,
  summary: "Time travel workflow stream",
  description: "Time travels a workflow run, starting from a specific step, and streams the results in real-time",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to time travel workflow stream" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const existingRun = await workflow.getWorkflowRunById(runId);
      if (!existingRun) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(existingRun, effectiveResourceId);
      const serverCache = mastra.getServerCache();
      const run = await workflow.createRun({ runId, resourceId: existingRun.resourceId });
      const result = run.timeTravelStream({ ...params, requestContext });
      if (serverCache) {
        const { transform } = stream.createCachingTransformStream({
          cache: serverCache,
          cacheKey: runId
        });
        return result.fullStream.pipeThrough(transform);
      }
      return result.fullStream;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error time traveling workflow stream");
    }
  }
});
var CANCEL_WORKFLOW_RUN_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/runs/:runId/cancel",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowRunPathParams,
  responseSchema: chunkPTPMBE6M_cjs.workflowControlResponseSchema,
  summary: "Cancel workflow run",
  description: "Cancels an in-progress workflow execution",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to cancel workflow run" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      await _run.cancel();
      return { message: "Workflow run cancelled" };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error canceling workflow run");
    }
  }
});
var STREAM_LEGACY_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/stream-legacy",
  responseType: "stream",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  bodySchema: chunkPTPMBE6M_cjs.streamWorkflowBodySchema,
  responseSchema: chunkZQ4GVMYG_cjs.streamResponseSchema,
  summary: "[DEPRECATED] Stream workflow with legacy format",
  description: "Legacy endpoint for streaming workflow execution. Use /workflows/:workflowId/stream instead.",
  tags: ["Workflows", "Legacy"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, resourceId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const serverCache = mastra.getServerCache();
      const run = await workflow.createRun({ runId, resourceId: effectiveResourceId });
      const result = run.streamLegacy({
        ...params,
        requestContext,
        onChunk: async (chunk) => {
          if (serverCache) {
            const cacheKey = runId;
            await serverCache.listPush(cacheKey, chunk);
          }
        }
      });
      return result.stream;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error executing workflow");
    }
  }
});
var OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/observe-stream-legacy",
  responseType: "stream",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  responseSchema: chunkZQ4GVMYG_cjs.streamResponseSchema,
  summary: "[DEPRECATED] Observe workflow stream with legacy format",
  description: "Legacy endpoint for observing workflow stream. Use /workflows/:workflowId/observe instead.",
  tags: ["Workflows", "Legacy"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext }) => {
    try {
      const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "runId required to observe workflow stream" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Workflow run not found" });
      }
      await chunk42M6Y2OD_cjs.validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const serverCache = mastra.getServerCache();
      if (!serverCache) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Server cache not found" });
      }
      const cachedRunChunks = await serverCache.listFromTo(runId, 0);
      const result = _run.observeStreamLegacy();
      if (!result.stream) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to create observe stream" });
      }
      return stream.createReplayStream({
        history: cachedRunChunks,
        liveSource: result.stream
      });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error observing workflow stream");
    }
  }
});
var stepExecutionBodySchema = v4.z.object({
  stepId: v4.z.string(),
  executionPath: v4.z.array(v4.z.number().int().nonnegative()),
  stepResults: v4.z.record(v4.z.string(), v4.z.any()),
  state: v4.z.record(v4.z.string(), v4.z.any()),
  requestContext: v4.z.record(v4.z.string(), v4.z.any()),
  input: v4.z.any().optional(),
  resumeData: v4.z.any().optional(),
  retryCount: v4.z.number().int().nonnegative().optional(),
  foreachIdx: v4.z.number().int().nonnegative().optional(),
  format: v4.z.enum(["legacy", "vnext"]).optional(),
  perStep: v4.z.boolean().optional(),
  validateInputs: v4.z.boolean().optional()
});
var strategyByMastra = /* @__PURE__ */ new WeakMap();
async function getStepStrategy(mastra) {
  let cached = strategyByMastra.get(mastra);
  if (!cached) {
    const { InProcessStrategy } = await import('@mastra/core/worker');
    cached = new InProcessStrategy({ mastra });
    strategyByMastra.set(mastra, cached);
  }
  return cached;
}
var stepExecutionResponseSchema = v4.z.any();
var EXECUTE_WORKFLOW_STEP_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/:workflowId/runs/:runId/steps/execute",
  responseType: "json",
  pathParamSchema: chunkPTPMBE6M_cjs.workflowRunPathParams,
  bodySchema: stepExecutionBodySchema,
  responseSchema: stepExecutionResponseSchema,
  summary: "Execute a workflow step",
  description: "Internal endpoint used by standalone OrchestrationWorker instances to execute workflow steps remotely via HttpRemoteStrategy.",
  tags: ["Workflows", "Worker"],
  requiresAuth: true,
  handler: (async ({ mastra, workflowId, runId, ...body }) => {
    try {
      const strategy = await getStepStrategy(mastra);
      const result = await strategy.executeStep({
        workflowId,
        runId,
        stepId: body.stepId,
        executionPath: body.executionPath,
        stepResults: body.stepResults,
        state: body.state,
        requestContext: body.requestContext,
        input: body.input,
        resumeData: body.resumeData,
        retryCount: body.retryCount,
        foreachIdx: body.foreachIdx,
        format: body.format,
        perStep: body.perStep,
        validateInputs: body.validateInputs
      });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error executing workflow step");
    }
  })
});
var workflowEventSchema = v4.z.object({
  id: v4.z.string(),
  type: v4.z.string(),
  data: v4.z.unknown(),
  runId: v4.z.string(),
  createdAt: v4.z.string(),
  index: v4.z.number().optional(),
  deliveryAttempt: v4.z.number().optional()
});
var receiveWorkflowEventBodySchema = v4.z.object({
  event: workflowEventSchema.passthrough()
});
var receiveWorkflowEventResponseSchema = v4.z.object({
  ok: v4.z.boolean(),
  retry: v4.z.boolean().optional()
});
var RECEIVE_WORKFLOW_EVENT_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/workflows/events",
  responseType: "json",
  bodySchema: receiveWorkflowEventBodySchema,
  responseSchema: receiveWorkflowEventResponseSchema,
  summary: "Receive a workflow event from a push-mode broker",
  description: "Push-mode entry point for workflow events. Brokers (GCP Pub/Sub push, SNS, EventBridge) POST each event here; Mastra processes it through the same pipeline as pull-mode workers.",
  tags: ["Workflows", "Worker"],
  requiresAuth: true,
  // Broker push endpoint: it advances runtime state rather than editing
  // definitions, so `workflows:execute` is the more accurate fit. `write` is
  // kept for back-compat with service principals that already grant it.
  requiresPermission: ["workflows:write", "workflows:execute"],
  handler: (async ({ mastra, event }) => {
    try {
      const rawCreatedAt = event.createdAt;
      const createdAt = rawCreatedAt instanceof Date ? rawCreatedAt : new Date(rawCreatedAt);
      if (Number.isNaN(createdAt.getTime())) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Invalid createdAt" });
      }
      return await mastra.handleWorkflowEvent({ ...event, createdAt });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error receiving workflow event");
    }
  })
});

exports.CANCEL_WORKFLOW_RUN_ROUTE = CANCEL_WORKFLOW_RUN_ROUTE;
exports.CREATE_WORKFLOW_RUN_ROUTE = CREATE_WORKFLOW_RUN_ROUTE;
exports.DELETE_WORKFLOW_RUN_BY_ID_ROUTE = DELETE_WORKFLOW_RUN_BY_ID_ROUTE;
exports.EXECUTE_WORKFLOW_STEP_ROUTE = EXECUTE_WORKFLOW_STEP_ROUTE;
exports.GET_WORKFLOW_BY_ID_ROUTE = GET_WORKFLOW_BY_ID_ROUTE;
exports.GET_WORKFLOW_RUN_BY_ID_ROUTE = GET_WORKFLOW_RUN_BY_ID_ROUTE;
exports.LIST_WORKFLOWS_ROUTE = LIST_WORKFLOWS_ROUTE;
exports.LIST_WORKFLOW_RUNS_ROUTE = LIST_WORKFLOW_RUNS_ROUTE;
exports.OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE = OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE;
exports.OBSERVE_STREAM_WORKFLOW_ROUTE = OBSERVE_STREAM_WORKFLOW_ROUTE;
exports.RECEIVE_WORKFLOW_EVENT_ROUTE = RECEIVE_WORKFLOW_EVENT_ROUTE;
exports.RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE = RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE;
exports.RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE = RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE;
exports.RESTART_ASYNC_WORKFLOW_ROUTE = RESTART_ASYNC_WORKFLOW_ROUTE;
exports.RESTART_WORKFLOW_ROUTE = RESTART_WORKFLOW_ROUTE;
exports.RESUME_ASYNC_WORKFLOW_ROUTE = RESUME_ASYNC_WORKFLOW_ROUTE;
exports.RESUME_NO_WAIT_WORKFLOW_ROUTE = RESUME_NO_WAIT_WORKFLOW_ROUTE;
exports.RESUME_STREAM_WORKFLOW_ROUTE = RESUME_STREAM_WORKFLOW_ROUTE;
exports.RESUME_WORKFLOW_ROUTE = RESUME_WORKFLOW_ROUTE;
exports.START_ASYNC_WORKFLOW_ROUTE = START_ASYNC_WORKFLOW_ROUTE;
exports.START_WORKFLOW_RUN_ROUTE = START_WORKFLOW_RUN_ROUTE;
exports.STREAM_LEGACY_WORKFLOW_ROUTE = STREAM_LEGACY_WORKFLOW_ROUTE;
exports.STREAM_WORKFLOW_ROUTE = STREAM_WORKFLOW_ROUTE;
exports.TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE = TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE;
exports.TIME_TRAVEL_STREAM_WORKFLOW_ROUTE = TIME_TRAVEL_STREAM_WORKFLOW_ROUTE;
exports.TIME_TRAVEL_WORKFLOW_ROUTE = TIME_TRAVEL_WORKFLOW_ROUTE;
exports.workflows_exports = workflows_exports;
//# sourceMappingURL=chunk-RJPRSDIS.cjs.map
//# sourceMappingURL=chunk-RJPRSDIS.cjs.map