import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { MessageList } from '@mastra/core/agent';
import { isProcessorWorkflow } from '@mastra/core/processors';
import z from 'zod';

var processorIdPathParams = z.object({
  processorId: z.string().describe("Unique identifier for the processor")
});
var processorConfigurationSchema = z.object({
  agentId: z.string(),
  agentName: z.string(),
  type: z.enum(["input", "output"])
});
var processorListConfigurationSchema = z.object({
  agentId: z.string(),
  type: z.enum(["input", "output"])
});
var serializedProcessorSchema = z.object({
  id: z.string(),
  name: z.string().optional(),
  description: z.string().optional(),
  phases: z.array(z.enum(["input", "inputStep", "outputStream", "outputResult", "outputStep"])),
  agentIds: z.array(z.string()),
  configurations: z.array(processorListConfigurationSchema),
  isWorkflow: z.boolean()
});
var serializedProcessorDetailSchema = z.object({
  id: z.string(),
  name: z.string().optional(),
  description: z.string().optional(),
  phases: z.array(z.enum(["input", "inputStep", "outputStream", "outputResult", "outputStep"])),
  configurations: z.array(processorConfigurationSchema),
  isWorkflow: z.boolean()
});
var listProcessorsResponseSchema = z.record(z.string(), serializedProcessorSchema);
var messageContentSchema = z.object({
  format: z.literal(2).optional(),
  parts: z.array(z.any()).optional(),
  content: z.string().optional()
}).passthrough();
var processorMessageSchema = z.object({
  id: z.string(),
  role: z.enum(["user", "assistant", "system", "tool"]),
  createdAt: z.coerce.date().optional(),
  content: z.union([messageContentSchema, z.string()])
}).passthrough();
var executeProcessorBodySchema = z.object({
  phase: z.enum(["input", "inputStep", "outputStream", "outputResult", "outputStep"]),
  messages: z.array(processorMessageSchema),
  agentId: z.string().optional(),
  requestContext: z.record(z.string(), z.any()).optional()
});
var tripwireSchema = z.object({
  triggered: z.boolean(),
  reason: z.string().optional(),
  metadata: z.any().optional()
});
var executeProcessorResponseSchema = z.object({
  success: z.boolean(),
  phase: z.string(),
  messages: z.array(processorMessageSchema).optional(),
  messageList: z.object({
    messages: z.array(processorMessageSchema)
  }).optional(),
  tripwire: tripwireSchema.optional(),
  error: z.string().optional()
});

