// Force strict mode and setup for ESM
"use strict";
import {
  preloadRuntimeFetchModule
} from "./chunk-Q3T5KA2V.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/config/models.ts
init_esbuild_shims();
var DEFAULT_QWEN_MODEL = "coder-model";
var DEFAULT_QWEN_EMBEDDING_MODEL = "text-embedding-v4";
var MAINLINE_CODER_MODEL = "qwen3.7-max";

// packages/core/src/core/contentGenerator.ts
init_esbuild_shims();

// packages/core/src/models/modelConfigErrors.ts
init_esbuild_shims();
function getDefaultApiKeyEnvVar(authType) {
  switch (authType) {
    case "openai":
      return "OPENAI_API_KEY";
    case "anthropic":
      return "ANTHROPIC_API_KEY";
    case "gemini":
      return "GEMINI_API_KEY";
    case "vertex-ai":
      return "GOOGLE_API_KEY";
    default:
      return "API_KEY";
  }
}
__name(getDefaultApiKeyEnvVar, "getDefaultApiKeyEnvVar");
function getDefaultModelEnvVar(authType) {
  switch (authType) {
    case "openai":
      return "OPENAI_MODEL";
    case "anthropic":
      return "ANTHROPIC_MODEL";
    case "gemini":
      return "GEMINI_MODEL";
    case "vertex-ai":
      return "GOOGLE_MODEL";
    default:
      return "MODEL";
  }
}
__name(getDefaultModelEnvVar, "getDefaultModelEnvVar");
var ModelConfigError = class extends Error {
  static {
    __name(this, "ModelConfigError");
  }
  constructor(message) {
    super(message);
    this.name = new.target.name;
    Object.setPrototypeOf(this, new.target.prototype);
  }
};
var StrictMissingCredentialsError = class extends ModelConfigError {
  static {
    __name(this, "StrictMissingCredentialsError");
  }
  code = "STRICT_MISSING_CREDENTIALS";
  constructor(authType, model, envKey) {
    const providerKey = authType || "(unknown)";
    const modelName = model || "(unknown)";
    super(
      `Missing credentials for modelProviders model '${modelName}'. ` + (envKey ? `Current configured envKey: '${envKey}'. Set that environment variable, or update modelProviders.${providerKey}[].envKey.` : `Configure modelProviders.${providerKey}[].envKey and set that environment variable.`)
    );
  }
};
var StrictMissingModelIdError = class extends ModelConfigError {
  static {
    __name(this, "StrictMissingModelIdError");
  }
  code = "STRICT_MISSING_MODEL_ID";
  constructor(authType) {
    super(
      `Missing model id for strict modelProviders resolution (authType: ${authType}).`
    );
  }
};
var MissingApiKeyError = class extends ModelConfigError {
  static {
    __name(this, "MissingApiKeyError");
  }
  code = "MISSING_API_KEY";
  constructor(params) {
    super(
      `Missing API key for ${params.authType} auth. Current model: '${params.model || "(unknown)"}', baseUrl: '${params.baseUrl || "(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${params.envKey}'.`
    );
  }
};
var MissingModelError = class extends ModelConfigError {
  static {
    __name(this, "MissingModelError");
  }
  code = "MISSING_MODEL";
  constructor(params) {
    super(
      `Missing model for ${params.authType} auth. Set the environment variable '${params.envKey}'.`
    );
  }
};
var MissingBaseUrlError = class extends ModelConfigError {
  static {
    __name(this, "MissingBaseUrlError");
  }
  code = "MISSING_BASE_URL";
  constructor(params) {
    super(
      `Missing baseUrl for modelProviders model '${params.model || "(unknown)"}'. Configure modelProviders.${params.authType || "(unknown)"}[].baseUrl.`
    );
  }
};
var MissingAnthropicBaseUrlEnvError = class extends ModelConfigError {
  static {
    __name(this, "MissingAnthropicBaseUrlEnvError");
  }
  code = "MISSING_ANTHROPIC_BASE_URL_ENV";
  constructor() {
    super("ANTHROPIC_BASE_URL environment variable not found.");
  }
};

