Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

35.8 KB
Raw Blame
import { getAntigravityModelsDiscoveryUrls } from "@omniroute/open-sse/config/antigravityUpstream.ts";
import {
  getGrokBuildModelsHeaders,
  GROK_BUILD_MODELS_URL,
  GROK_BUILD_SUPPORTED_REASONING_EFFORTS,
} from "@omniroute/open-sse/config/grokBuild.ts";
import { grok_cliProvider } from "@omniroute/open-sse/config/providers/registry/grok-cli/index.ts";
import { getAntigravityContentHeaders } from "@omniroute/open-sse/services/antigravityHeaders.ts";
import { parseGeminiModelsList } from "@/lib/providerModels/geminiModelsParser";
import { buildClaudeModelsHeaders } from "@/lib/providerModels/claudeModelsHeaders";
import {
  CLINE_MODELS_ENDPOINT,
  CLINEPASS_MODELS_ENDPOINT,
  parseClineModels,
  parseClinepassRecommendedModels,
} from "@omniroute/open-sse/services/clinepassModels.ts";
import { buildClaudeCodeCompatibleHeaders } from "@omniroute/open-sse/services/claudeCodeCompatible.ts";
import {
  buildKimiCodeIdentityHeaders,
  getKimiCodeCliUserAgent,
  KIMI_CODING_MODELS_URL,
} from "@omniroute/open-sse/config/providers/registry/kimi/coding/runtime.ts";
import { ALIBABA_MODEL_STUDIO_MODELS } from "@omniroute/open-sse/config/providers/registry/alibaba/index.ts";
import { QWEN_CLOUD_TEXT_MODELS } from "@omniroute/open-sse/config/providers/registry/qwen-cloud/index.ts";
import { filterAlibabaFreeEligibleModels } from "@omniroute/open-sse/services/alibabaFreeTierDiscovery.ts";
import { shouldUseLiveAlibabaFreeModelDiscovery } from "@omniroute/open-sse/services/alibabaFreeTier.ts";
import { isDashscopeTextModelId } from "@omniroute/open-sse/services/dashscopeTextModels.ts";
import { extractZaiToken } from "@omniroute/open-sse/services/zaiWebCredentials.ts";
import { buildOpencodeBackgroundHeaders } from "@omniroute/open-sse/utils/opencodeHeaders.ts";
import { isFeatureFlagEnabled } from "@/shared/utils/featureFlags";
import { applyConnectionCustomHeaders } from "./connectionCustomHeaders";
import { buildChatPlaygroundModelsDiscoveryEntry } from "@omniroute/open-sse/services/chatplaygroundModels.ts";
import { normalizeOpenAiLikeModelsResponse, normalizeWorkbuddyModelsResponse } from "./normalizers";

const QWEN_CLOUD_TEXT_MODEL_IDS = new Set(QWEN_CLOUD_TEXT_MODELS.map((model) => model.id));
const ALIBABA_MODEL_STUDIO_MODEL_IDS = new Set(
  ALIBABA_MODEL_STUDIO_MODELS.map((model) => model.id)
);

export { isDashscopeTextModelId };

export function parseDashscopeTextModels(data: any): any[] {
  const models = Array.isArray(data?.data)
    ? data.data
    : Array.isArray(data?.models)
      ? data.models
      : [];
  return models.filter((model: any) => isDashscopeTextModelId(model?.id));
}

function parseCuratedDashscopeModels(
  data: any,
  catalogModels: typeof ALIBABA_MODEL_STUDIO_MODELS,
  allowedModelIds: ReadonlySet<string>
): any[] {
  const liveModelsById = new Map(
    parseDashscopeTextModels(data)
      .filter((model: any) => allowedModelIds.has(model.id))
      .map((model: any) => [model.id, model])
  );
  return catalogModels.flatMap((catalogModel) => {
    const liveModel = liveModelsById.get(catalogModel.id);
    return liveModel ? [liveModel] : [];
  });
}

export function parseAlibabaModelStudioModels(data: any): any[] {
  return parseCuratedDashscopeModels(
    data,
    ALIBABA_MODEL_STUDIO_MODELS,
    ALIBABA_MODEL_STUDIO_MODEL_IDS
  );
}

