import { getWorkflowInfo, WorkflowRegistry } from './chunk-ED6NQBHF.js';
import { streamResponseSchema } from './chunk-LFNP3ACE.js';
import { getEffectiveResourceId, validateRunOwnership } from './chunk-USR6JK77.js';
import { createCombinedPaginationSchema, tracingOptionsSchema, messageResponseSchema, optionalRunIdSchema, runIdSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { TransformStream, ReadableStream } from 'stream/web';
import z, { z as z$1 } from 'zod';

// 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,
  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,
  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_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
});
var workflowRunStatusSchema = z.enum([
  "running",
  "waiting",
  "suspended",
  "success",
  "failed",
  "canceled",
  "pending",
  "bailed",
  "tripwire",
  "paused"
]);
var workflowIdPathParams = z.object({
  workflowId: z.string().describe("Unique identifier for the workflow")
});
var workflowRunPathParams = workflowIdPathParams.extend({
  runId: z.string().describe("Unique identifier for the workflow run")
});
var serializedStepSchema = z.object({
  id: z.string(),
  description: z.string().optional(),
  stateSchema: z.string().optional(),
  inputSchema: z.string().optional(),
  outputSchema: z.string().optional(),
  resumeSchema: z.string().optional(),
  suspendSchema: z.string().optional(),
  component: z.string().optional(),
  isWorkflow: z.boolean().optional()
});
var serializedStepFlowEntrySchema = z.object({
  type: z.enum(["step", "sleep", "sleepUntil", "waitForEvent", "parallel", "conditional", "loop", "foreach"])
});
var workflowInfoSchema = z.object({
  steps: z.record(z.string(), serializedStepSchema),
  allSteps: z.record(z.string(), serializedStepSchema),
  name: z.string().optional(),
  description: z.string().optional(),
  stepGraph: z.array(serializedStepFlowEntrySchema),
  inputSchema: z.string().optional(),
  outputSchema: z.string().optional(),
  stateSchema: z.string().optional(),
  options: z.object({}).optional(),
  isProcessorWorkflow: z.boolean().optional()
});
var listWorkflowsResponseSchema = z.record(z.string(), workflowInfoSchema);
var workflowRunSchema = z.object({
  workflowName: z.string(),
  runId: z.string(),
  snapshot: z.union([z.object({}), z.string()]),
  createdAt: z.date(),
  updatedAt: z.date(),
  resourceId: z.string().optional()
});
var workflowRunsResponseSchema = z.object({
  runs: z.array(workflowRunSchema),
  total: z.number()
});
var listWorkflowRunsQuerySchema = createCombinedPaginationSchema().extend({
  fromDate: z.coerce.date().optional(),
  toDate: z.coerce.date().optional(),
  resourceId: z.string().optional(),
  status: workflowRunStatusSchema.optional()
});
var workflowExecutionBodySchema = z.object({
  resourceId: z.string().optional(),
  inputData: z.unknown().optional(),
  initialState: z.unknown().optional(),
  requestContext: z.record(z.string(), z.unknown()).optional(),
  tracingOptions: tracingOptionsSchema.optional(),
  perStep: z.boolean().optional()
});
var streamLegacyWorkflowBodySchema = workflowExecutionBodySchema;
var streamWorkflowBodySchema = workflowExecutionBodySchema.extend({
  closeOnSuspend: z.boolean().optional()
});
var resumeBodySchema = z.object({
  step: z.union([z.string(), z.array(z.string())]).optional(),
  // Optional - workflow can auto-resume all suspended steps
  resumeData: z.unknown().optional(),
  requestContext: z.record(z.string(), z.unknown()).optional(),
  tracingOptions: tracingOptionsSchema.optional(),
  perStep: z.boolean().optional()
});
var restartBodySchema = z.object({
  requestContext: z.record(z.string(), z.unknown()).optional(),
  tracingOptions: tracingOptionsSchema.optional()
});
var timeTravelBodySchema = z.object({
  inputData: z.unknown().optional(),
  resumeData: z.unknown().optional(),
  initialState: z.unknown().optional(),
  step: z.union([z.string(), z.array(z.string())]),
  context: z.record(z.string(), z.any()).optional(),
  nestedStepsContext: z.record(z.string(), z.record(z.string(), z.any())).optional(),
  requestContext: z.record(z.string(), z.unknown()).optional(),
  tracingOptions: tracingOptionsSchema.optional(),
  perStep: z.boolean().optional()
});
var startAsyncWorkflowBodySchema = workflowExecutionBodySchema;
z.object({
  event: z.string(),
  data: z.unknown()
});
var VALID_WORKFLOW_RESULT_FIELDS = /* @__PURE__ */ new Set([
  "result",
  "error",
  "payload",
  "steps",
  "activeStepsPath",
  "serializedStepGraph"
]);
var WORKFLOW_RESULT_FIELDS_ERROR = "Invalid field name. Available fields: result, error, payload, steps, activeStepsPath, serializedStepGraph";
var createFieldsValidator = (description) => z.string().optional().refine(
  (value) => {
    if (!value) return true;
    const requestedFields = value.split(",").map((f) => f.trim());
    return requestedFields.every((field) => VALID_WORKFLOW_RESULT_FIELDS.has(field));
  },
  { message: WORKFLOW_RESULT_FIELDS_ERROR }
).describe(description);
var withNestedWorkflowsField = z.enum(["true", "false"]).optional().describe("Whether to include nested workflow data in steps. Defaults to true. Set to false for better performance.");
var workflowExecutionResultSchema = z.object({
  status: workflowRunStatusSchema.optional(),
  result: z.unknown().optional(),
  error: z.unknown().optional(),
  payload: z.unknown().optional(),
  initialState: z.unknown().optional(),
  steps: z.record(z.string(), z.any()).optional(),
  activeStepsPath: z.record(z.string(), z.array(z.number())).optional(),
  serializedStepGraph: z.array(serializedStepFlowEntrySchema).optional()
});
var workflowRunResultQuerySchema = z.object({
  fields: createFieldsValidator(
    "Comma-separated list of fields to return. Available fields: result, error, payload, steps, activeStepsPath, serializedStepGraph. Metadata fields (runId, workflowName, resourceId, createdAt, updatedAt) and status are always included."
  ),
  withNestedWorkflows: withNestedWorkflowsField
});
var workflowRunResultSchema = z.object({
  // Metadata - always present
  runId: z.string(),
  workflowName: z.string(),
  resourceId: z.string().optional(),
  createdAt: z.date(),
  updatedAt: z.date(),
  // Execution state
  status: workflowRunStatusSchema,
  initialState: z.record(z.string(), z.any()).optional(),
  result: z.unknown().optional(),
  error: z.unknown().optional(),
  payload: z.unknown().optional(),
  steps: z.record(z.string(), z.any()).optional(),
  // Optional detailed fields
  activeStepsPath: z.record(z.string(), z.array(z.number())).optional(),
  serializedStepGraph: z.array(serializedStepFlowEntrySchema).optional()
});
var workflowControlResponseSchema = messageResponseSchema;
var createWorkflowRunResponseSchema = z.object({
  runId: z.string()
});
var createWorkflowRunBodySchema = z.object({
  resourceId: z.string().optional(),
  disableScorers: z.boolean().optional()
});

