import { listWorkflowsResponseSchema, workflowInfoSchema, workflowIdPathParams, workflowRunsResponseSchema, listWorkflowRunsQuerySchema, workflowRunResultSchema, workflowRunResultQuerySchema, workflowRunPathParams, workflowControlResponseSchema, createWorkflowRunResponseSchema, createWorkflowRunBodySchema, streamWorkflowBodySchema, resumeBodySchema, workflowExecutionResultSchema, startAsyncWorkflowBodySchema, observeWorkflowQuerySchema, restartBodySchema, timeTravelBodySchema } from './chunk-K4HCNNHA.js';
import { streamResponseSchema } from './chunk-R3KUPFCO.js';
import { MastraFGAPermissions, getEffectiveResourceId, validateRunOwnership } from './chunk-JBSUT5XF.js';
import { optionalRunIdSchema, runIdSchema } from './chunk-2YY3EMMS.js';
import { getWorkflowInfo, WorkflowRegistry } from './chunk-QIQWHDPH.js';
import { handleError } from './chunk-7ZWJX3AN.js';
import { createRoute } from './chunk-PIKPS6Q6.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { createCachingTransformStream, createReplayStream } from '@mastra/core/stream';
import { z } from 'zod/v4';

// src/server/handlers/workflows.ts
var workflows_exports = {};
__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 HTTPException(400, { message: "Workflow ID is required" });
  }
  let workflow;
  workflow = 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 HTTPException(404, { message: "Workflow not found" });
  }
  return { workflow };
}
var LIST_WORKFLOWS_ROUTE = createRoute({
  method: "GET",
  path: "/workflows",
  responseType: "json",
  queryParamSchema: z.object({
    partial: z.string().optional()
  }),
  responseSchema: 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] = 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",
          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 handleError(error, "Error getting workflows");
    }
  })
});
var GET_WORKFLOW_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/workflows/:workflowId",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  responseSchema: 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 HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      return getWorkflowInfo(workflow);
    } catch (error) {
      return handleError(error, "Error getting workflow");
    }
  })
});
var LIST_WORKFLOW_RUNS_ROUTE = createRoute({
  method: "GET",
  path: "/workflows/:workflowId/runs",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: listWorkflowRunsQuerySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new 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 HTTPException(400, { message: "perPage must be a positive integer" });
      }
      if (finalPage !== void 0 && (!Number.isInteger(finalPage) || finalPage < 0)) {
        throw new HTTPException(400, { message: "page must be a non-negative integer" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new 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 handleError(error, "Error getting workflow runs");
    }
  }
});
var GET_WORKFLOW_RUN_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/workflows/:workflowId/runs/:runId",
  responseType: "json",
  pathParamSchema: workflowRunPathParams,
  queryParamSchema: workflowRunResultQuerySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "Run ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new 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 HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      return run;
    } catch (error) {
      return handleError(error, "Error getting workflow run");
    }
  }
});
var DELETE_WORKFLOW_RUN_BY_ID_ROUTE = createRoute({
  method: "DELETE",
  path: "/workflows/:workflowId/runs/:runId",
  responseType: "json",
  pathParamSchema: workflowRunPathParams,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "Run ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      await workflow.deleteWorkflowRunById(runId);
      return { message: "Workflow run deleted" };
    } catch (error) {
      return handleError(error, "Error deleting workflow run");
    }
  }
});
var CREATE_WORKFLOW_RUN_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/create-run",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: optionalRunIdSchema,
  bodySchema: createWorkflowRunBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.createRun({ runId, resourceId: effectiveResourceId, disableScorers });
      return { runId: run.runId };
    } catch (error) {
      return handleError(error, "Error creating workflow run");
    }
  }
});
var STREAM_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/stream",
  responseType: "stream",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to stream workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new 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 } = createCachingTransformStream({
          cache: serverCache,
          cacheKey: runId
        });
        return result.fullStream.pipeThrough(transform);
      }
      return result.fullStream;
    } catch (error) {
      return handleError(error, "Error streaming workflow");
    }
  }
});
var RESUME_STREAM_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume-stream",
  responseType: "stream",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: resumeBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await 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 } = createCachingTransformStream({
          cache: serverCache,
          cacheKey: runId
        });
        return resumeResult.fullStream.pipeThrough(transform);
      }
      return resumeResult.fullStream;
    } catch (error) {
      return handleError(error, "Error resuming workflow");
    }
  }
});
var START_ASYNC_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/start-async",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: optionalRunIdSchema,
  bodySchema: startAsyncWorkflowBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new 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 handleError(error, "Error starting async workflow");
    }
  }
});
var START_WORKFLOW_RUN_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/start",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: startAsyncWorkflowBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to start run" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await 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 handleError(e, "Error starting workflow run");
    }
  }
});
var OBSERVE_STREAM_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/observe",
  responseType: "stream",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: observeWorkflowQuerySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to observe workflow stream" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const serverCache = mastra.getServerCache();
      if (!serverCache) {
        throw new HTTPException(500, { message: "Server cache not found" });
      }
      const startIndex = offset ?? 0;
      const cachedRunChunks = await serverCache.listFromTo(runId, startIndex);
      const liveStream = _run.observeStream();
      return createReplayStream({
        history: cachedRunChunks,
        liveSource: liveStream
      });
    } catch (error) {
      return handleError(error, "Error observing workflow stream");
    }
  }
});
var RESUME_ASYNC_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume-async",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: resumeBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.resume({ ...params, requestContext });
      return result;
    } catch (error) {
      return handleError(error, "Error resuming workflow step");
    }
  }
});
var RESUME_NO_WAIT_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume-no-wait",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: resumeBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.resumeAsync({ ...params, requestContext });
      return result;
    } catch (error) {
      return handleError(error, "Error resuming workflow step");
    }
  }
});
var RESUME_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/resume",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: resumeBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await 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 handleError(error, "Error resuming workflow");
    }
  }
});
var RESTART_ASYNC_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart-async",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: restartBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to restart workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.restart({ ...params, requestContext });
      return result;
    } catch (error) {
      return handleError(error, "Error restarting workflow");
    }
  }
});
var RESTART_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: restartBodySchema,
  responseSchema: workflowControlResponseSchema,
  summary: "Restart workflow",
  description: "Restarts an active workflow execution",
  tags: ["Workflows"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, runId, requestContext, ...params }) => {
    try {
      const effectiveResourceId = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to restart workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await 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 handleError(error, "Error restarting workflow");
    }
  }
});
var RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ASYNC_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart-all-active-workflow-runs-async",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  responseSchema: 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 HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      await workflow.restartAllActiveWorkflowRuns();
      return { message: "All active workflow runs restarted" };
    } catch (error) {
      return handleError(error, "Error restarting workflow");
    }
  }
});
var RESTART_ALL_ACTIVE_WORKFLOW_RUNS_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/restart-all-active-workflow-runs",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  responseSchema: 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 HTTPException(400, { message: "Workflow ID is required" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      void workflow.restartAllActiveWorkflowRuns();
      return { message: "All active workflow runs restarted" };
    } catch (error) {
      return handleError(error, "Error restarting workflow");
    }
  }
});
var TIME_TRAVEL_ASYNC_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/time-travel-async",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: timeTravelBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to time travel workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const result = await _run.timeTravel({ ...params, requestContext });
      return result;
    } catch (error) {
      return handleError(error, "Error time traveling workflow");
    }
  }
});
var TIME_TRAVEL_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/time-travel",
  responseType: "json",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: timeTravelBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to time travel workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await 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 handleError(error, "Error time traveling workflow");
    }
  }
});
var TIME_TRAVEL_STREAM_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/time-travel-stream",
  responseType: "stream",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to time travel workflow stream" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const existingRun = await workflow.getWorkflowRunById(runId);
      if (!existingRun) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await 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 } = createCachingTransformStream({
          cache: serverCache,
          cacheKey: runId
        });
        return result.fullStream.pipeThrough(transform);
      }
      return result.fullStream;
    } catch (error) {
      return handleError(error, "Error time traveling workflow stream");
    }
  }
});
var CANCEL_WORKFLOW_RUN_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/runs/:runId/cancel",
  responseType: "json",
  pathParamSchema: workflowRunPathParams,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to cancel workflow run" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      await _run.cancel();
      return { message: "Workflow run cancelled" };
    } catch (error) {
      return handleError(error, "Error canceling workflow run");
    }
  }
});
var STREAM_LEGACY_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/stream-legacy",
  responseType: "stream",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  bodySchema: streamWorkflowBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to resume workflow" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new 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 handleError(error, "Error executing workflow");
    }
  }
});
var OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/observe-stream-legacy",
  responseType: "stream",
  pathParamSchema: workflowIdPathParams,
  queryParamSchema: runIdSchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, void 0);
      if (!workflowId) {
        throw new HTTPException(400, { message: "Workflow ID is required" });
      }
      if (!runId) {
        throw new HTTPException(400, { message: "runId required to observe workflow stream" });
      }
      const { workflow } = await listWorkflowsFromSystem({ mastra, workflowId });
      if (!workflow) {
        throw new HTTPException(404, { message: "Workflow not found" });
      }
      const run = await workflow.getWorkflowRunById(runId);
      if (!run) {
        throw new HTTPException(404, { message: "Workflow run not found" });
      }
      await validateRunOwnership(run, effectiveResourceId);
      const _run = await workflow.createRun({ runId, resourceId: run.resourceId });
      const serverCache = mastra.getServerCache();
      if (!serverCache) {
        throw new HTTPException(500, { message: "Server cache not found" });
      }
      const cachedRunChunks = await serverCache.listFromTo(runId, 0);
      const result = _run.observeStreamLegacy();
      if (!result.stream) {
        throw new HTTPException(500, { message: "Failed to create observe stream" });
      }
      return createReplayStream({
        history: cachedRunChunks,
        liveSource: result.stream
      });
    } catch (error) {
      return handleError(error, "Error observing workflow stream");
    }
  }
});
var stepExecutionBodySchema = z.object({
  stepId: z.string(),
  executionPath: z.array(z.number().int().nonnegative()),
  stepResults: z.record(z.string(), z.any()),
  state: z.record(z.string(), z.any()),
  requestContext: z.record(z.string(), z.any()),
  input: z.any().optional(),
  resumeData: z.any().optional(),
  retryCount: z.number().int().nonnegative().optional(),
  foreachIdx: z.number().int().nonnegative().optional(),
  format: z.enum(["legacy", "vnext"]).optional(),
  perStep: z.boolean().optional(),
  validateInputs: 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 = z.any();
var EXECUTE_WORKFLOW_STEP_ROUTE = createRoute({
  method: "POST",
  path: "/workflows/:workflowId/runs/:runId/steps/execute",
  responseType: "json",
  pathParamSchema: 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 handleError(error, "Error executing workflow step");
    }
  })
});
var workflowEventSchema = z.object({
  id: z.string(),
  type: z.string(),
  data: z.unknown(),
  runId: z.string(),
  createdAt: z.string(),
  index: z.number().optional(),
  deliveryAttempt: z.number().optional()
});
var receiveWorkflowEventBodySchema = z.object({
  event: workflowEventSchema.passthrough()
});
var receiveWorkflowEventResponseSchema = z.object({
  ok: z.boolean(),
  retry: z.boolean().optional()
});
var RECEIVE_WORKFLOW_EVENT_ROUTE = 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 HTTPException(400, { message: "Invalid createdAt" });
      }
      return await mastra.handleWorkflowEvent({ ...event, createdAt });
    } catch (error) {
      return handleError(error, "Error receiving workflow event");
    }
  })
});

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