"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var buildSteps_exports = {};
__export(buildSteps_exports, {
  buildSteps: () => buildSteps
});
module.exports = __toCommonJS(buildSteps_exports);
var import_messages = require("@langchain/core/messages");
var import_n8n_workflow = require("n8n-workflow");
function extractProviderMetadata(metadata) {
  if (!metadata) return {};
  const thoughtSignature = typeof metadata.google?.thoughtSignature === "string" ? metadata.google.thoughtSignature : void 0;
  const thinkingContent = typeof metadata.anthropic?.thinkingContent === "string" ? metadata.anthropic.thinkingContent : void 0;
  const thinkingType = metadata.anthropic?.thinkingType === "thinking" || metadata.anthropic?.thinkingType === "redacted_thinking" ? metadata.anthropic.thinkingType : void 0;
  const thinkingSignature = typeof metadata.anthropic?.thinkingSignature === "string" ? metadata.anthropic.thinkingSignature : void 0;
  return {
    thoughtSignature,
    thinkingContent,
    thinkingType,
    thinkingSignature
  };
}
function buildAnthropicContentBlocks(thinkingContent, thinkingType, thinkingSignature, toolInput, toolId, toolName) {
  const thinkingBlock = thinkingType === "thinking" ? {
    type: "thinking",
    thinking: thinkingContent,
    signature: thinkingSignature ?? ""
    // Use original signature if available
  } : {
    type: "redacted_thinking",
    data: thinkingContent
  };
  const toolInputData = toolInput.input;
  const toolUseBlock = {
    type: "tool_use",
    id: toolId,
    name: toolName,
    input: toolInputData && typeof toolInputData === "object" ? toolInputData : {}
  };
  return [thinkingBlock, toolUseBlock];
}
function buildMessageContent(providerMetadata, toolInput, toolId, toolName, nodeName) {
  const { thinkingContent, thinkingType, thinkingSignature } = providerMetadata;
  if (thinkingContent && thinkingType) {
    return buildAnthropicContentBlocks(
      thinkingContent,
      thinkingType,
      thinkingSignature,
      toolInput,
      toolId,
      toolName
    );
  }
  return `Calling ${nodeName} with input: ${JSON.stringify(toolInput)}`;
}
function buildSteps(response, itemIndex) {
  const steps = [];
  if (response) {
    const responses = response?.actionResponses ?? [];
    if (response.metadata?.previousRequests) {
      steps.push.apply(steps, response.metadata.previousRequests);
    }
    for (const tool of responses) {
      if (tool.action?.metadata?.itemIndex !== itemIndex) continue;
      const toolInput = {
        ...tool.action.input,
        id: tool.action.id
      };
      if (!toolInput || !tool.data) {
        continue;
      }
      const step = steps.find((step2) => step2.action.toolCallId === toolInput.id);
      if (step) {
        continue;
      }
      const providerMetadata = extractProviderMetadata(tool.action.metadata);
      const toolId = typeof toolInput?.id === "string" ? toolInput.id : "reconstructed_call";
      const toolName = (0, import_n8n_workflow.nodeNameToToolName)(tool.action.nodeName);
      const toolCall = {
        id: toolId,
        name: toolName,
        args: toolInput,
        type: "tool_call",
        additional_kwargs: {
          ...providerMetadata.thoughtSignature && {
            thought_signature: providerMetadata.thoughtSignature
          }
        }
      };
      const messageContent = buildMessageContent(
        providerMetadata,
        toolInput,
        toolId,
        toolName,
        tool.action.nodeName
      );
      const syntheticAIMessage = new import_messages.AIMessage({
        content: messageContent,
        // Note: tool_calls is only used when content is a string
        // When content is an array (thinking mode), tool_use blocks are in the content array
        ...typeof messageContent === "string" && { tool_calls: [toolCall] }
      });
      const toolInputForResult = toolInput.input;
      const aiToolData = tool.data?.data?.ai_tool?.[0]?.map((item) => item?.json);
      let observation;
      if (aiToolData && aiToolData.length > 0) {
        observation = JSON.stringify(aiToolData);
      } else if (tool.data?.error) {
        const errorInfo = {
          error: tool.data.error.message ?? "Unknown error",
          ...tool.data.error.name && { errorType: tool.data.error.name }
        };
        observation = JSON.stringify(errorInfo);
      } else {
        observation = JSON.stringify("");
      }
      const toolResult = {
        action: {
          tool: (0, import_n8n_workflow.nodeNameToToolName)(tool.action.nodeName),
          toolInput: toolInputForResult && typeof toolInputForResult === "object" ? toolInputForResult : {},
          log: toolInput.log || syntheticAIMessage.content,
          messageLog: [syntheticAIMessage],
          toolCallId: toolInput?.id,
          type: toolInput.type || "tool_call"
        },
        observation
      };
      steps.push(toolResult);
    }
  }
  return steps;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildSteps
});
//# sourceMappingURL=buildSteps.js.map