export function parseAlibabaModelStudioModelsForConnection(
  data: any,
  providerSpecificData?: Record<string, unknown> | null
): any[] {
  if (shouldUseLiveAlibabaFreeModelDiscovery(providerSpecificData)) {
    const models = parseDashscopeTextModels(data);
    const eligibleIds = new Set(
      filterAlibabaFreeEligibleModels(
        models.map((model: { id?: string }) => model.id).filter(Boolean) as string[],
        providerSpecificData
      )
    );
    return models.filter((model: { id?: string }) => model.id && eligibleIds.has(model.id));
  }
  return parseAlibabaModelStudioModels(data);
}

export function parseQwenCloudTextModels(data: any): any[] {
  return parseCuratedDashscopeModels(data, QWEN_CLOUD_TEXT_MODELS, QWEN_CLOUD_TEXT_MODEL_IDS);
}

// Perplexity's /v1/models lists the Agent API catalog (vendor-prefixed ids like
// "anthropic/claude-fable-5"), but chat requests always go to the classic
// /chat/completions endpoint, which only accepts the Sonar family. Filter
// discovery to Sonar-family ids so agent-style ids never surface as routable
// chat models (#11060). Bounded pattern — no ReDoS-prone quantifiers.
export function parsePerplexitySonarModels(data: any): any[] {
  const models = Array.isArray(data?.data)
    ? data.data
    : Array.isArray(data?.models)
      ? data.models
      : [];
  return models.filter(
    (model: any) => typeof model?.id === "string" && /^sonar(-|$)/.test(model.id)
  );
}
export type ProviderModelsHeaderContext = {
  id?: string;
  authType?: string;
  providerSpecificData?: unknown;
  email?: string | null;
  accessToken?: string | null;
  apiKey?: string | null;
};

export type ProviderModelsConfigEntry = {
  url: string;
  method: "GET" | "POST";
  headers: Record<string, string>;
  authHeader?: string;
  authPrefix?: string;
  authQuery?: string;
  body?: unknown;
  buildHeaders?: (
    token: string,
    connection?: ProviderModelsHeaderContext
  ) => Record<string, string>;
  parseResponse: (data: any) => any;
};

export function assembleProviderModelsHeaders(
  config: ProviderModelsConfigEntry,
  token: string,
  context?: ProviderModelsHeaderContext
): Record<string, string> {
  const headers = config.buildHeaders ? config.buildHeaders(token, context) : { ...config.headers };
  if (!config.buildHeaders && config.authHeader && !config.authQuery) {
    headers[config.authHeader] = (config.authPrefix || "") + token;
  }
  applyConnectionCustomHeaders(headers, context?.providerSpecificData);
  return headers;
}

const DASHSCOPE_TEXT_MODELS_CONFIG: ProviderModelsConfigEntry = {
  url: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",
  method: "GET",
  headers: { "Content-Type": "application/json" },
  authHeader: "Authorization",
  authPrefix: "Bearer ",
  parseResponse: parseDashscopeTextModels,
};

const ALIBABA_MODEL_STUDIO_MODELS_CONFIG: ProviderModelsConfigEntry = {
  ...DASHSCOPE_TEXT_MODELS_CONFIG,
  parseResponse: parseAlibabaModelStudioModels,
};

const QWEN_CLOUD_TEXT_MODELS_CONFIG: ProviderModelsConfigEntry = {
  ...DASHSCOPE_TEXT_MODELS_CONFIG,
  parseResponse: parseQwenCloudTextModels,
};

function getKimiThinkingType(model: any): "only" | "both" | "no" | undefined {
  return model.supports_thinking_type === "only" ||
    model.supports_thinking_type === "both" ||
    model.supports_thinking_type === "no"
    ? model.supports_thinking_type
    : undefined;
}

