// Force strict mode and setup for ESM
"use strict";
import {
  formatAcpModelId,
  getAuthTypeFromEnv,
  parseAcpBaseModelId,
  resolveCliGenerationConfig,
  sanitizeProviderBaseUrl
} from "./chunk-A76FGLIX.js";
import {
  loadSettings
} from "./chunk-AFPB2TZB.js";
import {
  STATUS_SCHEMA_VERSION
} from "./chunk-7MFZZRJS.js";
import {
  ModelsConfig,
  resolveProviderProtocol
} from "./chunk-IQ7FOOIH.js";
import {
  APPROVAL_MODES
} from "./chunk-LM3YCCZJ.js";
import {
  tokenLimit
} from "./chunk-KYTQOCDE.js";
import {
  createDebugLogger
} from "./chunk-AVQDCKNF.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/serve/workspace-providers-status.ts
init_esbuild_shims();
var debugLogger = createDebugLogger("WORKSPACE_PROVIDERS_STATUS");
function createWorkspaceProvidersStatusProvider(options = {}) {
  return async (workspaceCwd, acpChannelLive) => buildWorkspaceProvidersStatus(workspaceCwd, acpChannelLive, options);
}
__name(createWorkspaceProvidersStatusProvider, "createWorkspaceProvidersStatusProvider");
function buildWorkspaceProvidersStatus(workspaceCwd, acpChannelLive, options) {
  try {
    const loaded = loadSettings(workspaceCwd);
    const settings = loaded.merged;
    const env = options.env ?? process.env;
    const selectedAuthType = settings.security?.auth?.selectedType ?? getAuthTypeFromEnv();
    const argv = {
      model: options.argv?.model,
      openaiApiKey: options.argv?.openaiApiKey,
      openaiBaseUrl: options.argv?.openaiBaseUrl,
      openaiLogging: options.argv?.openaiLogging,
      openaiLoggingDir: options.argv?.openaiLoggingDir
    };
    const resolvedCliConfig = resolveCliGenerationConfig({
      argv,
      settings,
      selectedAuthType,
      env
    });
    const modelsConfig = new ModelsConfig({
      initialAuthType: selectedAuthType,
      modelProvidersConfig: settings.modelProviders,
      providerProtocolConfig: settings.providerProtocol,
      generationConfig: resolvedCliConfig.generationConfig,
      generationConfigSources: resolvedCliConfig.sources
    });
    const currentAuth = selectedAuthType;
    const currentModelId = (resolvedCliConfig.model || modelsConfig.getModel() || "").trim();
    const hasCurrentModel = currentModelId.length > 0;
    const currentAcpModelId = hasCurrentModel && currentAuth ? formatAcpModelId(currentModelId, currentAuth) : currentModelId || void 0;
    const currentBaseUrl = resolvedCliConfig.sources["baseUrl"] ? resolvedCliConfig.baseUrl || void 0 : void 0;
    const fastModelId = typeof settings.fastModel === "string" && settings.fastModel.length > 0 ? settings.fastModel : void 0;
    const visionModelId = typeof settings.visionModel === "string" && settings.visionModel.length > 0 ? settings.visionModel : void 0;
    const approvalMode = resolveApprovalMode(settings);
    const providers = /* @__PURE__ */ new Map();
    const explicitModelBaseUrls = buildExplicitModelBaseUrls(
      settings.modelProviders,
      settings.providerProtocol
    );
    for (const model of modelsConfig.getAllConfiguredModels().filter(isMainSelectableModel)) {
      if (model.isRuntimeModel) continue;
      const authType = String(model.authType);
      let provider = providers.get(authType);
      if (!provider) {
        provider = {
          kind: "model_provider",
          status: "ok",
          authType,
          current: false,
          models: []
        };
        providers.set(authType, provider);
      }
      const effectiveModelId = model.id;
      const modelId = formatAcpModelId(effectiveModelId, model.authType);
      const isCurrent = currentAuth === model.authType && hasCurrentModel && matchesCurrentModel(currentModelId, effectiveModelId, modelId) && matchesCurrentBaseUrl(
        currentBaseUrl,
        model.baseUrl,
        model.baseUrl !== void 0 && explicitModelBaseUrls.has(
          modelBaseUrlKey(authType, effectiveModelId, model.baseUrl)
        )
      );
      const providerModel = {
        modelId,
        baseModelId: parseAcpBaseModelId(effectiveModelId),
        name: model.label,
        ...model.description !== void 0 ? { description: model.description } : {},
        contextLimit: model.contextWindowSize ?? tokenLimit(effectiveModelId),
        ...model.modalities !== void 0 ? { modalities: model.modalities } : {},
        ...model.baseUrl !== void 0 ? { baseUrl: sanitizeProviderBaseUrl(model.baseUrl) } : {},
        ...model.envKey !== void 0 ? { envKey: model.envKey } : {},
        isCurrent,
        isRuntime: false
      };
      provider.models.push(providerModel);
      if (isCurrent) provider.current = true;
    }
    const current = buildCurrent(
      currentAuth,
      currentAcpModelId,
      currentBaseUrl,
      fastModelId,
      visionModelId
    );
    return {
      v: STATUS_SCHEMA_VERSION,
      workspaceCwd,
      initialized: true,
      acpChannelLive,
      ...current ? { current } : {},
      approvalMode,
      providers: [...providers.values()],
      ...resolvedCliConfig.warnings.length > 0 ? {
        errors: resolvedCliConfig.warnings.map((warning) => ({
          kind: "providers",
          status: "warning",
          error: sanitizeProviderWarning(warning)
        }))
      } : {}
    };
  } catch (error) {
    return {
      v: STATUS_SCHEMA_VERSION,
      workspaceCwd,
      initialized: false,
      acpChannelLive,
      providers: [],
      errors: [
        {
          kind: "providers",
          status: "error",
          error: sanitizeProviderWarning(
            error instanceof Error ? error.message : String(error)
          )
        }
      ]
    };
  }
}
__name(buildWorkspaceProvidersStatus, "buildWorkspaceProvidersStatus");
function resolveApprovalMode(settings) {
  const value = settings.tools?.approvalMode;
  if (typeof value !== "string") return "default" /* DEFAULT */;
  const normalized = value.trim().toLowerCase().replaceAll("_", "-");
  const mode = normalized === "autoedit" ? "auto-edit" /* AUTO_EDIT */ : normalized;
  if (APPROVAL_MODES.includes(mode)) {
    return mode;
  }
  if (value.trim().length > 0) {
    debugLogger.warn(
      `[workspace-providers-status] unrecognized approvalMode "${value}", falling back to default`
    );
  }
  return "default" /* DEFAULT */;
}
__name(resolveApprovalMode, "resolveApprovalMode");
function isMainSelectableModel(model) {
  return model.fastOnly !== true && model.voiceOnly !== true;
}
__name(isMainSelectableModel, "isMainSelectableModel");
function matchesCurrentModel(currentModelId, baseModelId, acpModelId) {
  return currentModelId === baseModelId || currentModelId === acpModelId;
}
__name(matchesCurrentModel, "matchesCurrentModel");
function matchesCurrentBaseUrl(currentBaseUrl, modelBaseUrl, modelHasExplicitBaseUrl) {
  if (!currentBaseUrl) return !modelHasExplicitBaseUrl;
  return currentBaseUrl === modelBaseUrl;
}
__name(matchesCurrentBaseUrl, "matchesCurrentBaseUrl");
function buildExplicitModelBaseUrls(modelProviders, providerProtocol) {
  const baseUrls = /* @__PURE__ */ new Set();
  if (!modelProviders) return baseUrls;
  for (const [providerId, providerConfig] of Object.entries(modelProviders)) {
    const authType = resolveProviderProtocol(providerId, providerProtocol);
    if (!authType) continue;
    const models = readProviderModels(providerConfig);
    for (const model of models) {
      if (typeof model.id === "string" && typeof model.baseUrl === "string" && model.baseUrl.length > 0) {
        baseUrls.add(modelBaseUrlKey(authType, model.id, model.baseUrl));
      }
    }
  }
  return baseUrls;
}
__name(buildExplicitModelBaseUrls, "buildExplicitModelBaseUrls");
function readProviderModels(providerConfig) {
  if (Array.isArray(providerConfig)) {
    return providerConfig.filter(isProviderModelBaseUrlConfig);
  }
  if (typeof providerConfig !== "object" || providerConfig === null) {
    return [];
  }
  const { models } = providerConfig;
  return Array.isArray(models) ? models.filter(isProviderModelBaseUrlConfig) : [];
}
__name(readProviderModels, "readProviderModels");
function isProviderModelBaseUrlConfig(value) {
  return typeof value === "object" && value !== null;
}
__name(isProviderModelBaseUrlConfig, "isProviderModelBaseUrlConfig");
function modelBaseUrlKey(authType, modelId, baseUrl) {
  return `${authType}\0${modelId}\0${baseUrl}`;
}
__name(modelBaseUrlKey, "modelBaseUrlKey");
var URL_LIKE_PATTERN = /\b[A-Za-z][A-Za-z\d+.-]*:\/\/[^\s'"`<>]+/g;
var URL_START_PATTERN = /\b[A-Za-z][A-Za-z\d+.-]*:\/\//g;
function sanitizeProviderWarning(warning) {
  let result = "";
  let index = 0;
  let next = findNextUrlStart(warning, index);
  while (next) {
    result += warning.slice(index, next.index);
    const segmentEnd = findUrlSegmentEnd(warning, next.index, next.marker);
    const segment = warning.slice(next.index, segmentEnd);
    result += sanitizeProviderWarningSegment(segment, next.marker.length);
    index = segmentEnd;
    next = findNextUrlStart(warning, index);
  }
  return result + warning.slice(index);
}
__name(sanitizeProviderWarning, "sanitizeProviderWarning");
function findNextUrlStart(value, from) {
  URL_START_PATTERN.lastIndex = from;
  const match = URL_START_PATTERN.exec(value);
  return match ? { index: match.index, marker: match[0] } : void 0;
}
__name(findNextUrlStart, "findNextUrlStart");
function findUrlSegmentEnd(value, start, marker) {
  const afterMarker = start + marker.length;
  const carriageReturn = value.indexOf("\r", afterMarker);
  const lineFeed = value.indexOf("\n", afterMarker);
  let lineEnd = value.length;
  if (carriageReturn !== -1) lineEnd = Math.min(lineEnd, carriageReturn);
  if (lineFeed !== -1) lineEnd = Math.min(lineEnd, lineFeed);
  const nextUrl = findNextUrlStart(value, afterMarker);
  return Math.min(lineEnd, nextUrl?.index ?? value.length);
}
__name(findUrlSegmentEnd, "findUrlSegmentEnd");
function sanitizeProviderWarningSegment(segment, markerLength) {
  const at = segment.indexOf("@", markerLength);
  if (at !== -1 && hasCredentialPrefix(segment, markerLength, at) && segment[at + 1] !== void 0 && /[A-Za-z0-9.[\]-]/.test(segment[at + 1])) {
    return `${segment.slice(0, markerLength)}${segment.slice(at + 1)}`;
  }
  return segment.replace(
    URL_LIKE_PATTERN,
    (url) => sanitizeProviderBaseUrl(url)
  );
}
__name(sanitizeProviderWarningSegment, "sanitizeProviderWarningSegment");
function hasCredentialPrefix(segment, markerLength, at) {
  const colon = segment.indexOf(":", markerLength);
  if (colon === -1 || colon > at) return false;
  const username = segment.slice(markerLength, colon);
  return !/[/?#\s'"`<>]/.test(username);
}
__name(hasCredentialPrefix, "hasCredentialPrefix");
function buildCurrent(authType, modelId, baseUrl, fastModelId, visionModelId) {
  if (!authType && !modelId && !baseUrl && !fastModelId && !visionModelId)
    return void 0;
  return {
    ...authType ? { authType: String(authType) } : {},
    ...modelId ? { modelId } : {},
    ...baseUrl ? { baseUrl: sanitizeProviderBaseUrl(baseUrl) } : {},
    ...fastModelId ? { fastModelId } : {},
    ...visionModelId ? { visionModelId } : {}
  };
}
__name(buildCurrent, "buildCurrent");

export {
  createWorkspaceProvidersStatusProvider
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
