/**
 * 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 anthropic_exports = {};
__export(anthropic_exports, {
  AnthropicProvider: () => AnthropicProvider,
  anthropicProviderOptions: () => anthropicProviderOptions
});
module.exports = __toCommonJS(anthropic_exports);
var import_provider = require("./provider");
var import_anthropic = require("@langchain/anthropic");
var import_axios = __toESM(require("axios"));
var import_utils = require("../utils");
var import_ai_manager = require("../manager/ai-manager");
const MAX_TOKENS_PRESET = {
  "kimi-for-coding": 128 * 1024
};
class AnthropicProvider extends import_provider.LLMProvider {
  get baseURL() {
    return "https://api.anthropic.com";
  }
  createModel() {
    const { apiKey, baseURL } = this.serviceOptions || {};
    const sanitizedModelOptions = { ...this.modelOptions || {} };
    const model = sanitizedModelOptions.model;
    const hasTemperature = sanitizedModelOptions.temperature !== void 0 && sanitizedModelOptions.temperature !== null;
    const hasTopP = sanitizedModelOptions.topP !== void 0 && sanitizedModelOptions.topP !== null || sanitizedModelOptions.top_p !== void 0 && sanitizedModelOptions.top_p !== null;
    if (hasTemperature) {
      delete sanitizedModelOptions.topP;
      delete sanitizedModelOptions.top_p;
      delete sanitizedModelOptions.topK;
      delete sanitizedModelOptions.top_k;
    } else if (hasTopP) {
      delete sanitizedModelOptions.temperature;
      delete sanitizedModelOptions.topK;
      delete sanitizedModelOptions.top_k;
    } else {
      delete sanitizedModelOptions.topK;
      delete sanitizedModelOptions.top_k;
    }
    for (const key of ["topP", "top_p", "topK", "top_k"]) {
      if (sanitizedModelOptions[key] === -1) {
        delete sanitizedModelOptions[key];
      }
    }
    this.setMaxTokens(sanitizedModelOptions);
    return new import_anthropic.ChatAnthropic({
      apiKey,
      ...sanitizedModelOptions,
      model,
      anthropicApiUrl: baseURL || this.baseURL,
      verbose: false
    });
  }
  async listModels() {
    var _a, _b, _c, _d, _e;
    const options = this.serviceOptions || {};
    const apiKey = options.apiKey;
    let baseURL = options.baseURL || this.baseURL;
    if (!baseURL) {
      return { code: 400, errMsg: "baseURL is required" };
    }
    if (!apiKey) {
      return { code: 400, errMsg: "API Key required" };
    }
    if (baseURL && baseURL.endsWith("/")) {
      baseURL = baseURL.slice(0, -1);
    }
    try {
      const res = await import_axios.default.get(`${baseURL}/v1/models`, {
        headers: {
          "x-api-key": apiKey,
          "anthropic-version": "2023-06-01"
        }
      });
      return {
        models: (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.data
      };
    } catch (e) {
      const status = ((_b = e.response) == null ? void 0 : _b.status) || 500;
      const errorMsg = ((_e = (_d = (_c = e.response) == null ? void 0 : _c.data) == null ? void 0 : _d.error) == null ? void 0 : _e.message) || e.message;
      return { code: status, errMsg: `Anthropic API Error: ${errorMsg}` };
    }
  }
  parseResponseMessage(message) {
    const { content: rawContent, messageId, metadata, role, toolCalls, attachments, workContext } = message;
    const content = {
      ...rawContent,
      messageId,
      metadata,
      attachments,
      workContext
    };
    if (toolCalls) {
      content.tool_calls = toolCalls;
    }
    if (Array.isArray(content.content)) {
      const blocks = content.content;
      const textBlocks = blocks.filter((msg) => msg.type === "text");
      content.content = textBlocks.map((block) => block.text).join("") || "";
      if (!content.reference) {
        const refs = [];
        for (const block of blocks) {
          if (block.type === "web_search_tool_result" && Array.isArray(block.content)) {
            for (const item of block.content) {
              if (item.type === "web_search_result" && item.url) {
                refs.push({ title: item.title || "", url: item.url });
              }
            }
          }
        }
        if (refs.length) {
          content.reference = refs;
        }
      }
    }
    return {
      key: messageId,
      content,
      role
    };
  }
  parseResponseChunk(chunk) {
    if (chunk && Array.isArray(chunk)) {
      const textBlock = chunk.find((block) => block.type === "text");
      if (textBlock) {
        return (0, import_utils.stripToolCallTags)(textBlock.text);
      }
      return null;
    }
    return (0, import_utils.stripToolCallTags)(chunk);
  }
  builtInTools() {
    var _a, _b;
    if (((_b = (_a = this.modelOptions) == null ? void 0 : _a.builtIn) == null ? void 0 : _b.webSearch) === true) {
      return [
        {
          type: "web_search_20250305",
          name: "web_search"
        }
      ];
    }
    return [];
  }
  isToolConflict() {
    return false;
  }
  parseWebSearchAction(chunk) {
    if (!Array.isArray(chunk.content)) {
      return [];
    }
    return chunk.content.filter((block) => block.type === "server_tool_use" && block.name === "web_search").map((block) => {
      var _a;
      return {
        type: "web_search",
        query: ((_a = block.input) == null ? void 0 : _a.query) || ""
      };
    });
  }
  async convertToContent(ctx, attachment) {
    const fileManager = this.app.pm.get("file-manager");
    const url = await fileManager.getFileURL(attachment);
    const data = await (0, import_utils.encodeFile)(ctx, decodeURIComponent(url));
    if (attachment.mimetype.startsWith("image/")) {
      return {
        placement: "contentBlocks",
        content: {
          type: "image_url",
          image_url: {
            url: `data:image/${attachment.mimetype.split("/")[1]};base64,${data}`
          }
        }
      };
    } else {
      return {
        placement: "contentBlocks",
        content: {
          type: "document",
          source: {
            type: "base64",
            media_type: attachment.mimetype,
            data
          }
        }
      };
    }
  }
  setMaxTokens(options = {}) {
    var _a;
    if (!options.model || options.maxTokens) {
      return;
    }
    options.maxTokens = (_a = Object.entries(MAX_TOKENS_PRESET).find(([key]) => options.model.startsWith(key))) == null ? void 0 : _a[1];
  }
}
const anthropicProviderOptions = {
  title: "Anthropic",
  supportedModel: [import_ai_manager.SupportedModel.LLM],
  models: {
    [import_ai_manager.SupportedModel.LLM]: [
      "claude-opus-4-0",
      "claude-sonnet-4-0",
      "claude-3-7-sonnet-latest",
      "claude-3-5-sonnet-latest",
      "claude-3-5-haiku-latest"
    ]
  },
  provider: AnthropicProvider,
  supportWebSearch: true
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AnthropicProvider,
  anthropicProviderOptions
});