// src/server/handlers/processors.ts
function extractTextFromMessages(messages) {
  if (!messages || !Array.isArray(messages) || messages.length === 0) {
    return "";
  }
  const firstMessage = messages[0];
  if (firstMessage?.content?.parts) {
    const textParts = firstMessage.content.parts.filter((part) => part?.type === "text").map((part) => part?.text || "");
    return textParts.join("");
  }
  return "";
}
function detectProcessorPhases(processor) {
  if (isProcessorWorkflow(processor)) {
    return ["input", "inputStep", "outputStream", "outputResult", "outputStep"];
  }
  const phases = [];
  if (typeof processor.processInput === "function") {
    phases.push("input");
  }
  if (typeof processor.processInputStep === "function") {
    phases.push("inputStep");
  }
  if (typeof processor.processOutputStream === "function") {
    phases.push("outputStream");
  }
  if (typeof processor.processOutputResult === "function") {
    phases.push("outputResult");
  }
  if (typeof processor.processOutputStep === "function") {
    phases.push("outputStep");
  }
  return phases;
}
var LIST_PROCESSORS_ROUTE = createRoute({
  method: "GET",
  path: "/processors",
  responseType: "json",
  responseSchema: listProcessorsResponseSchema,
  summary: "List all processors",
  description: "Returns a list of all available individual processors",
  tags: ["Processors"],
  requiresAuth: true,
  handler: async ({ mastra }) => {
    try {
      const processors = mastra.listProcessors() || {};
      const processorConfigurations = mastra.listProcessorConfigurations();
      const result = {};
      for (const [processorKey, processorEntry] of Object.entries(processors)) {
        const processor = processorEntry;
        const processorId = processor.id || processorKey;
        const isWorkflow = isProcessorWorkflow(processor);
        const phases = detectProcessorPhases(processor);
        const configs = processorConfigurations.get(processorId) || [];
        const agentIds = [...new Set(configs.map((c) => c.agentId))];
        const configurations = configs.map((c) => ({ agentId: c.agentId, type: c.type }));
        result[processorId] = {
          id: processorId,
          name: processor.name || processorId,
          description: processor.description,
          phases,
          agentIds,
          configurations,
          isWorkflow
        };
      }
      return result;
    } catch (error) {
      return handleError(error, "Error getting processors");
    }
  }
});
var GET_PROCESSOR_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/processors/:processorId",
  responseType: "json",
  pathParamSchema: processorIdPathParams,
  responseSchema: serializedProcessorDetailSchema,
  summary: "Get processor by ID",
  description: "Returns details for a specific processor including its phases and configurations",
  tags: ["Processors"],
  requiresAuth: true,
  handler: async ({ mastra, processorId }) => {
    try {
      let processorEntry;
      try {
        processorEntry = mastra.getProcessorById(processorId);
      } catch {
        const processors = mastra.listProcessors() || {};
        processorEntry = processors[processorId];
      }
      if (!processorEntry) {
        throw new HTTPException(404, { message: "Processor not found" });
      }
      const isWorkflow = isProcessorWorkflow(processorEntry);
      const phases = detectProcessorPhases(processorEntry);
      const configs = mastra.getProcessorConfigurations(processorId);
      const agents = mastra.listAgents() || {};
      const configurations = configs.map((c) => ({
        agentId: c.agentId,
        agentName: agents[c.agentId]?.name || c.agentId,
        type: c.type
      }));
      return {
        id: processorEntry.id,
        name: processorEntry.name || processorEntry.id,
        description: processorEntry.description,
        phases,
        configurations,
        isWorkflow
      };
    } catch (error) {
      return handleError(error, "Error getting processor");
    }
  }
});
var EXECUTE_PROCESSOR_ROUTE = createRoute({
  method: "POST",
  path: "/processors/:processorId/execute",
  responseType: "json",
  pathParamSchema: processorIdPathParams,
  bodySchema: executeProcessorBodySchema,
  responseSchema: executeProcessorResponseSchema,
  summary: "Execute processor",
  description: "Executes a specific processor with the provided input data",
  tags: ["Processors"],
  requiresAuth: true,
  handler: async ({ mastra, processorId, ...bodyParams }) => {
    try {
      const { phase, messages } = bodyParams;
      if (!processorId) {
        throw new HTTPException(400, { message: "Processor ID is required" });
      }
      if (!phase) {
        throw new HTTPException(400, { message: "Phase is required" });
      }
      if (!messages || !Array.isArray(messages)) {
        throw new HTTPException(400, { message: "Messages array is required" });
      }
      let processor;
      try {
        processor = mastra.getProcessorById(processorId);
      } catch {
        const processors = mastra.listProcessors() || {};
        processor = processors[processorId];
      }
      if (!processor) {
        throw new HTTPException(404, { message: "Processor not found" });
      }
      const messageList = new MessageList();
      messageList.add(messages, "input");
      if (isProcessorWorkflow(processor)) {
        try {
          const baseInputData = {
            phase,
            messages: messageList.get.all.db(),
            messageList,
            retryCount: 0
          };
          let inputData = baseInputData;
          switch (phase) {
            case "input":
              inputData = {
                ...inputData,
                systemMessages: []
              };
              break;
            case "inputStep":
              inputData = {
                ...inputData,
                stepNumber: 0,
                systemMessages: [],
                steps: [],
                model: "",
                tools: {},
                toolChoice: void 0,
                activeTools: [],
                providerOptions: void 0,
                modelSettings: void 0,
                structuredOutput: void 0
              };
              break;
            case "outputResult":
              break;
            case "outputStep":
              inputData = {
                ...inputData,
                stepNumber: 0,
                systemMessages: [],
                steps: [],
                finishReason: "stop",
                toolCalls: [],
                text: extractTextFromMessages(messages)
              };
              break;
            case "outputStream":
              inputData = {
                ...inputData,
                part: null,
                streamParts: [],
                state: {}
              };
              break;
          }
          const run = await processor.createRun();
          const result = await run.start({
            inputData
          });
          if (result.status === "tripwire") {
            return {
              success: false,
              phase,
              tripwire: {
                triggered: true,
                reason: result.tripwire.reason || `Tripwire triggered in workflow ${processor.id}`,
                metadata: result.tripwire.metadata
              },
              messages,
              messageList: {
                messages
              }
            };
          }
          if (result.status !== "success") {
            throw new HTTPException(500, {
              message: `Processor workflow ${processor.id} failed with status: ${result.status}`
            });
          }
          const output = result.result;
          let outputMessages = messages;
          if (output && typeof output === "object") {
            if ("messages" in output && Array.isArray(output.messages)) {
              outputMessages = output.messages;
            } else if ("messageList" in output && output.messageList instanceof MessageList) {
              outputMessages = output.messageList.get.all.db();
            }
          }
          return {
            success: true,
            phase,
            messages: outputMessages,
            messageList: {
              messages: outputMessages
            }
          };
        } catch (error) {
          if (error instanceof HTTPException) {
            throw error;
          }
          throw new HTTPException(500, {
            message: `Error executing processor workflow: ${error.message}`
          });
        }
      }
      let tripwireTriggered = false;
      let tripwireReason;
      let tripwireMetadata;
      const abort = (reason, options) => {
        tripwireTriggered = true;
        tripwireReason = reason;
        tripwireMetadata = options?.metadata;
        throw new Error(`TRIPWIRE:${reason || "Processor aborted"}`);
      };
      const baseContext = {
        abort,
        retryCount: 0,
        messages: messageList.get.all.db(),
        messageList
      };
      try {
        let result;
        switch (phase) {
          case "input":
            if (!processor.processInput) {
              throw new HTTPException(400, { message: "Processor does not support input phase" });
            }
            result = await processor.processInput({
              ...baseContext,
              systemMessages: []
            });
            break;
          case "inputStep":
            if (!processor.processInputStep) {
              throw new HTTPException(400, { message: "Processor does not support inputStep phase" });
            }
            result = await processor.processInputStep({
              ...baseContext,
              systemMessages: [],
              stepNumber: 0,
              steps: [],
              // Pass empty/default values for all inputStep fields
              model: "",
              tools: {},
              toolChoice: void 0,
              activeTools: [],
              providerOptions: void 0,
              modelSettings: void 0,
              structuredOutput: void 0
            });
            break;
          case "outputResult":
            if (!processor.processOutputResult) {
              throw new HTTPException(400, { message: "Processor does not support outputResult phase" });
            }
            result = await processor.processOutputResult(baseContext);
            break;
          case "outputStep":
            if (!processor.processOutputStep) {
              throw new HTTPException(400, { message: "Processor does not support outputStep phase" });
            }
            result = await processor.processOutputStep({
              ...baseContext,
              systemMessages: [],
              stepNumber: 0,
              steps: [],
              finishReason: "stop",
              toolCalls: [],
              text: extractTextFromMessages(messages)
            });
            break;
          case "outputStream":
            throw new HTTPException(400, {
              message: "outputStream phase cannot be executed directly. Use streaming instead."
            });
          default:
            throw new HTTPException(400, { message: `Unknown phase: ${phase}` });
        }
        let outputMessages = messages;
        if (result) {
          if (Array.isArray(result)) {
            outputMessages = result;
          } else if (result.get && result.get.all && typeof result.get.all.db === "function") {
            outputMessages = result.get.all.db();
          } else if (result.messages) {
            outputMessages = result.messages;
          }
        }
        return {
          success: true,
          phase,
          messages: outputMessages,
          messageList: {
            messages: outputMessages
          }
        };
      } catch (error) {
        if (tripwireTriggered || error.message?.startsWith("TRIPWIRE:")) {
          return {
            success: false,
            phase,
            tripwire: {
              triggered: true,
              reason: tripwireReason || error.message?.replace("TRIPWIRE:", ""),
              metadata: tripwireMetadata
            },
            messages,
            messageList: {
              messages
            }
          };
        }
        throw error;
      }
    } catch (error) {
      return handleError(error, "Error executing processor");
    }
  }
});

export { EXECUTE_PROCESSOR_ROUTE, GET_PROCESSOR_BY_ID_ROUTE, LIST_PROCESSORS_ROUTE };
//# sourceMappingURL=chunk-OMOE6NPR.js.map
//# sourceMappingURL=chunk-OMOE6NPR.js.map