/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tools_exports = {};
__export(tools_exports, {
  toolCallStatusMiddleware: () => toolCallStatusMiddleware,
  toolInteractionMiddleware: () => toolInteractionMiddleware
});
module.exports = __toCommonJS(tools_exports);
var import_langchain = require("langchain");
var import_zod = __toESM(require("zod"));
var import_lodash = __toESM(require("lodash"));
const toolInteractionMiddleware = (aiEmployee, tools) => {
  const interruptOn = {};
  for (const tool of tools) {
    interruptOn[tool.definition.name] = aiEmployee.shouldInterruptToolCall(tool);
  }
  return (0, import_langchain.humanInTheLoopMiddleware)({
    interruptOn
  });
};
const toolCallStatusMiddleware = (aiEmployee) => {
  return (0, import_langchain.createMiddleware)({
    name: "ToolCallStatusMiddleware",
    stateSchema: import_zod.default.object({
      messageId: import_zod.default.coerce.string().optional()
    }),
    wrapToolCall: async (request, handler) => {
      var _a, _b, _c, _d;
      const { runtime, toolCall } = request;
      const { messageId } = request.state;
      const tm = await aiEmployee.getToolCallResult(messageId, request.toolCall.id);
      if (tm.status === "error") {
        (_a = runtime.writer) == null ? void 0 : _a.call(runtime, {
          action: "afterToolCall",
          body: { toolCall, toolCallResult: tm }
        });
        return new import_langchain.ToolMessage({
          tool_call_id: request.toolCall.id,
          status: "error",
          content: tm.content,
          metadata: {
            messageId
          }
        });
      }
      await aiEmployee.updateToolCallPending(messageId, request.toolCall.id);
      (_b = runtime.writer) == null ? void 0 : _b.call(runtime, { action: "beforeToolCall", body: { toolCall } });
      let result;
      try {
        const toolMessage = await handler(request);
        if (toolMessage instanceof import_langchain.ToolMessage) {
          if (import_lodash.default.isObject(toolMessage.content)) {
            result = toolMessage.content;
          } else if (typeof toolMessage.content === "string") {
            try {
              result = JSON.parse(toolMessage.content);
            } catch (e) {
              aiEmployee.logger.warn("tool result parse fail", e);
              result = toolMessage.content;
            }
          } else {
            result = toolMessage.content;
          }
        } else {
          result = toolMessage.toJSON();
        }
        return toolMessage;
      } catch (e) {
        aiEmployee.logger.error(e);
        result = { status: "error", content: e.message };
        (_c = runtime.writer) == null ? void 0 : _c.call(runtime, {
          action: "afterToolCallError",
          body: { toolCall, error: e }
        });
        return new import_langchain.ToolMessage({
          tool_call_id: request.toolCall.id,
          status: "error",
          content: e.message,
          metadata: {
            messageId
          }
        });
      } finally {
        await aiEmployee.updateToolCallDone(messageId, request.toolCall.id, result);
        const toolCallResult = await aiEmployee.getToolCallResult(messageId, request.toolCall.id);
        (_d = runtime.writer) == null ? void 0 : _d.call(runtime, {
          action: "afterToolCall",
          body: { toolCall, toolCallResult }
        });
      }
    }
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  toolCallStatusMiddleware,
  toolInteractionMiddleware
});