// packages/core/src/models/constants.ts
init_esbuild_shims();
var MODEL_GENERATION_CONFIG_FIELDS = [
  "samplingParams",
  "timeout",
  "maxRetries",
  "retryInitialDelayMs",
  "retryMaxDelayMs",
  "retryErrorCodes",
  "enableCacheControl",
  "forceGlobalCacheScope",
  "schemaCompliance",
  "reasoning",
  "contextWindowSize",
  "customHeaders",
  "extra_body",
  "thinkingMandatory",
  "modalities",
  "splitToolMedia",
  "toolResultContentFormat"
];
var CREDENTIAL_FIELDS = [
  "model",
  "apiKey",
  "apiKeyEnvKey",
  "baseUrl"
];
var PROVIDER_SOURCED_FIELDS = [
  ...CREDENTIAL_FIELDS,
  ...MODEL_GENERATION_CONFIG_FIELDS
];
var AUTH_ENV_MAPPINGS = {
  openai: {
    apiKey: ["OPENAI_API_KEY"],
    baseUrl: ["OPENAI_BASE_URL"],
    model: ["OPENAI_MODEL", "QWEN_MODEL"]
  },
  anthropic: {
    apiKey: ["ANTHROPIC_API_KEY"],
    baseUrl: ["ANTHROPIC_BASE_URL"],
    model: ["ANTHROPIC_MODEL"]
  },
  gemini: {
    apiKey: ["GEMINI_API_KEY"],
    baseUrl: [],
    model: ["GEMINI_MODEL"]
  },
  "vertex-ai": {
    apiKey: ["GOOGLE_API_KEY"],
    baseUrl: [],
    model: ["GOOGLE_MODEL"]
  },
  "qwen-oauth": {
    apiKey: [],
    baseUrl: [],
    model: []
  }
};
var DEFAULT_MODELS = {
  openai: MAINLINE_CODER_MODEL,
  "qwen-oauth": DEFAULT_QWEN_MODEL
};
var QWEN_OAUTH_MODELS = [
  {
    id: "coder-model",
    name: "coder-model",
    description: "Qwen 3.7 Max \u2014 efficient hybrid model with leading coding performance",
    capabilities: { vision: true }
  }
];
var QWEN_OAUTH_ALLOWED_MODELS = QWEN_OAUTH_MODELS.map(
  (model) => model.id
);