// src/server/handlers/workflows.ts
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$1.object({
    partial: z$1.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 }) => {
    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;
      }, {});
      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,
  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 });
      return result.fullStream.pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            if (serverCache) {
              const cacheKey = runId;
              serverCache.listPush(cacheKey, chunk).catch(() => {
              });
            }
            controller.enqueue(chunk);
          }
        })
      );
    } 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 stream = _run.resumeStream({ ...params, requestContext }).fullStream.pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            if (serverCache) {
              const cacheKey = runId;
              serverCache.listPush(cacheKey, chunk).catch(() => {
              });
            }
            controller.enqueue(chunk);
          }
        })
      );
      return stream;
    } 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: runIdSchema,
  responseSchema: streamResponseSchema,
  summary: "Observe workflow stream",
  description: "Observes and streams updates from an already running 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 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 combinedStream = new ReadableStream({
        start(controller) {
          const emitCachedChunks = async () => {
            for (const chunk of cachedRunChunks) {
              controller.enqueue(chunk);
            }
          };
          const liveStream = _run.observeStream();
          const reader = liveStream.getReader();
          const pump = async () => {
            try {
              while (true) {
                const { done, value } = await reader.read();
                if (done) {
                  controller.close();
                  break;
                }
                controller.enqueue(value);
              }
            } catch (error) {
              controller.error(error);
            } finally {
              reader.releaseLock();
            }
          };
          void emitCachedChunks().then(() => {
            void pump();
          }).catch((error) => {
            controller.error(error);
          });
        }
      });
      return combinedStream;
    } 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_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 });
      return result.fullStream.pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            if (serverCache) {
              const cacheKey = runId;
              serverCache.listPush(cacheKey, chunk).catch(() => {
              });
            }
            controller.enqueue(chunk);
          }
        })
      );
    } 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 transformStream = new TransformStream();
      const writer = transformStream.writable.getWriter();
      const cachedRunChunks = await serverCache.listFromTo(runId, 0);
      for (const chunk of cachedRunChunks) {
        await writer.write(chunk);
      }
      writer.releaseLock();
      const result = _run.observeStreamLegacy();
      return result.stream?.pipeThrough(transformStream);
    } catch (error) {
      return handleError(error, "Error observing workflow stream");
    }
  }
});

export { CANCEL_WORKFLOW_RUN_ROUTE, CREATE_WORKFLOW_RUN_ROUTE, DELETE_WORKFLOW_RUN_BY_ID_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, 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_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, createWorkflowRunResponseSchema, listWorkflowRunsQuerySchema, listWorkflowsResponseSchema, resumeBodySchema, startAsyncWorkflowBodySchema, streamLegacyWorkflowBodySchema, streamWorkflowBodySchema, workflowControlResponseSchema, workflowExecutionResultSchema, workflowInfoSchema, workflowRunResultQuerySchema, workflowRunResultSchema, workflowRunsResponseSchema, workflows_exports };
//# sourceMappingURL=chunk-ES5OZHJ4.js.map
//# sourceMappingURL=chunk-ES5OZHJ4.js.map