function getKimiThinkingEfforts(model: any): {
  supportedThinkingEfforts?: string[];
  defaultThinkingEffort?: string;
} {
  const efforts = model.think_efforts;
  const supportedThinkingEfforts =
    efforts?.support === true && Array.isArray(efforts.valid_efforts)
      ? efforts.valid_efforts.filter(
          (effort: unknown): effort is string => typeof effort === "string" && effort.length > 0
        )
      : undefined;
  const defaultThinkingEffort =
    efforts?.support === true && typeof efforts.default_effort === "string"
      ? efforts.default_effort
      : undefined;
  return { supportedThinkingEfforts, defaultThinkingEffort };
}

function normalizeKimiCodingModel(model: any): any {
  const thinkingType = getKimiThinkingType(model);
  const supportsThinking = thinkingType ? thinkingType !== "no" : model.supports_reasoning === true;
  const { supportedThinkingEfforts, defaultThinkingEffort } = getKimiThinkingEfforts(model);
  const isAnthropic = model.protocol === "anthropic";
  const normalized: any = {
    id: model.id,
    name:
      typeof model.display_name === "string" && model.display_name.length > 0
        ? model.display_name
        : model.id,
    owned_by: "kimi-code",
    targetFormat: isAnthropic ? "claude" : "openai",
    upstreamProtocol: isAnthropic ? "anthropic" : "kimi",
    supportsThinking,
    supportsVision: model.supports_image_in === true,
    supportsVideo: model.supports_video_in === true,
    supportsTools: model.supports_tool_use !== false,
  };

  if (typeof model.context_length === "number") normalized.context_length = model.context_length;
  if (thinkingType === "only") normalized.alwaysThinking = true;
  if (supportedThinkingEfforts?.length) {
    normalized.supportedThinkingEfforts = supportedThinkingEfforts;
  }
  if (defaultThinkingEffort) normalized.defaultThinkingEffort = defaultThinkingEffort;
  return normalized;
}

export function parseKimiCodingModels(data: any): any[] {
  const models = Array.isArray(data?.data)
    ? data.data
    : Array.isArray(data?.models)
      ? data.models
      : [];

  return models
    .filter((model: any) => typeof model?.id === "string" && model.id.length > 0)
    .map(normalizeKimiCodingModel);
}

type GrokBuildModelRecord = Record<string, unknown>;

function asGrokBuildRecord(value: unknown): GrokBuildModelRecord {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as GrokBuildModelRecord)
    : {};
}

function grokBuildString(...values: unknown[]): string | undefined {
  return values
    .find((value): value is string => typeof value === "string" && value.trim().length > 0)
    ?.trim();
}

function grokBuildPositiveNumber(...values: unknown[]): number | undefined {
  return values.find(
    (value): value is number => typeof value === "number" && Number.isFinite(value) && value > 0
  );
}

const GROK_CLI_REGISTRY_CONTEXT_BY_ID = new Map<string, number>(
  grok_cliProvider.models.flatMap((model) => {
    const window = model.contextLength;
    return typeof window === "number" && Number.isInteger(window) && window > 0
      ? ([[model.id, window]] as Array<[string, number]>)
      : [];
  })
);

function resolveGrokBuildInputTokenLimit(
  model: GrokBuildModelRecord,
  metadata: GrokBuildModelRecord,
  id: string
): number | undefined {
  // Registry first. Grok Build's /v1/models advertises contextWindow 256000 for every
  // model, yet the backend serves grok-4.6 up to 500k (prod: 88 successful requests
  // with 256k-485k input; upstream rejects at "> 500000 tokens"). Trusting the
  // advertised number pinned 256k auto:discovery overrides over the verified window.
  // Models the registry does not know keep the upstream number — under-advertising
  // only makes clients compact early — and never get an invented default.
  return (
    GROK_CLI_REGISTRY_CONTEXT_BY_ID.get(id) ??
    grokBuildPositiveNumber(
      model.contextWindow,
      model.context_window,
      metadata.contextWindow,
      metadata.totalContextTokens
    )
  );
}

function getGrokBuildModelItems(data: unknown): unknown[] {
  const envelope = asGrokBuildRecord(data);
  if (Array.isArray(data)) return data;
  if (Array.isArray(envelope.data)) return envelope.data;
  return Array.isArray(envelope.models) ? envelope.models : [];
}