// packages/core/src/core/contentGenerator.ts
var AuthType = /* @__PURE__ */ ((AuthType2) => {
  AuthType2["USE_OPENAI"] = "openai";
  AuthType2["QWEN_OAUTH"] = "qwen-oauth";
  AuthType2["USE_GEMINI"] = "gemini";
  AuthType2["USE_VERTEX_AI"] = "vertex-ai";
  AuthType2["USE_ANTHROPIC"] = "anthropic";
  return AuthType2;
})(AuthType || {});
function setSource(sources, path, source) {
  sources[path] = source;
}
__name(setSource, "setSource");
function getSeedSource(seed, path) {
  return seed?.[path];
}
__name(getSeedSource, "getSeedSource");
function resolveContentGeneratorConfigWithSources(config, authType, generationConfig, seedSources, options) {
  const sources = { ...seedSources || {} };
  const strictModelProvider = options?.strictModelProvider === true;
  const newContentGeneratorConfig = {
    ...generationConfig || {},
    authType,
    proxy: config?.getProxy()
  };
  setSource(sources, "authType", {
    kind: "computed",
    detail: "provided by caller"
  });
  if (config?.getProxy()) {
    setSource(sources, "proxy", {
      kind: "computed",
      detail: "Config.getProxy()"
    });
  }
  const seedOrUnknown = /* @__PURE__ */ __name((path) => getSeedSource(seedSources, path) ?? { kind: "unknown" }, "seedOrUnknown");
  for (const field of PROVIDER_SOURCED_FIELDS) {
    if (generationConfig && field in generationConfig && !sources[field]) {
      setSource(sources, field, seedOrUnknown(field));
    }
  }
  const validation = validateModelConfig(
    newContentGeneratorConfig,
    strictModelProvider
  );
  if (!validation.valid) {
    throw new Error(validation.errors.map((e) => e.message).join("\n"));
  }
  return {
    config: newContentGeneratorConfig,
    sources
  };
}
__name(resolveContentGeneratorConfigWithSources, "resolveContentGeneratorConfigWithSources");
function validateModelConfig(config, isStrictModelProvider = false) {
  const errors = [];
  if (config.authType === "qwen-oauth" /* QWEN_OAUTH */) {
    return { valid: true, errors: [] };
  }
  if (!config.apiKey) {
    if (isStrictModelProvider) {
      errors.push(
        new StrictMissingCredentialsError(
          config.authType,
          config.model,
          config.apiKeyEnvKey
        )
      );
    } else {
      const envKey = config.apiKeyEnvKey || getDefaultApiKeyEnvVar(config.authType);
      errors.push(
        new MissingApiKeyError({
          authType: config.authType,
          model: config.model,
          baseUrl: config.baseUrl,
          envKey
        })
      );
    }
  }
  if (!config.model) {
    if (isStrictModelProvider) {
      errors.push(new StrictMissingModelIdError(config.authType));
    } else {
      const envKey = getDefaultModelEnvVar(config.authType);
      errors.push(new MissingModelError({ authType: config.authType, envKey }));
    }
  }
  if (config.authType === "anthropic" /* USE_ANTHROPIC */ && !config.baseUrl) {
    if (isStrictModelProvider) {
      errors.push(
        new MissingBaseUrlError({
          authType: config.authType,
          model: config.model
        })
      );
    } else if (config.authType === "anthropic" /* USE_ANTHROPIC */) {
      errors.push(new MissingAnthropicBaseUrlEnvError());
    }
  }
  return { valid: errors.length === 0, errors };
}
__name(validateModelConfig, "validateModelConfig");
function getModuleNotFoundError(error) {
  let current = error;
  while (current instanceof Error) {
    if ("code" in current && current.code === "ERR_MODULE_NOT_FOUND") {
      return current;
    }
    current = current.cause;
  }
  return void 0;
}
__name(getModuleNotFoundError, "getModuleNotFoundError");
function wrapProviderLoadError(error, authType) {
  const moduleNotFoundError = getModuleNotFoundError(error);
  if (!moduleNotFoundError) {
    return error;
  }
  return new Error(
    `Qwen Code was updated in the background and needs to be restarted.
Please exit and restart Qwen Code to use the '${authType}' provider.`,
    { cause: moduleNotFoundError }
  );
}
__name(wrapProviderLoadError, "wrapProviderLoadError");
var LazyContentGenerator = class {
  constructor(loader, summarizedThinking) {
    this.loader = loader;
    this.summarizedThinking = summarizedThinking;
  }
  static {
    __name(this, "LazyContentGenerator");
  }
  generatorPromise;
  preloadedOnly = false;
  getGenerator() {
    this.generatorPromise ??= this.loader();
    return this.generatorPromise;
  }
  getGeneratorForUse() {
    this.preloadedOnly = false;
    return this.getGenerator();
  }
  preload() {
    if (!this.generatorPromise) {
      this.preloadedOnly = true;
    }
    return this.getGenerator();
  }
  resetPreload() {
    if (!this.preloadedOnly) return;
    this.preloadedOnly = false;
    this.generatorPromise = void 0;
  }
  async generateContent(request, userPromptId) {
    return (await this.getGeneratorForUse()).generateContent(
      request,
      userPromptId
    );
  }
  async generateContentStream(request, userPromptId) {
    return (await this.getGeneratorForUse()).generateContentStream(
      request,
      userPromptId
    );
  }
  async countTokens(request) {
    return (await this.getGeneratorForUse()).countTokens(request);
  }
  async embedContent(request) {
    return (await this.getGeneratorForUse()).embedContent(request);
  }
  useSummarizedThinking() {
    return this.summarizedThinking;
  }
};
async function preloadContentGenerator(generator) {
  if (generator instanceof LazyContentGenerator) {
    await generator.preload();
  }
}
__name(preloadContentGenerator, "preloadContentGenerator");
function resetPreloadedContentGenerator(generator) {
  if (generator instanceof LazyContentGenerator) {
    generator.resetPreload();
  }
}
__name(resetPreloadedContentGenerator, "resetPreloadedContentGenerator");
async function createContentGenerator(generatorConfig, config, isInitialAuth) {
  const validation = validateModelConfig(generatorConfig, false);
  if (!validation.valid) {
    throw new Error(validation.errors.map((e) => e.message).join("\n"));
  }
  const authType = generatorConfig.authType;
  if (!authType) {
    throw new Error("ContentGeneratorConfig must have an authType");
  }
  await preloadRuntimeFetchModule();
  let loadBaseGenerator;
  try {
    if (authType === "openai" /* USE_OPENAI */) {
      loadBaseGenerator = /* @__PURE__ */ __name(async () => {
        const { createOpenAIContentGenerator } = await import("./openaiContentGenerator-2VEZSO5Z.js");
        return createOpenAIContentGenerator(generatorConfig, config);
      }, "loadBaseGenerator");
    } else if (authType === "qwen-oauth" /* QWEN_OAUTH */) {
      const { getQwenOAuthClient: getQwenOauthClient } = await import("./qwenOAuth2-NCGXU7XR.js");
      try {
        const qwenClient = await getQwenOauthClient(
          config,
          isInitialAuth ? { requireCachedCredentials: true } : void 0
        );
        loadBaseGenerator = /* @__PURE__ */ __name(async () => {
          const { QwenContentGenerator } = await import("./qwenContentGenerator-MISBKINV.js");
          return new QwenContentGenerator(qwenClient, generatorConfig, config);
        }, "loadBaseGenerator");
      } catch (error) {
        if (getModuleNotFoundError(error)) {
          throw error;
        }
        throw new Error(error instanceof Error ? error.message : String(error));
      }
    } else if (authType === "anthropic" /* USE_ANTHROPIC */) {
      loadBaseGenerator = /* @__PURE__ */ __name(async () => {
        const { createAnthropicContentGenerator } = await import("./anthropicContentGenerator-OFHSZJBF.js");
        return createAnthropicContentGenerator(generatorConfig, config);
      }, "loadBaseGenerator");
    } else if (authType === "gemini" /* USE_GEMINI */ || authType === "vertex-ai" /* USE_VERTEX_AI */) {
      loadBaseGenerator = /* @__PURE__ */ __name(async () => {
        const { createGeminiContentGenerator } = await import("./geminiContentGenerator-ZZX6NBO4.js");
        return createGeminiContentGenerator(generatorConfig, config);
      }, "loadBaseGenerator");
    } else {
      throw new Error(
        `Error creating contentGenerator: Unsupported authType: ${authType}`
      );
    }
  } catch (error) {
    throw wrapProviderLoadError(error, authType);
  }
  return new LazyContentGenerator(
    async () => {
      try {
        const [baseGenerator, { LoggingContentGenerator }] = await Promise.all([
          loadBaseGenerator(),
          import("./loggingContentGenerator-7FNZ42PN.js")
        ]);
        return new LoggingContentGenerator(
          baseGenerator,
          config,
          generatorConfig
        );
      } catch (error) {
        throw wrapProviderLoadError(error, authType);
      }
    },
    authType === "gemini" /* USE_GEMINI */ || authType === "vertex-ai" /* USE_VERTEX_AI */
  );
}
__name(createContentGenerator, "createContentGenerator");

export {
  DEFAULT_QWEN_MODEL,
  DEFAULT_QWEN_EMBEDDING_MODEL,
  MAINLINE_CODER_MODEL,
  MODEL_GENERATION_CONFIG_FIELDS,
  PROVIDER_SOURCED_FIELDS,
  AUTH_ENV_MAPPINGS,
  DEFAULT_MODELS,
  QWEN_OAUTH_MODELS,
  QWEN_OAUTH_ALLOWED_MODELS,
  AuthType,
  resolveContentGeneratorConfigWithSources,
  preloadContentGenerator,
  resetPreloadedContentGenerator,
  createContentGenerator
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
