/**
 * 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 provider_exports = {};
__export(provider_exports, {
  KimiProvider: () => KimiProvider,
  kimiProviderOptions: () => kimiProviderOptions
});
module.exports = __toCommonJS(provider_exports);
var import_node_path = __toESM(require("node:path"));
var import_lodash = __toESM(require("lodash"));
var import_provider = require("../provider");
var import_ai_manager = require("../../manager/ai-manager");
var import_document_loader = require("../../document-loader");
var import_document_loader2 = require("./document-loader");
var import_reasoning = require("../common/reasoning");
class KimiProvider extends import_provider.LLMProvider {
  _documentLoader;
  get baseURL() {
    return "https://api.moonshot.cn/v1";
  }
  createModel() {
    const { baseURL, apiKey } = this.serviceOptions || {};
    const { responseFormat, structuredOutput } = this.modelOptions || {};
    const { schema } = structuredOutput || {};
    const responseFormatOptions = {
      type: responseFormat ?? "text"
    };
    if (responseFormat === "json_schema" && schema) {
      responseFormatOptions["json_schema"] = schema;
    }
    return new import_reasoning.ReasoningChatOpenAI({
      apiKey,
      ...this.modelOptions,
      modelKwargs: {
        response_format: responseFormatOptions
      },
      configuration: {
        baseURL: baseURL || this.baseURL
      }
    });
  }
  parseResponseMessage(message) {
    var _a;
    const result = super.parseResponseMessage(message);
    if (["user", "tool"].includes(result == null ? void 0 : result.role)) {
      return result;
    }
    const { metadata } = (message == null ? void 0 : message.toJSON()) ?? {};
    if (!import_lodash.default.isEmpty((_a = metadata == null ? void 0 : metadata.additional_kwargs) == null ? void 0 : _a.reasoning_content)) {
      result.content = {
        ...result.content ?? {},
        reasoning: {
          status: "stop",
          content: metadata == null ? void 0 : metadata.additional_kwargs.reasoning_content
        }
      };
    }
    return result;
  }
  parseReasoningContent(chunk) {
    var _a;
    if (!import_lodash.default.isEmpty((_a = chunk == null ? void 0 : chunk.additional_kwargs) == null ? void 0 : _a.reasoning_content)) {
      return {
        status: "streaming",
        content: chunk.additional_kwargs.reasoning_content
      };
    }
    return null;
  }
  async parseAttachment(ctx, attachment) {
    if (!(attachment == null ? void 0 : attachment.mimetype) || attachment.mimetype.startsWith("image/")) {
      return super.parseAttachment(ctx, attachment);
    }
    const parsed = await this.documentLoader.load(attachment);
    const safeFilename = attachment.filename ? import_node_path.default.basename(attachment.filename) : "document";
    if (!parsed.supported) {
      return {
        placement: "system",
        content: `File ${safeFilename} is not a supported document type for text parsing.`
      };
    }
    if (parsed.text.length === 0) {
      return {
        placement: "system",
        content: `The file provided by the user is an empty file, file name is "${safeFilename}"`
      };
    }
    return {
      placement: "system",
      content: `<parsed_document filename="${safeFilename}">
${parsed.text}
</parsed_document>`
    };
  }
  get aiPlugin() {
    return this.app.pm.get("ai");
  }
  get documentLoader() {
    var _a, _b;
    if (!this._documentLoader) {
      const loader = new import_document_loader2.KimiDocumentLoader(this.aiPlugin.fileManager, {
        apiKey: (_a = this.serviceOptions) == null ? void 0 : _a.apiKey,
        baseURL: ((_b = this.serviceOptions) == null ? void 0 : _b.baseURL) || this.baseURL
      });
      this._documentLoader = new import_document_loader.CachedDocumentLoader(this.aiPlugin, {
        loader,
        parserVersion: "kimi-v1",
        parsedMimetype: "application/json",
        parsedFileExtname: "json",
        supports: () => true
      });
    }
    return this._documentLoader;
  }
}
const kimiProviderOptions = {
  title: "Kimi",
  supportedModel: [import_ai_manager.SupportedModel.LLM],
  models: {
    [import_ai_manager.SupportedModel.LLM]: ["kimi-k2.5", "kimi-k2-0905-Preview", "kimi-k2-turbo-preview"]
  },
  provider: KimiProvider
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  KimiProvider,
  kimiProviderOptions
});