function hasGrokBuildReasoning(
  model: GrokBuildModelRecord,
  metadata: GrokBuildModelRecord
): boolean {
  const flags = [
    model.supportsReasoningEffort,
    model.supports_reasoning_effort,
    metadata.supportsReasoningEffort,
    metadata.supports_reasoning_effort,
  ];
  const effortLists = [
    model.reasoningEfforts,
    model.reasoning_efforts,
    metadata.reasoningEfforts,
    metadata.reasoning_efforts,
  ];
  return (
    flags.some((value) => value === true) ||
    grokBuildString(
      model.reasoningEffort,
      model.reasoning_effort,
      metadata.reasoningEffort,
      metadata.reasoning_effort
    ) !== undefined ||
    effortLists.some((value) => Array.isArray(value) && value.length > 0)
  );
}

function getGrokBuildReasoningEfforts(
  model: GrokBuildModelRecord,
  metadata: GrokBuildModelRecord
): string[] {
  const supported = new Set(GROK_BUILD_SUPPORTED_REASONING_EFFORTS);
  const effortLists = [
    model.reasoningEfforts,
    model.reasoning_efforts,
    metadata.reasoningEfforts,
    metadata.reasoning_efforts,
  ];
  const hasExplicitEffortList = effortLists.some((value) => Array.isArray(value));
  const discovered = effortLists
    .flatMap((value) => (Array.isArray(value) ? value : []))
    .map((value) => {
      if (typeof value === "string") return value;
      if (value && typeof value === "object") {
        const record = value as { value?: unknown; id?: unknown };
        const named = typeof record.value === "string" ? record.value.trim() : "";
        if (named) return named;
        return typeof record.id === "string" ? record.id : "";
      }
      return "";
    })
    .map((value) => value.trim().toLowerCase())
    .filter((value) => supported.has(value));
  if (hasExplicitEffortList) return [...new Set(discovered)];

  const singleEffort = grokBuildString(
    model.reasoningEffort,
    model.reasoning_effort,
    metadata.reasoningEffort,
    metadata.reasoning_effort
  )?.toLowerCase();
  if (singleEffort && supported.has(singleEffort)) return [singleEffort];
  // No list in the payload. The boolean only proves reasoning exists.
  // grok-4.5 advertises low/medium/high. xhigh is kept only when named.
  return hasGrokBuildReasoning(model, metadata) ? ["low", "medium", "high"] : [];
}

function normalizeGrokBuildModel(value: unknown): GrokBuildModelRecord | null {
  const model = asGrokBuildRecord(value);
  const metadata = asGrokBuildRecord(model._meta);
  const catalogId = grokBuildString(model.id);
  const id = grokBuildString(
    model.model,
    model.modelId,
    catalogId,
    metadata.model,
    metadata.modelId
  );
  const hidden = model.hidden === true || metadata.hidden === true;
  // grok-cli always uses OAuth session auth. Official Grok Build visibility
  // keeps supported_in_api=false models available to session users and only
  // hides them from API-key users.
  if (!id || hidden) return null;

  const backend = grokBuildString(
    model.apiBackend,
    model.api_backend,
    metadata.apiBackend,
    metadata.api_backend
  );
  // This provider currently executes against /v1/responses. Grok Build can
  // advertise chat_completions or messages backends too, but exposing those
  // here would route their request shape to the wrong upstream endpoint.
  if (backend !== "responses") return null;

  const inputTokenLimit = resolveGrokBuildInputTokenLimit(model, metadata, id);
  const outputTokenLimit = grokBuildPositiveNumber(
    model.maxCompletionTokens,
    model.max_completion_tokens
  );
  const description = grokBuildString(model.description);
  const supportsThinking = hasGrokBuildReasoning(model, metadata);
  const supportedThinkingEfforts = getGrokBuildReasoningEfforts(model, metadata);

  return {
    id,
    name: grokBuildString(model.name, id) || id,
    owned_by: "grok-cli",
    ...(description ? { description } : {}),
    ...(typeof inputTokenLimit === "number" ? { inputTokenLimit } : {}),
    ...(outputTokenLimit ? { outputTokenLimit } : {}),
    ...(supportsThinking ? { supportsThinking: true } : {}),
    ...(supportedThinkingEfforts.length > 0 ? { supportedThinkingEfforts } : {}),
    apiFormat: "responses",
    supportedEndpoints: ["responses"],
  };
}

