// Force strict mode and setup for ESM
"use strict";
import {
  InstallationManager
} from "./chunk-BZHLWC6T.js";
import "./chunk-T42ACHFI.js";
import {
  GoogleGenAI
} from "./chunk-55ZMG67I.js";
import "./chunk-H6BD2ELD.js";
import "./chunk-5IFG2VC4.js";
import {
  createDebugLogger
} from "./chunk-AVQDCKNF.js";
import "./chunk-Z2Z3GUXZ.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/core/geminiContentGenerator/index.ts
init_esbuild_shims();

// packages/core/src/core/geminiContentGenerator/geminiContentGenerator.ts
init_esbuild_shims();
var debugLogger = createDebugLogger("GEMINI");
var GeminiContentGenerator = class {
  static {
    __name(this, "GeminiContentGenerator");
  }
  googleGenAI;
  contentGeneratorConfig;
  // Latch so the effort-clamp warning fires once per generator lifetime
  // instead of on every request that needs the downgrade.
  effortClampWarned = false;
  constructor(options, contentGeneratorConfig) {
    const customHeaders = contentGeneratorConfig?.customHeaders;
    const finalOptions = customHeaders ? (() => {
      const baseHttpOptions = options.httpOptions;
      const baseHeaders = baseHttpOptions?.headers ?? {};
      return {
        ...options,
        httpOptions: {
          ...baseHttpOptions ?? {},
          headers: {
            ...baseHeaders,
            ...customHeaders
          }
        }
      };
    })() : options;
    this.googleGenAI = new GoogleGenAI(finalOptions);
    this.contentGeneratorConfig = contentGeneratorConfig;
  }
  buildGenerateContentConfig(request) {
    const configSamplingParams = this.contentGeneratorConfig?.samplingParams;
    const requestConfig = request.config || {};
    const getParameterValue = /* @__PURE__ */ __name((configValue, requestKey, defaultValue) => {
      const requestValue = requestConfig[requestKey];
      if (configValue !== void 0) return configValue;
      if (requestValue !== void 0) return requestValue;
      return defaultValue;
    }, "getParameterValue");
    return {
      ...requestConfig,
      temperature: getParameterValue(
        configSamplingParams?.temperature,
        "temperature",
        1
      ),
      topP: getParameterValue(
        configSamplingParams?.top_p,
        "topP",
        0.95
      ),
      topK: getParameterValue(configSamplingParams?.top_k, "topK", 64),
      maxOutputTokens: getParameterValue(
        configSamplingParams?.max_tokens,
        "maxOutputTokens"
      ),
      presencePenalty: getParameterValue(
        configSamplingParams?.presence_penalty,
        "presencePenalty"
      ),
      frequencyPenalty: getParameterValue(
        configSamplingParams?.frequency_penalty,
        "frequencyPenalty"
      ),
      thinkingConfig: getParameterValue(
        this.buildThinkingConfig(),
        "thinkingConfig",
        {
          includeThoughts: true,
          thinkingLevel: "THINKING_LEVEL_UNSPECIFIED"
        }
      )
    };
  }
  buildThinkingConfig() {
    const reasoning = this.contentGeneratorConfig?.reasoning;
    if (reasoning === false) {
      return { includeThoughts: false };
    }
    if (reasoning) {
      let thinkingLevel;
      switch (reasoning.effort) {
        case "low":
          thinkingLevel = "LOW";
          break;
        case "medium":
          thinkingLevel = "MEDIUM";
          break;
        case "high":
          thinkingLevel = "HIGH";
          break;
        case "xhigh":
        case "max":
          if (!this.effortClampWarned) {
            debugLogger.warn(
              `reasoning.effort='${reasoning.effort}' is not supported by Gemini; clamping to 'HIGH'.`
            );
            this.effortClampWarned = true;
          }
          thinkingLevel = "HIGH";
          break;
        case void 0:
          thinkingLevel = "THINKING_LEVEL_UNSPECIFIED";
          break;
        default: {
          const _exhaustive = reasoning.effort;
          void _exhaustive;
          thinkingLevel = "THINKING_LEVEL_UNSPECIFIED";
          break;
        }
      }
      return {
        includeThoughts: true,
        thinkingLevel
      };
    }
    return void 0;
  }
  async generateContent(request, _userPromptId) {
    const finalRequest = {
      ...request,
      contents: this.stripUnsupportedFields(request.contents),
      config: this.buildGenerateContentConfig(request)
    };
    return this.googleGenAI.models.generateContent(finalRequest);
  }
  async generateContentStream(request, _userPromptId) {
    const finalRequest = {
      ...request,
      contents: this.stripUnsupportedFields(request.contents),
      config: this.buildGenerateContentConfig(request)
    };
    return this.googleGenAI.models.generateContentStream(finalRequest);
  }
  /**
   * Strip fields not supported by Gemini API (e.g., displayName in inlineData/fileData)
   */
  stripUnsupportedFields(contents) {
    if (!contents) return contents;
    if (typeof contents === "string") return contents;
    if (Array.isArray(contents)) {
      return contents.map(
        (content) => this.stripContentFields(content)
      );
    }
    return this.stripContentFields(
      contents
    );
  }
  stripContentFields(content) {
    if (typeof content === "string") {
      return content;
    }
    if (!("role" in content) && !("parts" in content)) {
      return this.stripPartFields(content);
    }
    const contentObj = content;
    if (!contentObj.parts) return contentObj;
    return {
      ...contentObj,
      parts: contentObj.parts.map((part) => this.stripPartFields(part))
    };
  }
  stripPartFields(part) {
    if (typeof part === "string") {
      return part;
    }
    const result = { ...part };
    if (result.inlineData) {
      const { displayName: _, ...inlineDataWithoutDisplayName } = result.inlineData;
      result.inlineData = inlineDataWithoutDisplayName;
    }
    if (result.fileData) {
      const { displayName: _, ...fileDataWithoutDisplayName } = result.fileData;
      result.fileData = fileDataWithoutDisplayName;
    }
    if (result.functionResponse?.parts) {
      const processedParts = result.functionResponse.parts.map((p) => {
        const converted = this.convertUnsupportedMediaToText(p);
        return this.stripPartFields(converted);
      });
      result.functionResponse = {
        ...result.functionResponse,
        parts: processedParts
      };
    }
    return result;
  }
  /**
   * Convert unsupported media types (audio, video) to explanatory text for Gemini API
   */
  convertUnsupportedMediaToText(part) {
    if (typeof part === "string") return part;
    const inlineMimeType = part.inlineData?.mimeType || "";
    const fileMimeType = part.fileData?.mimeType || "";
    if (inlineMimeType.startsWith("audio/") || inlineMimeType.startsWith("video/")) {
      const displayName = part.inlineData?.displayName;
      const displayNameText = displayName ? ` (${displayName})` : "";
      return {
        text: `Unsupported media type for Gemini: ${inlineMimeType}${displayNameText}.`
      };
    }
    if (fileMimeType.startsWith("audio/") || fileMimeType.startsWith("video/")) {
      const displayName = part.fileData?.displayName;
      const displayNameText = displayName ? ` (${displayName})` : "";
      return {
        text: `Unsupported media type for Gemini: ${fileMimeType}${displayNameText}.`
      };
    }
    return part;
  }
  async countTokens(request) {
    return this.googleGenAI.models.countTokens(request);
  }
  async embedContent(request) {
    return this.googleGenAI.models.embedContent(request);
  }
  useSummarizedThinking() {
    return true;
  }
};

// packages/core/src/core/geminiContentGenerator/index.ts
function createGeminiContentGenerator(config, gcConfig) {
  const version = "0.19.6";
  const userAgent = config.userAgent || `QwenCode/${version} (${process.platform}; ${process.arch})`;
  const baseHeaders = {
    "User-Agent": userAgent
  };
  let headers = { ...baseHeaders };
  if (gcConfig?.getUsageStatisticsEnabled()) {
    const installationManager = new InstallationManager();
    const installationId = installationManager.getInstallationId();
    headers = {
      ...headers,
      "x-gemini-api-privileged-user-id": `${installationId}`
    };
  }
  const httpOptions = config.baseUrl ? {
    headers,
    baseUrl: config.baseUrl
  } : { headers };
  const geminiContentGenerator = new GeminiContentGenerator(
    {
      apiKey: config.apiKey === "" ? void 0 : config.apiKey,
      vertexai: config.vertexai,
      httpOptions
    },
    config
  );
  return geminiContentGenerator;
}
__name(createGeminiContentGenerator, "createGeminiContentGenerator");
export {
  GeminiContentGenerator,
  createGeminiContentGenerator
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
