'use strict';

var chunkWOMVBFIP_cjs = require('./chunk-WOMVBFIP.cjs');
var chunkY2BKW5ND_cjs = require('./chunk-Y2BKW5ND.cjs');
var chunk6P7P7Y5U_cjs = require('./chunk-6P7P7Y5U.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var agent = require('@mastra/core/agent');
var processors = require('@mastra/core/processors');

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 (processors.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 = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/processors",
  responseType: "json",
  responseSchema: chunkWOMVBFIP_cjs.listProcessorsResponseSchema,
  summary: "List all processors",
  description: "Returns a list of all available individual processors",
  tags: ["Processors"],
  requiresAuth: true,
  handler: async ({ mastra }) => {
    try {
      const processors$1 = mastra.listProcessors() || {};
      const processorConfigurations = mastra.listProcessorConfigurations();
      const result = {};
      for (const [processorKey, processorEntry] of Object.entries(processors$1)) {
        const processor = processorEntry;
        const processorId = processor.id || processorKey;
        const isWorkflow = processors.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 chunkY2BKW5ND_cjs.handleError(error, "Error getting processors");
    }
  }
});
var GET_PROCESSOR_BY_ID_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/processors/:processorId",
  responseType: "json",
  pathParamSchema: chunkWOMVBFIP_cjs.processorIdPathParams,
  responseSchema: chunkWOMVBFIP_cjs.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 chunk64ITUOXI_cjs.HTTPException(404, { message: "Processor not found" });
      }
      const isWorkflow = processors.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 chunkY2BKW5ND_cjs.handleError(error, "Error getting processor");
    }
  }
});
var EXECUTE_PROCESSOR_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "POST",
  path: "/processors/:processorId/execute",
  responseType: "json",
  pathParamSchema: chunkWOMVBFIP_cjs.processorIdPathParams,
  bodySchema: chunkWOMVBFIP_cjs.executeProcessorBodySchema,
  responseSchema: chunkWOMVBFIP_cjs.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 chunk64ITUOXI_cjs.HTTPException(400, { message: "Processor ID is required" });
      }
      if (!phase) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Phase is required" });
      }
      if (!messages || !Array.isArray(messages)) {
        throw new chunk64ITUOXI_cjs.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 chunk64ITUOXI_cjs.HTTPException(404, { message: "Processor not found" });
      }
      const messageList = new agent.MessageList();
      messageList.add(messages, "input");
      if (processors.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":
              inputData = {
                ...inputData,
                state: {},
                result: {
                  text: extractTextFromMessages(messages),
                  usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
                  finishReason: "unknown",
                  steps: []
                }
              };
              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 chunk64ITUOXI_cjs.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 agent.MessageList) {
              outputMessages = output.messageList.get.all.db();
            }
          }
          return {
            success: true,
            phase,
            messages: outputMessages,
            messageList: {
              messages: outputMessages
            }
          };
        } catch (error) {
          if (error instanceof chunk64ITUOXI_cjs.HTTPException) {
            throw error;
          }
          throw new chunk64ITUOXI_cjs.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,
        state: {}
      };
      try {
        let result;
        switch (phase) {
          case "input":
            if (!processor.processInput) {
              throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Processor does not support input phase" });
            }
            result = await processor.processInput({
              ...baseContext,
              systemMessages: []
            });
            break;
          case "inputStep":
            if (!processor.processInputStep) {
              throw new chunk64ITUOXI_cjs.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 chunk64ITUOXI_cjs.HTTPException(400, { message: "Processor does not support outputResult phase" });
            }
            result = await processor.processOutputResult({
              ...baseContext,
              state: {},
              result: {
                text: extractTextFromMessages(messages),
                usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
                finishReason: "unknown",
                steps: []
              }
            });
            break;
          case "outputStep":
            if (!processor.processOutputStep) {
              throw new chunk64ITUOXI_cjs.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 chunk64ITUOXI_cjs.HTTPException(400, {
              message: "outputStream phase cannot be executed directly. Use streaming instead."
            });
          default:
            throw new chunk64ITUOXI_cjs.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 chunkY2BKW5ND_cjs.handleError(error, "Error executing processor");
    }
  }
});

exports.EXECUTE_PROCESSOR_ROUTE = EXECUTE_PROCESSOR_ROUTE;
exports.GET_PROCESSOR_BY_ID_ROUTE = GET_PROCESSOR_BY_ID_ROUTE;
exports.LIST_PROCESSORS_ROUTE = LIST_PROCESSORS_ROUTE;
//# sourceMappingURL=chunk-JWCTCYDF.cjs.map
//# sourceMappingURL=chunk-JWCTCYDF.cjs.map