function parseGrokBuildModels(data: unknown): GrokBuildModelRecord[] {
  return getGrokBuildModelItems(data)
    .map(normalizeGrokBuildModel)
    .filter((model): model is GrokBuildModelRecord => model !== null);
}

const KIMI_CODING_MODELS_CONFIG: ProviderModelsConfigEntry = {
  url: KIMI_CODING_MODELS_URL,
  method: "GET",
  headers: { Accept: "application/json" },
  buildHeaders: (token, connection) => {
    if (connection?.authType === "apikey" || connection?.authType === "api_key") {
      return {
        Accept: "application/json",
        "x-api-key": token,
      };
    }

    return {
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
      "User-Agent": getKimiCodeCliUserAgent(),
      ...buildKimiCodeIdentityHeaders(connection?.providerSpecificData || {}),
    };
  },
  parseResponse: parseKimiCodingModels,
};

const OPENCODE_DISCOVERY_PARSE = (data: any) => data.data || data.models || [];

/**
 * Stable background-identity seed for one connection. Prefers the workspace id
 * (all three spellings the providerSpecificData validator accepts) so
 * connections sharing a workspace group under one upstream identity, then
 * falls back to the connection id so a workspace-less connection still gets a
 * deterministic session instead of a fresh anonymous UUID per discovery call.
 */
function readOpencodeBackgroundSeed(connection?: ProviderModelsHeaderContext): string | null {
  const psd = connection?.providerSpecificData;
  if (psd && typeof psd === "object") {
    const record = psd as Record<string, unknown>;
    for (const key of ["openCodeGoWorkspaceId", "opencodeGoWorkspaceId", "workspaceId"] as const) {
      const value = record[key];
      if (typeof value === "string" && value.trim().length > 0) return value.trim();
    }
  }
  const id = connection?.id;
  return typeof id === "string" && id.trim().length > 0 ? id.trim() : null;
}

/**
 * Discovery entry for the opencode-family providers with the OpenCode CLI
 * identity headers attached (User-Agent + x-opencode-session/request/client/
 * project). Bare runtime fetches (UA "Bun fetch", no session header) are
 * exactly the shape OpenCode's operator warning names — enforcement of the
 * header is announced from 2026-09-06. The session id is a stable
 * per-workspace/connection fingerprint so background discovery groups under
 * one identity upstream instead of a fresh anonymous client per call.
 */
function buildOpencodeModelsDiscoveryEntry(url: string): ProviderModelsConfigEntry {
  return {
    url,
    method: "GET",
    headers: { Accept: "application/json" },
    buildHeaders: (token, connection) => ({
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
      ...buildOpencodeBackgroundHeaders({ seed: readOpencodeBackgroundSeed(connection) }),
    }),
    parseResponse: OPENCODE_DISCOVERY_PARSE,
  };
}
// Also used, behind the XAI_OAUTH_LIVE_MODEL_DISCOVERY flag, to fetch a live
// catalog for xai-oauth (see getXaiOauthLiveModelsConfig below). Whether x.ai
// accepts an OAuth bearer at this endpoint is unverified — that is why
// xai-oauth is not registered in PROVIDER_MODELS_CONFIG below and stays on
// its frozen static seed (open-sse/config/providers/registry/xai/index.ts)
// unless the flag is explicitly turned on.
// x.ai /v1/models lists Grok Imagine media models next to the chat models without a
// type field. Tag them so they stay out of chat catalogs and auto/* pools.
function tagXaiMediaModel(model: unknown) {
  if (!model || typeof model !== "object") return model;
  const id = typeof (model as { id?: unknown }).id === "string" ? (model as { id: string }).id : "";
  if (/^grok-imagine-image/i.test(id)) {
    return { ...model, supportedEndpoints: ["images"], modelType: "image" };
  }
  if (/^grok-imagine-video/i.test(id)) return { ...model, supportedEndpoints: ["videos"] };
  return model;
}

