// src/model-resolution.ts
var DEFAULT_ROUTER_BASE_URL = "https://router.tangle.tools";
function resolveRouterBaseUrl(env = {}) {
  return (env.TANGLE_ROUTER_URL ?? env.TANGLE_ROUTER_BASE_URL ?? DEFAULT_ROUTER_BASE_URL).replace(/\/v1\/?$/, "").replace(/\/$/, "");
}
async function getModels(routerBaseUrl = DEFAULT_ROUTER_BASE_URL) {
  const res = await fetch(`${routerBaseUrl}/v1/models`, {
    headers: { Accept: "application/json" }
  });
  if (!res.ok) throw new Error(`router /v1/models ${res.status}`);
  const body = await res.json();
  return Array.isArray(body.data) ? body.data : [];
}
function cleanModelId(value) {
  if (typeof value !== "string") return void 0;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : void 0;
}
function resolveChatModel(candidates, fallback) {
  for (const candidate of candidates) {
    const model = cleanModelId(candidate.model);
    if (model) return { source: candidate.source, model };
  }
  return fallback;
}
var WELL_FORMED_MODEL_ID = /^[A-Za-z0-9._/@:-]+$/;
function isWellFormedModelId(modelId) {
  return modelId.length <= 200 && WELL_FORMED_MODEL_ID.test(modelId);
}
function catalogIdsForModel(model) {
  const ids = /* @__PURE__ */ new Set();
  const id = cleanModelId(model.id);
  if (id) ids.add(id);
  const provider = cleanModelId(model._provider) ?? cleanModelId(model.provider);
  if (provider && id && !id.includes("/")) ids.add(`${provider}/${id}`);
  return [...ids];
}
async function validateChatModelId(modelId, options = {}) {
  const {
    allowlist = [],
    routerBaseUrl = DEFAULT_ROUTER_BASE_URL,
    loadModels = getModels
  } = options;
  const cleaned = cleanModelId(modelId);
  if (!cleaned) return { succeeded: false, error: "Model id must be a non-empty string." };
  if (!isWellFormedModelId(cleaned)) {
    return { succeeded: false, error: `Model id is malformed: ${cleaned}` };
  }
  if (allowlist.some((id) => cleanModelId(id) === cleaned)) {
    return { succeeded: true, value: cleaned };
  }
  let catalog;
  try {
    catalog = await loadModels(routerBaseUrl);
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    return { succeeded: false, error: `Could not validate model catalog: ${message}` };
  }
  const ids = new Set(catalog.flatMap(catalogIdsForModel));
  if (!ids.has(cleaned)) return { succeeded: false, error: `Model is not available: ${cleaned}` };
  return { succeeded: true, value: cleaned };
}

export {
  DEFAULT_ROUTER_BASE_URL,
  resolveRouterBaseUrl,
  getModels,
  cleanModelId,
  resolveChatModel,
  validateChatModelId
};
//# sourceMappingURL=chunk-NURIQBJQ.js.map