// @bun
import {
  getProxyFetchOptions,
  init_proxy
} from "./chunk-1eapde8a.js";
import"./chunk-nxsh6de2.js";
import"./chunk-fbv4apne.js";
import"./chunk-3r24h7t6.js";
import"./chunk-qqfa0dqg.js";
import"./chunk-hqmz36b3.js";
import"./chunk-4g3v8y12.js";
import"./chunk-7739pg2c.js";
import"./chunk-xszk7n10.js";
import"./chunk-sdj9b9wh.js";
import {
  __esm
} from "./chunk-qp2qdcda.js";

// src/services/api/providerRegistry.ts
function resolveProvider() {
  const explicit = process.env.PROVIDER?.toLowerCase();
  if (explicit && PROVIDER_REGISTRY[explicit]) {
    return { providerId: explicit, config: PROVIDER_REGISTRY[explicit] };
  }
  const baseURL = process.env.OPENAI_BASE_URL;
  if (baseURL) {
    for (const [id, cfg] of Object.entries(PROVIDER_REGISTRY)) {
      if (baseURL.includes(new URL(cfg.baseURL).hostname)) {
        return { providerId: id, config: cfg };
      }
    }
    return {
      providerId: "custom",
      config: {
        name: "Custom OpenAI-Compatible",
        baseURL,
        defaultModel: process.env.OPENAI_MODEL || "default",
        apiKeyEnvVars: ["OPENAI_API_KEY"],
        models: []
      }
    };
  }
  for (const [id, cfg] of Object.entries(PROVIDER_REGISTRY)) {
    for (const envVar of cfg.apiKeyEnvVars) {
      if (process.env[envVar]) {
        return { providerId: id, config: cfg };
      }
    }
  }
  return { providerId: "ollama", config: PROVIDER_REGISTRY.ollama };
}
function resolveAPIKey(config) {
  for (const envVar of config.apiKeyEnvVars) {
    if (process.env[envVar])
      return process.env[envVar];
  }
  return process.env.OPENAI_API_KEY || "";
}
var PROVIDER_REGISTRY;
var init_providerRegistry = __esm(() => {
  PROVIDER_REGISTRY = {
    openai: {
      name: "OpenAI",
      baseURL: "https://api.openai.com/v1",
      defaultModel: "gpt-4o",
      apiKeyEnvVars: ["OPENAI_API_KEY"],
      models: [
        { id: "gpt-4o", name: "GPT-4o", description: "\u6700\u65B0\u65D7\u8230\u591A\u6A21\u6001\u6A21\u578B" },
        { id: "gpt-4o-mini", name: "GPT-4o Mini", description: "\u5FEB\u901F\u7ECF\u6D4E\u578B\u6A21\u578B" },
        { id: "gpt-4.1", name: "GPT-4.1", description: "GPT-4.1 \u65D7\u8230" },
        { id: "gpt-4.1-mini", name: "GPT-4.1 Mini", description: "GPT-4.1 \u7ECF\u6D4E\u578B" },
        { id: "gpt-4.1-nano", name: "GPT-4.1 Nano", description: "GPT-4.1 \u8D85\u8F7B\u91CF" },
        { id: "o3", name: "o3", description: "\u63A8\u7406\u6A21\u578B" },
        { id: "o3-mini", name: "o3-mini", description: "\u63A8\u7406\u7ECF\u6D4E\u578B" },
        { id: "o4-mini", name: "o4-mini", description: "\u6700\u65B0\u63A8\u7406\u7ECF\u6D4E\u578B" }
      ]
    },
    google: {
      name: "Google Gemini",
      baseURL: "https://generativelanguage.googleapis.com/v1beta/openai",
      defaultModel: "gemini-2.5-flash",
      apiKeyEnvVars: ["GOOGLE_API_KEY", "GEMINI_API_KEY"],
      models: [
        { id: "gemini-2.5-pro", name: "Gemini 2.5 Pro", description: "\u6700\u5F3A\u63A8\u7406\u6A21\u578B\uFF0C100 \u4E07 token \u4E0A\u4E0B\u6587" },
        { id: "gemini-2.5-flash", name: "Gemini 2.5 Flash", description: "\u5FEB\u901F\u601D\u8003\u6A21\u578B" },
        { id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", description: "\u4E0B\u4E00\u4EE3\u529F\u80FD\u3001\u901F\u5EA6" },
        { id: "gemini-2.0-flash-lite", name: "Gemini 2.0 Flash Lite", description: "\u6027\u4EF7\u6BD4\u6700\u9AD8" }
      ]
    },
    mistral: {
      name: "Mistral AI",
      baseURL: "https://api.mistral.ai/v1",
      defaultModel: "mistral-large-latest",
      apiKeyEnvVars: ["MISTRAL_API_KEY"],
      models: [
        { id: "mistral-large-latest", name: "Mistral Large", description: "\u65D7\u8230\u6A21\u578B\uFF0C\u63A8\u7406 & \u7F16\u7801" },
        { id: "mistral-medium-latest", name: "Mistral Medium", description: "\u4E2D\u7B49\u5C3A\u5BF8\u5747\u8861\u578B" },
        { id: "mistral-small-latest", name: "Mistral Small", description: "\u5FEB\u901F\u7ECF\u6D4E\u578B" },
        { id: "codestral-latest", name: "Codestral", description: "\u4E13\u7528\u7F16\u7801\u6A21\u578B" },
        { id: "pixtral-large-latest", name: "Pixtral Large", description: "\u591A\u6A21\u6001\u65D7\u8230" }
      ]
    },
    groq: {
      name: "Groq",
      baseURL: "https://api.groq.com/openai/v1",
      defaultModel: "llama-3.3-70b-versatile",
      apiKeyEnvVars: ["GROQ_API_KEY"],
      models: [
        { id: "llama-3.3-70b-versatile", name: "Llama 3.3 70B", description: "Meta Llama 3.3\uFF0C\u6781\u901F\u63A8\u7406" },
        { id: "llama-3.1-8b-instant", name: "Llama 3.1 8B", description: "\u8D85\u4F4E\u5EF6\u8FDF" },
        { id: "mixtral-8x7b-32768", name: "Mixtral 8x7B", description: "Mistral MoE \u6A21\u578B" },
        { id: "gemma2-9b-it", name: "Gemma 2 9B", description: "Google Gemma 2" },
        { id: "deepseek-r1-distill-llama-70b", name: "DeepSeek R1 Distill 70B", description: "DeepSeek R1 \u84B8\u998F\u7248" }
      ]
    },
    xai: {
      name: "xAI (Grok)",
      baseURL: "https://api.x.ai/v1",
      defaultModel: "grok-3",
      apiKeyEnvVars: ["XAI_API_KEY", "GROK_API_KEY"],
      models: [
        { id: "grok-3", name: "Grok 3", description: "xAI \u6700\u5F3A\u65D7\u8230\u6A21\u578B" },
        { id: "grok-3-mini", name: "Grok 3 Mini", description: "\u5FEB\u901F\u601D\u8003\u6A21\u578B" },
        { id: "grok-3-fast", name: "Grok 3 Fast", description: "\u4F4E\u5EF6\u8FDF\u7248\u672C" },
        { id: "grok-2", name: "Grok 2", description: "Grok 2 \u6807\u51C6\u7248" }
      ]
    },
    together: {
      name: "Together AI",
      baseURL: "https://api.together.xyz/v1",
      defaultModel: "meta-llama/Llama-3.3-70B-Instruct-Turbo",
      apiKeyEnvVars: ["TOGETHER_API_KEY"],
      models: [
        { id: "meta-llama/Llama-3.3-70B-Instruct-Turbo", name: "Llama 3.3 70B Turbo", description: "Meta Llama 3.3 \u52A0\u901F\u7248" },
        { id: "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo", name: "Llama 3.1 405B", description: "\u6700\u5927\u5F00\u6E90\u6A21\u578B" },
        { id: "deepseek-ai/DeepSeek-R1", name: "DeepSeek R1", description: "DeepSeek R1 \u5B8C\u6574\u7248" },
        { id: "Qwen/Qwen2.5-72B-Instruct-Turbo", name: "Qwen 2.5 72B", description: "\u901A\u4E49\u5343\u95EE 72B \u52A0\u901F\u7248" },
        { id: "mistralai/Mixtral-8x22B-Instruct-v0.1", name: "Mixtral 8x22B", description: "Mistral MoE \u65D7\u8230" }
      ]
    },
    cohere: {
      name: "Cohere",
      baseURL: "https://api.cohere.com/compatibility/v1",
      defaultModel: "command-a-03-2025",
      apiKeyEnvVars: ["COHERE_API_KEY", "CO_API_KEY"],
      models: [
        { id: "command-a-03-2025", name: "Command A", description: "\u6700\u5F3A\u4F01\u4E1A\u7EA7\u6A21\u578B" },
        { id: "command-r-plus", name: "Command R+", description: "RAG \u4F18\u5316\u65D7\u8230" },
        { id: "command-r", name: "Command R", description: "RAG \u4F18\u5316\u6807\u51C6" },
        { id: "command-light", name: "Command Light", description: "\u8F7B\u91CF\u5FEB\u901F" }
      ]
    },
    perplexity: {
      name: "Perplexity",
      baseURL: "https://api.perplexity.ai",
      defaultModel: "sonar-pro",
      apiKeyEnvVars: ["PERPLEXITY_API_KEY", "PPLX_API_KEY"],
      models: [
        { id: "sonar-pro", name: "Sonar Pro", description: "\u9AD8\u7EA7\u641C\u7D22\u589E\u5F3A\u6A21\u578B" },
        { id: "sonar", name: "Sonar", description: "\u6807\u51C6\u641C\u7D22\u589E\u5F3A\u6A21\u578B" },
        { id: "sonar-reasoning-pro", name: "Sonar Reasoning Pro", description: "\u63A8\u7406 + \u641C\u7D22" },
        { id: "sonar-reasoning", name: "Sonar Reasoning", description: "\u63A8\u7406 + \u641C\u7D22\u6807\u51C6" }
      ]
    },
    deepseek: {
      name: "DeepSeek \u6DF1\u5EA6\u6C42\u7D22",
      baseURL: "https://api.deepseek.com/v1",
      defaultModel: "deepseek-chat",
      apiKeyEnvVars: ["DEEPSEEK_API_KEY"],
      models: [
        { id: "deepseek-chat", name: "DeepSeek V3", description: "\u901A\u7528\u5BF9\u8BDD\uFF0CMoE \u67B6\u6784\uFF0C\u6027\u4EF7\u6BD4\u6781\u9AD8" },
        { id: "deepseek-reasoner", name: "DeepSeek R1", description: "\u63A8\u7406\u6A21\u578B\uFF0C\u652F\u6301\u601D\u7EF4\u94FE" }
      ]
    },
    qwen: {
      name: "\u963F\u91CC\u4E91 \u901A\u4E49\u5343\u95EE",
      baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
      defaultModel: "qwen-max-latest",
      apiKeyEnvVars: ["QWEN_API_KEY", "DASHSCOPE_API_KEY"],
      models: [
        { id: "qwen-max-latest", name: "Qwen Max", description: "\u65D7\u8230\u6A21\u578B\uFF0C\u7EFC\u5408\u6700\u5F3A" },
        { id: "qwen-plus-latest", name: "Qwen Plus", description: "\u6027\u80FD\u5747\u8861\u578B" },
        { id: "qwen-turbo-latest", name: "Qwen Turbo", description: "\u8D85\u5FEB\u54CD\u5E94" },
        { id: "qwen-long", name: "Qwen Long", description: "1000 \u4E07 token \u957F\u4E0A\u4E0B\u6587" },
        { id: "qwen-coder-plus-latest", name: "Qwen Coder Plus", description: "\u7F16\u7A0B\u4E13\u7528\u589E\u5F3A\u7248" },
        { id: "qwq-plus-latest", name: "QwQ Plus", description: "\u63A8\u7406\u6A21\u578B\uFF0C\u601D\u7EF4\u94FE" }
      ]
    },
    zhipu: {
      name: "\u667A\u8C31 AI (GLM)",
      baseURL: "https://open.bigmodel.cn/api/paas/v4",
      defaultModel: "glm-4-plus",
      apiKeyEnvVars: ["ZHIPU_API_KEY", "GLM_API_KEY"],
      models: [
        { id: "glm-4-plus", name: "GLM-4 Plus", description: "\u65D7\u8230\u5BF9\u8BDD\u6A21\u578B" },
        { id: "glm-4-long", name: "GLM-4 Long", description: "100 \u4E07 token \u4E0A\u4E0B\u6587" },
        { id: "glm-4-flash", name: "GLM-4 Flash", description: "\u514D\u8D39\u5FEB\u901F\u6A21\u578B" },
        { id: "glm-4-flashx", name: "GLM-4 FlashX", description: "\u6781\u901F\u63A8\u7406" },
        { id: "codegeex-4", name: "CodeGeeX 4", description: "\u7F16\u7A0B\u4E13\u7528\u6A21\u578B" }
      ]
    },
    moonshot: {
      name: "Moonshot AI (Kimi)",
      baseURL: "https://api.moonshot.cn/v1",
      defaultModel: "moonshot-v1-128k",
      apiKeyEnvVars: ["MOONSHOT_API_KEY", "KIMI_API_KEY"],
      models: [
        { id: "moonshot-v1-8k", name: "Moonshot 8K", description: "8K \u4E0A\u4E0B\u6587" },
        { id: "moonshot-v1-32k", name: "Moonshot 32K", description: "32K \u4E0A\u4E0B\u6587" },
        { id: "moonshot-v1-128k", name: "Moonshot 128K", description: "128K \u957F\u4E0A\u4E0B\u6587" }
      ]
    },
    doubao: {
      name: "\u5B57\u8282\u8DF3\u52A8 \u8C46\u5305",
      baseURL: "https://ark.cn-beijing.volces.com/api/v3",
      defaultModel: "doubao-1.5-pro-32k",
      apiKeyEnvVars: ["DOUBAO_API_KEY", "ARK_API_KEY", "VOLC_API_KEY"],
      models: [
        { id: "doubao-1.5-pro-32k", name: "\u8C46\u5305 1.5 Pro 32K", description: "\u65D7\u8230\u6A21\u578B" },
        { id: "doubao-1.5-pro-256k", name: "\u8C46\u5305 1.5 Pro 256K", description: "\u957F\u4E0A\u4E0B\u6587\u65D7\u8230" },
        { id: "doubao-1.5-lite-32k", name: "\u8C46\u5305 1.5 Lite 32K", description: "\u8F7B\u91CF\u5FEB\u901F" },
        { id: "doubao-1.5-vision-pro-32k", name: "\u8C46\u5305 Vision Pro", description: "\u591A\u6A21\u6001\u7406\u89E3" }
      ]
    },
    baidu: {
      name: "\u767E\u5EA6 \u6587\u5FC3\u4E00\u8A00",
      baseURL: "https://qianfan.baidubce.com/v2",
      defaultModel: "ernie-4.5-8k",
      apiKeyEnvVars: ["BAIDU_API_KEY", "QIANFAN_API_KEY"],
      models: [
        { id: "ernie-4.5-8k", name: "ERNIE 4.5", description: "\u6587\u5FC3\u5927\u6A21\u578B 4.5 \u65D7\u8230" },
        { id: "ernie-4.5-turbo-128k", name: "ERNIE 4.5 Turbo 128K", description: "\u957F\u4E0A\u4E0B\u6587\u5FEB\u901F" },
        { id: "ernie-x1-turbo-32k", name: "ERNIE X1 Turbo", description: "\u63A8\u7406\u6A21\u578B" },
        { id: "ernie-3.5-8k", name: "ERNIE 3.5", description: "\u7ECF\u5178\u7248\u672C" }
      ]
    },
    yi: {
      name: "\u96F6\u4E00\u4E07\u7269 (Yi)",
      baseURL: "https://api.lingyiwanwu.com/v1",
      defaultModel: "yi-lightning",
      apiKeyEnvVars: ["YI_API_KEY", "LINGYIWANWU_API_KEY"],
      models: [
        { id: "yi-lightning", name: "Yi Lightning", description: "\u6781\u901F\u63A8\u7406\uFF0C\u6027\u4EF7\u6BD4\u9AD8" },
        { id: "yi-large", name: "Yi Large", description: "\u65D7\u8230\u6A21\u578B" },
        { id: "yi-large-turbo", name: "Yi Large Turbo", description: "\u65D7\u8230\u52A0\u901F\u7248" },
        { id: "yi-medium", name: "Yi Medium", description: "\u5747\u8861\u578B" }
      ]
    },
    stepfun: {
      name: "\u9636\u8DC3\u661F\u8FB0 (Step)",
      baseURL: "https://api.stepfun.com/v1",
      defaultModel: "step-2-16k",
      apiKeyEnvVars: ["STEPFUN_API_KEY", "STEP_API_KEY"],
      models: [
        { id: "step-2-16k", name: "Step 2", description: "\u4E07\u4EBF\u53C2\u6570 MoE \u65D7\u8230" },
        { id: "step-1-200k", name: "Step 1 200K", description: "200K \u957F\u4E0A\u4E0B\u6587" },
        { id: "step-1-32k", name: "Step 1 32K", description: "\u6807\u51C6\u4E0A\u4E0B\u6587" },
        { id: "step-1-flash", name: "Step 1 Flash", description: "\u6781\u901F\u54CD\u5E94" }
      ]
    },
    baichuan: {
      name: "\u767E\u5DDD\u667A\u80FD",
      baseURL: "https://api.baichuan-ai.com/v1",
      defaultModel: "Baichuan4-Air",
      apiKeyEnvVars: ["BAICHUAN_API_KEY"],
      models: [
        { id: "Baichuan4-Air", name: "Baichuan 4 Air", description: "\u65D7\u8230\u6A21\u578B" },
        { id: "Baichuan4-Turbo", name: "Baichuan 4 Turbo", description: "\u5FEB\u901F\u7248" },
        { id: "Baichuan3-Turbo", name: "Baichuan 3 Turbo", description: "\u7ECF\u5178\u5FEB\u901F" }
      ]
    },
    minimax: {
      name: "MiniMax",
      baseURL: "https://api.minimax.chat/v1",
      defaultModel: "MiniMax-Text-01",
      apiKeyEnvVars: ["MINIMAX_API_KEY"],
      models: [
        { id: "MiniMax-Text-01", name: "MiniMax Text 01", description: "400 \u4E07 token \u65D7\u8230\u6A21\u578B" },
        { id: "MiniMax-M1", name: "MiniMax M1", description: "\u63A8\u7406\u589E\u5F3A\u6A21\u578B" },
        { id: "abab6.5s-chat", name: "ABAB 6.5s", description: "\u6807\u51C6\u5BF9\u8BDD" }
      ]
    },
    spark: {
      name: "\u8BAF\u98DE\u661F\u706B",
      baseURL: "https://spark-api-open.xf-yun.com/v1",
      defaultModel: "spark-max",
      apiKeyEnvVars: ["SPARK_API_KEY", "XFYUN_API_KEY"],
      models: [
        { id: "spark-max", name: "\u661F\u706B Max", description: "\u65D7\u8230\u6A21\u578B" },
        { id: "spark-pro-128k", name: "\u661F\u706B Pro 128K", description: "\u957F\u4E0A\u4E0B\u6587\u4E13\u4E1A\u7248" },
        { id: "spark-lite", name: "\u661F\u706B Lite", description: "\u8F7B\u91CF\u514D\u8D39" }
      ]
    },
    hunyuan: {
      name: "\u817E\u8BAF\u6DF7\u5143",
      baseURL: "https://api.hunyuan.cloud.tencent.com/v1",
      defaultModel: "hunyuan-turbos-latest",
      apiKeyEnvVars: ["HUNYUAN_API_KEY", "TENCENT_API_KEY"],
      models: [
        { id: "hunyuan-turbos-latest", name: "\u6DF7\u5143 Turbo S", description: "\u65D7\u8230\u6A21\u578B" },
        { id: "hunyuan-large-latest", name: "\u6DF7\u5143 Large", description: "\u8D85\u5927\u53C2\u6570" },
        { id: "hunyuan-standard-latest", name: "\u6DF7\u5143 Standard", description: "\u5747\u8861\u578B" },
        { id: "hunyuan-lite-latest", name: "\u6DF7\u5143 Lite", description: "\u8F7B\u91CF\u7248" }
      ]
    },
    siliconflow: {
      name: "\u7845\u57FA\u6D41\u52A8 SiliconFlow",
      baseURL: "https://api.siliconflow.cn/v1",
      defaultModel: "deepseek-ai/DeepSeek-V3",
      apiKeyEnvVars: ["SILICONFLOW_API_KEY", "SF_API_KEY"],
      models: [
        { id: "deepseek-ai/DeepSeek-V3", name: "DeepSeek V3", description: "DeepSeek V3 \u6258\u7BA1\u7248" },
        { id: "deepseek-ai/DeepSeek-R1", name: "DeepSeek R1", description: "DeepSeek R1 \u6258\u7BA1\u7248" },
        { id: "Qwen/Qwen2.5-72B-Instruct", name: "Qwen 2.5 72B", description: "\u901A\u4E49\u5343\u95EE 72B" },
        { id: "Pro/Qwen/Qwen2.5-7B-Instruct", name: "Qwen 2.5 7B (Pro)", description: "\u52A0\u901F\u7248" },
        { id: "THUDM/glm-4-9b-chat", name: "GLM-4 9B", description: "\u667A\u8C31 GLM-4 \u8F7B\u91CF" }
      ]
    },
    openrouter: {
      name: "OpenRouter",
      baseURL: "https://openrouter.ai/api/v1",
      defaultModel: "anthropic/claude-sonnet-4",
      apiKeyEnvVars: ["OPENROUTER_API_KEY", "OR_API_KEY"],
      models: [
        { id: "anthropic/claude-sonnet-4", name: "Claude Sonnet 4", description: "Anthropic Claude Sonnet" },
        { id: "openai/gpt-4o", name: "GPT-4o", description: "OpenAI GPT-4o" },
        { id: "google/gemini-2.5-pro", name: "Gemini 2.5 Pro", description: "Google Gemini" },
        { id: "deepseek/deepseek-r1", name: "DeepSeek R1", description: "DeepSeek R1" },
        { id: "meta-llama/llama-3.3-70b-instruct", name: "Llama 3.3 70B", description: "Meta Llama" }
      ]
    },
    ollama: {
      name: "Ollama",
      baseURL: "http://218.201.19.105:11434/v1",
      defaultModel: "qwen3.5:35b",
      apiKeyEnvVars: ["OLLAMA_API_KEY"],
      models: [
        { id: "qwen3.5:35b", name: "Qwen 3.5 35B", description: "\u901A\u4E49\u5343\u95EE 3.5 MoE (\u672C\u5730)" },
        { id: "qwen3:30b-thinking", name: "Qwen 3 30B Thinking", description: "\u5343\u95EE 3 \u601D\u7EF4\u94FE" },
        { id: "qwen3:4b-thinking", name: "Qwen 3 4B Thinking", description: "\u5343\u95EE 3 \u8F7B\u91CF\u601D\u7EF4\u94FE" },
        { id: "qwen2.5:7b-instruct", name: "Qwen 2.5 7B", description: "\u901A\u4E49\u5343\u95EE 2.5" },
        { id: "deepseek-r1:14b", name: "DeepSeek R1 14B", description: "DeepSeek \u63A8\u7406" },
        { id: "deepseek-r1:32b", name: "DeepSeek R1 32B", description: "DeepSeek \u63A8\u7406\u5927\u6A21\u578B" },
        { id: "deepseek-r1:70b", name: "DeepSeek R1 70B", description: "DeepSeek \u63A8\u7406\u65D7\u8230" },
        { id: "llama3.1", name: "Llama 3.1", description: "Meta Llama 3.1" },
        { id: "mistral", name: "Mistral 7B", description: "Mistral \u672C\u5730" }
      ]
    }
  };
});

// src/services/api/openaiAdapter.ts
import { createHash } from "crypto";
function getOpenAIConfig() {
  const resolved = resolveProvider();
  if (resolved) {
    const { config } = resolved;
    return {
      apiKey: resolveAPIKey(config),
      baseURL: process.env.OPENAI_BASE_URL || config.baseURL,
      model: process.env.OPENAI_MODEL || config.defaultModel
    };
  }
  return {
    apiKey: process.env.OPENAI_API_KEY || "",
    baseURL: process.env.OPENAI_BASE_URL || "https://api.openai.com/v1",
    model: process.env.OPENAI_MODEL || "gpt-4o"
  };
}
function convertMessages(system, messages) {
  const result = [];
  if (system) {
    if (typeof system === "string") {
      result.push({ role: "system", content: system });
    } else if (Array.isArray(system)) {
      const text = system.map((b) => typeof b === "string" ? b : b?.text || "").filter(Boolean).join(`
`);
      if (text)
        result.push({ role: "system", content: text });
    }
  }
  for (const msg of messages) {
    const m = msg;
    const role = m.role === "assistant" ? "assistant" : "user";
    let content = "";
    if (typeof m.content === "string") {
      content = m.content;
    } else if (Array.isArray(m.content)) {
      const parts = [];
      for (const block of m.content) {
        if (typeof block === "string") {
          parts.push(block);
        } else if (block.type === "text") {
          parts.push(block.text || "");
        } else if (block.type === "tool_use") {
          parts.push(`[Tool call: ${block.name}(${JSON.stringify(block.input)})]`);
        } else if (block.type === "tool_result") {
          const resultContent = typeof block.content === "string" ? block.content : Array.isArray(block.content) ? block.content.map((c) => c.text || "").join(`
`) : "";
          parts.push(`[Tool result: ${resultContent}]`);
        } else if (block.type === "thinking") {} else if (block.type === "image") {
          parts.push("[Image content]");
        }
      }
      content = parts.join(`
`);
    }
    if (content) {
      result.push({ role, content });
    }
  }
  return result;
}
function convertTools(tools) {
  if (!tools || tools.length === 0)
    return;
  return tools.map((tool) => ({
    type: "function",
    function: {
      name: tool.name,
      description: tool.description || "",
      parameters: tool.input_schema || {}
    }
  }));
}
async function* openaiStreamToAnthropicEvents(response, model) {
  yield {
    type: "message_start",
    message: {
      id: `msg_openai_${Date.now()}`,
      type: "message",
      role: "assistant",
      content: [],
      model,
      stop_reason: null,
      stop_sequence: null,
      usage: { input_tokens: 0, output_tokens: 0 }
    }
  };
  let textBlockStarted = false;
  let textBlockIndex = 0;
  let toolCallBlocks = new Map;
  let thinkingBlockStarted = false;
  let thinkingBlockIndex = -1;
  let nextBlockIndex = 0;
  let outputTokens = 0;
  let inputTokens = 0;
  const reader = response.body?.getReader();
  if (!reader)
    return;
  const decoder = new TextDecoder;
  let buffer = "";
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done)
        break;
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split(`
`);
      buffer = lines.pop() || "";
      for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed || trimmed === "data: [DONE]")
          continue;
        if (!trimmed.startsWith("data: "))
          continue;
        let chunk;
        try {
          chunk = JSON.parse(trimmed.slice(6));
        } catch {
          continue;
        }
        if (chunk.usage) {
          inputTokens = chunk.usage.prompt_tokens || 0;
          outputTokens = chunk.usage.completion_tokens || 0;
        }
        for (const choice of chunk.choices) {
          const delta = choice.delta;
          const thinkingText = delta.reasoning_content || delta.reasoning;
          if (thinkingText) {
            if (!thinkingBlockStarted) {
              thinkingBlockIndex = nextBlockIndex++;
              thinkingBlockStarted = true;
              yield {
                type: "content_block_start",
                index: thinkingBlockIndex,
                content_block: { type: "thinking", thinking: "", signature: "" }
              };
            }
            yield {
              type: "content_block_delta",
              index: thinkingBlockIndex,
              delta: { type: "thinking_delta", thinking: thinkingText }
            };
          }
          if (delta.content && delta.content.length > 0) {
            if (thinkingBlockStarted && !textBlockStarted) {
              yield {
                type: "content_block_stop",
                index: thinkingBlockIndex
              };
              thinkingBlockStarted = false;
            }
            if (!textBlockStarted) {
              textBlockIndex = nextBlockIndex++;
              textBlockStarted = true;
              yield {
                type: "content_block_start",
                index: textBlockIndex,
                content_block: { type: "text", text: "" }
              };
            }
            yield {
              type: "content_block_delta",
              index: textBlockIndex,
              delta: { type: "text_delta", text: delta.content }
            };
            outputTokens++;
          }
          if (delta.tool_calls) {
            for (const tc of delta.tool_calls) {
              if (!toolCallBlocks.has(tc.index)) {
                if (textBlockStarted) {
                  yield { type: "content_block_stop", index: textBlockIndex };
                  textBlockStarted = false;
                }
                const blockIdx = nextBlockIndex++;
                const toolId = tc.id || `toolu_openai_${Date.now()}_${tc.index}`;
                const toolName = tc.function?.name || "";
                toolCallBlocks.set(tc.index, { id: toolId, name: toolName, argsBuf: "" });
                yield {
                  type: "content_block_start",
                  index: blockIdx,
                  content_block: {
                    type: "tool_use",
                    id: toolId,
                    name: toolName,
                    input: {}
                  }
                };
              }
              const block = toolCallBlocks.get(tc.index);
              if (tc.function?.arguments) {
                block.argsBuf += tc.function.arguments;
                yield {
                  type: "content_block_delta",
                  index: nextBlockIndex - 1,
                  delta: {
                    type: "input_json_delta",
                    partial_json: tc.function.arguments
                  }
                };
              }
            }
          }
          if (choice.finish_reason) {
            if (thinkingBlockStarted) {
              yield { type: "content_block_stop", index: thinkingBlockIndex };
            }
            if (textBlockStarted) {
              yield { type: "content_block_stop", index: textBlockIndex };
            }
            for (const [, _] of toolCallBlocks) {}
          }
        }
      }
    }
  } finally {
    reader.releaseLock();
  }
  yield {
    type: "message_delta",
    delta: { stop_reason: "end_turn", stop_sequence: null },
    usage: { output_tokens: outputTokens }
  };
  yield {
    type: "message_stop"
  };
}
function hashKey(key) {
  return createHash("sha256").update(key).digest("hex");
}
function verifyOllamaLicense() {
  const userSetBaseURL = process.env.OPENAI_BASE_URL;
  const userSetProvider = process.env.PROVIDER;
  if (userSetBaseURL)
    return;
  if (userSetProvider && userSetProvider.toLowerCase() !== "ollama")
    return;
  if (process.env.OPENAI_API_KEY || process.env.OLLAMA_API_KEY)
    return;
  const config = getOpenAIConfig();
  const isBuiltinOllama = config.baseURL.includes("218.201.19.105:11434") || config.baseURL.includes("localhost:11434") || config.baseURL.includes("127.0.0.1:11434");
  if (!isBuiltinOllama)
    return;
  const licenseKey = process.env.JIALING_LICENSE_KEY?.trim();
  if (!licenseKey) {
    throw new Error(`
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
` + `\u2551  \u5609\u9675\u6C5F-code Ollama \u672C\u5730\u6A21\u5F0F\u9700\u8981\u6388\u6743\u5BC6\u94A5                  \u2551
` + `\u2551                                                          \u2551
` + `\u2551  \u8BF7\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF:                                          \u2551
` + `\u2551    export JIALING_LICENSE_KEY="\u4F60\u7684\u5BC6\u94A5"                   \u2551
` + `\u2551                                                          \u2551
` + `\u2551  \u83B7\u53D6\u5BC6\u94A5\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458                                      \u2551
` + `\u2551                                                          \u2551
` + `\u2551  \u4F7F\u7528\u5176\u4ED6\u5927\u6A21\u578B\u5382\u5546\u4E0D\u53D7\u6B64\u9650\u5236:                              \u2551
` + `\u2551    export DEEPSEEK_API_KEY=sk-xxx  (DeepSeek)             \u2551
` + `\u2551    export OPENAI_API_KEY=sk-xxx    (OpenAI)               \u2551
` + `\u2551    export QWEN_API_KEY=sk-xxx      (\u901A\u4E49\u5343\u95EE)              \u2551
` + `\u2551    ... \u652F\u6301 22+ \u5382\u5546\uFF0C\u8BE6\u89C1\u6587\u6863                             \u2551
` + `\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
`);
  }
  if (!OLLAMA_LICENSE_HASHES.has(hashKey(licenseKey))) {
    throw new Error(`
[\u5609\u9675\u6C5F-code] \u5BC6\u94A5\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 JIALING_LICENSE_KEY \u662F\u5426\u6B63\u786E\u3002
`);
  }
}
function createOpenAIAdapterClient(options) {
  verifyOllamaLicense();
  const config = getOpenAIConfig();
  const client = {
    beta: {
      messages: {
        create: (params, requestOptions) => {
          const doFetch = async () => {
            const model = params.model || config.model;
            const openaiMessages = convertMessages(params.system, params.messages);
            const openaiTools = convertTools(params.tools || []);
            const isOllama = config.baseURL.includes("localhost:11434") || config.baseURL.includes("127.0.0.1:11434") || config.baseURL.includes("218.201.19.105:11434") || process.env.PROVIDER === "ollama";
            const body = {
              model,
              messages: openaiMessages,
              stream: true,
              ...!isOllama && { stream_options: { include_usage: true } },
              max_tokens: params.max_tokens || 16384
            };
            if (params.temperature !== undefined) {
              body.temperature = params.temperature;
            }
            if (openaiTools && openaiTools.length > 0) {
              body.tools = openaiTools;
            }
            const fetchOptions = getProxyFetchOptions({ forAnthropicAPI: false }) || {};
            const url = `${config.baseURL.replace(/\/+$/, "")}/chat/completions`;
            const headers = {
              "Content-Type": "application/json",
              ...process.env.OPENAI_CUSTOM_HEADERS ? parseCustomHeaders(process.env.OPENAI_CUSTOM_HEADERS) : {}
            };
            if (config.apiKey && config.apiKey !== "ollama") {
              headers["Authorization"] = `Bearer ${config.apiKey}`;
            }
            const response = await fetch(url, {
              method: "POST",
              headers,
              body: JSON.stringify(body),
              signal: requestOptions?.signal,
              ...fetchOptions
            });
            if (!response.ok) {
              const errorText = await response.text().catch(() => "Unknown error");
              throw new Error(`OpenAI API error (${response.status}): ${errorText}`);
            }
            const stream = openaiStreamToAnthropicEvents(response, model);
            return { stream, response };
          };
          const resultPromise = doFetch();
          return {
            withResponse: () => resultPromise.then(({ stream, response }) => ({
              data: stream,
              response,
              request_id: response.headers.get("x-request-id") || `openai-${Date.now()}`
            })),
            then: (resolve, reject) => resultPromise.then(({ stream }) => stream).then(resolve, reject)
          };
        }
      }
    },
    messages: {
      create: async () => {
        throw new Error("Use beta.messages.create for OpenAI adapter");
      }
    }
  };
  return client;
}
function parseCustomHeaders(headerStr) {
  const headers = {};
  for (const line of headerStr.split(/\n|\r\n/)) {
    const idx = line.indexOf(":");
    if (idx === -1)
      continue;
    const name = line.slice(0, idx).trim();
    const value = line.slice(idx + 1).trim();
    if (name)
      headers[name] = value;
  }
  return headers;
}
var OLLAMA_LICENSE_HASHES;
var init_openaiAdapter = __esm(() => {
  init_proxy();
  init_providerRegistry();
  OLLAMA_LICENSE_HASHES = new Set([
    "2352f11c7b38404b2ab5a135b3c429199a5a0ff7c04349c9179b3f58265f6b3a"
  ]);
});
init_openaiAdapter();

export {
  getOpenAIConfig,
  createOpenAIAdapterClient
};