export const XAI_MODELS_CONFIG: ProviderModelsConfigEntry = {
  url: "https://api.x.ai/v1/models",
  method: "GET",
  headers: { "Content-Type": "application/json" },
  authHeader: "Authorization",
  authPrefix: "Bearer ",
  parseResponse: (data) => {
    const models = data.data || data.models || [];
    return Array.isArray(models) ? models.map(tagXaiMediaModel) : models;
  },
};

/**
 * Resolve the live-discovery config for xai-oauth when the
 * XAI_OAUTH_LIVE_MODEL_DISCOVERY flag is on, or `undefined` when it is off
 * (or its resolution throws) so the caller falls back to the frozen static
 * seed — the flag defaults to "true" and fails closed on any error.
 */
export function getXaiOauthLiveModelsConfig(): ProviderModelsConfigEntry | undefined {
  try {
    return isFeatureFlagEnabled("XAI_OAUTH_LIVE_MODEL_DISCOVERY") ? XAI_MODELS_CONFIG : undefined;
  } catch {
    return undefined;
  }
}

// Provider models endpoints configuration
export const PROVIDER_MODELS_CONFIG: Record<string, ProviderModelsConfigEntry> = {
  alibaba: ALIBABA_MODEL_STUDIO_MODELS_CONFIG,
  "alibaba-cn": ALIBABA_MODEL_STUDIO_MODELS_CONFIG,
  claude: {
    url: "https://api.anthropic.com/v1/models?limit=1000",
    method: "GET",
    headers: {
      "anthropic-version": "2023-06-01",
      "Content-Type": "application/json",
    },
    buildHeaders: (_token, context) =>
      buildClaudeModelsHeaders({
        accessToken: context?.accessToken,
        apiKey: context?.apiKey,
      }),
    parseResponse: (data) => data.data || [],
  },
  gemini: {
    url: "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authQuery: "key", // Use query param for API key
    parseResponse: (data) => parseGeminiModelsList(data),
  },
  huggingface: {
    url: "https://router.huggingface.co/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => normalizeOpenAiLikeModelsResponse(data, "huggingface"),
  },
  "qwen-cloud": QWEN_CLOUD_TEXT_MODELS_CONFIG,
  antigravity: {
    url: getAntigravityModelsDiscoveryUrls()[0],
    method: "POST",
    headers: getAntigravityContentHeaders("ide"),
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    body: {},
    parseResponse: (data) => data.models || [],
  },
  // #7016: AgentRouter rejects /v1/models unless the request carries the same
  // Claude Code wire image the chat path uses (it adopts the dynamic CC wire
  // image while keeping its own x-api-key auth — see #6056). Without these
  // headers the gateway WAF 4xx's the request and model import silently falls
  // back to the local catalog ("API unavailable — using local catalog").
  agentrouter: {
    url: "https://agentrouter.org/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    buildHeaders: (token: string) => {
      const wire = buildClaudeCodeCompatibleHeaders(token, false, undefined, {});
      const out: Record<string, string> = { ...wire };
      // Keep AgentRouter's own x-api-key auth scheme (#6056); the CC helper
      // adds a Bearer Authorization we must not send.
      for (const key of Object.keys(out)) {
        if (key.toLowerCase() === "authorization") delete out[key];
      }
      if (token) out["x-api-key"] = token;
      return out;
    },
    parseResponse: (data: any) => (Array.isArray(data) ? data : data?.data || data?.models || []),
  },
  openai: {
    url: "https://api.openai.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || [],
  },
  "grok-cli": {
    url: GROK_BUILD_MODELS_URL,
    method: "GET",
    headers: {},
    buildHeaders: (token, context) => {
      const providerData = asGrokBuildRecord(context?.providerSpecificData);
      return getGrokBuildModelsHeaders({
        token,
        userId: grokBuildString(providerData.userId),
        email: grokBuildString(context?.email, providerData.email),
        principalType: grokBuildString(providerData.principalType),
      });
    },
    parseResponse: parseGrokBuildModels,
  },
  openrouter: {
    url: "https://openrouter.ai/api/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || [],
  },
  aimlapi: {
    // #5570: AI/ML API's live catalog (400+ models) lives at the public,
    // auth-free /models database endpoint (NOT /v1/models). The registry has no
    // modelsUrl, so without this entry the route fell back to a stale 6-model
    // seed. Response is a bare array of { id, type, info: { name } }.
    url: "https://api.aimlapi.com/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    parseResponse: (data) => {
      const all = Array.isArray(data) ? data : [];
      const chat = all.filter((m) => m?.type === "chat-completion");
      return (chat.length > 0 ? chat : all)
        .map((m) => ({ id: m?.id, name: m?.info?.name || m?.id }))
        .filter((m) => typeof m.id === "string" && m.id);
    },
  },
  thebai: {
    url: "https://api.theb.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  fenayai: {
    url: "https://fenayai.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  chutes: {
    url: "https://llm.chutes.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  clarifai: {
    url: "https://api.clarifai.com/v2/ext/openai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Key ",
    parseResponse: (data) => normalizeOpenAiLikeModelsResponse(data, "clarifai"),
  },
  kimi: {
    url: "https://api.moonshot.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || [],
  },
  "kimi-coding": {
    ...KIMI_CODING_MODELS_CONFIG,
  },
  "kimi-coding-apikey": {
    ...KIMI_CODING_MODELS_CONFIG,
    buildHeaders: (token) => ({
      Accept: "application/json",
      "x-api-key": token,
    }),
  },
  anthropic: {
    url: "https://api.anthropic.com/v1/models",
    method: "GET",
    headers: {
      "Anthropic-Version": "2023-06-01",
      "Content-Type": "application/json",
    },
    authHeader: "x-api-key",
    parseResponse: (data) => data.data || [],
  },
  deepseek: {
    url: "https://api.deepseek.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  groq: {
    url: "https://api.groq.com/openai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  blackbox: {
    url: "https://api.blackbox.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  xai: XAI_MODELS_CONFIG,
  // xai-oauth intentionally NOT registered here: it stays on the frozen
  // static seed unless XAI_OAUTH_LIVE_MODEL_DISCOVERY is on (see
  // getXaiOauthLiveModelsConfig above) — keeping this map's keys in lockstep
  // with HARDCODED_MODELS_CONFIG_IDS (tests/unit/discovery-class.test.ts)
  // means the flag gate has to live at the lookup call site, not here.
  mistral: {
    url: "https://api.mistral.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },

  together: {
    url: "https://api.together.xyz/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  // OpenVecta (https://openvecta.com/) — OpenAI-compatible `/v1/models` returning
  // { object: "list", data: [{ id, context_length, owned_by, … }, …] }. Bearer
  // token with the `ov_sk_…` prefix. Same discovery shape as Together AI /
  // Cerebras / NVIDIA NIM (live-fetch path; registry seed is the offline fallback).
  openvecta: {
    url: "https://api.openvecta.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  openference: {
    url: "https://api.openference.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  "openference-api": {
    url: "https://api.openference.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  fireworks: {
    url: "https://api.fireworks.ai/inference/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  cerebras: {
    url: "https://api.cerebras.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  // Import exposes Cline's full official catalog but never mixes the separate
  // ClinePass subscription namespace into the Cline provider.
  cline: {
    url: CLINE_MODELS_ENDPOINT,
    method: "GET",
    headers: { Accept: "application/json" },
    parseResponse: parseClineModels,
  },
  // The full Cline catalog currently omits subscription entries. Keep ClinePass
  // import on the authoritative clinePass bucket instead of returning an empty list.
  clinepass: {
    url: CLINEPASS_MODELS_ENDPOINT,
    method: "GET",
    headers: { Accept: "application/json" },
    parseResponse: parseClinepassRecommendedModels,
  },
  // Perplexity's /v1/models lists the Agent API catalog (vendor-prefixed agent
  // ids), but chat only accepts the Sonar family on /chat/completions. Import
  // must keep Sonar-family ids only (#11060).
  perplexity: {
    url: "https://api.perplexity.ai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: parsePerplexitySonarModels,
  },
  cohere: {
    url: "https://api.cohere.com/v2/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  nvidia: {
    url: "https://integrate.api.nvidia.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  nebius: {
    url: "https://api.tokenfactory.nebius.com/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  kilocode: {
    url: "https://api.kilo.ai/api/openrouter/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  "ollama-cloud": {
    // Hosted Ollama lists directly callable models at /api/tags (#16823).
    url: "https://ollama.com/api/tags",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    // Ollama tag rows use name/model, not id; the synced catalog needs id.
    parseResponse: (data) => {
      const models = Array.isArray(data?.models)
        ? data.models
        : Array.isArray(data?.data)
          ? data.data
          : [];
      return models.flatMap((model: any) => {
        if (!model || typeof model !== "object") return [];
        const id = [model.id, model.model, model.name].find(
          (value) => typeof value === "string" && value.trim().length > 0
        );
        if (typeof id !== "string") return [];
        const normalizedId = id.trim();
        const name =
          typeof model.name === "string" && model.name.trim() ? model.name.trim() : normalizedId;
        return [{ ...model, id: normalizedId, name }];
      });
    },
  },
  "cloudflare-ai": {
    url: "https://api.cloudflare.com/client/v4/accounts/{accountId}/ai/models/search",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    // #4259: Cloudflare's `/ai/models/search` returns `{ id: "<uuid>", name: "@cf/..." }`.
    // `name` is the usable model slug; `id` is an internal UUID. Map `name`→id so the
    // dashboard/import surfaces callable model ids (`@cf/...`) instead of UUIDs.
    parseResponse: (data) =>
      (data.result || [])
        .map((model: any) => {
          const slug = typeof model?.name === "string" ? model.name : "";
          if (!slug) return null;
          return {
            id: slug,
            name: slug,
            ...(typeof model?.description === "string" && model.description
              ? { description: model.description }
              : {}),
          };
        })
        .filter(Boolean),
  },
  synthetic: {
    url: "https://api.synthetic.new/openai/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  "kilo-gateway": {
    url: "https://api.kilo.ai/api/gateway/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  "command-code": {
    url: "https://api.commandcode.ai/provider/v1/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  // OpenCode CLI identity headers on both opencode-family entries (see
  // buildOpencodeModelsDiscoveryEntry above for why — bare "Bun fetch" calls
  // without x-opencode-session are what OpenCode's operator warning names).
  "opencode-zen": buildOpencodeModelsDiscoveryEntry("https://opencode.ai/zen/v1/models"),
  "opencode-go": buildOpencodeModelsDiscoveryEntry("https://opencode.ai/zen/go/v1/models"),
  "glm-cn": {
    url: "https://open.bigmodel.cn/api/coding/paas/v4/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  gitlawb: {
    url: "https://opengateway.gitlawb.com/v1/xiaomi-mimo/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  "gitlawb-gmi": {
    url: "https://opengateway.gitlawb.com/v1/gmi-cloud/models",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => data.data || data.models || [],
  },
  chatplayground: buildChatPlaygroundModelsDiscoveryEntry(),
  cpl: buildChatPlaygroundModelsDiscoveryEntry(),
  // WorkBuddy serves no OpenAI-shaped /models endpoint (/v1/models and
  // /v2/models both 404) and its bundled catalog is known to be stale, so the
  // roster is read from the authenticated config the official CLI itself uses.
  // The registry entry stays `models: []` + `passthroughModels: true`; this is
  // what fills the dashboard. See normalizeWorkbuddyModelsResponse for what was
  // verified live vs. taken from the shipped CLI catalog.
  workbuddy: {
    url: "https://www.workbuddy.ai/v3/config",
    method: "GET",
    headers: { "Content-Type": "application/json", "X-Product": "SaaS" },
    authHeader: "Authorization",
    authPrefix: "Bearer ",
    parseResponse: (data) => normalizeWorkbuddyModelsResponse(data),
  },
};