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

7.6 KB
Raw Blame
import type { RegistryEntry, RegistryModel } from "./providers/shared.ts";
import { USAGE_FETCHER_PROVIDERS } from "../services/usage/fetcherProviders.ts";
import { USAGE_SUPPORTED_PROVIDERS } from "../services/usage/supportedProviders.ts";
import { hasFreeTierProvider } from "./freeTierProviders.ts";

export type ProviderPluginCapability =
  | "apikey"
  | "custom-executor"
  | "free-tier"
  | "oauth"
  | "passthrough-models"
  | "responses"
  | "sidecar-candidate"
  | "usage-fetch"
  | "usage-supported";

export interface ProviderPluginModel {
  id: string;
  name: string;
  contextLength?: number;
  maxOutputTokens?: number;
  toolCalling?: boolean;
  supportsReasoning?: boolean;
  supportsVision?: boolean;
  supportsVideo?: boolean;
  unsupportedParams?: readonly string[];
  targetFormat?: string;
}

export interface ProviderPluginManifestEntry {
  id: string;
  alias?: string;
  format: string;
  executor: string;
  auth: {
    type: string;
    header: string;
    prefix?: string;
  };
  endpoints: {
    baseUrl?: string;
    baseUrls?: string[];
    responsesBaseUrl?: string;
    chatPath?: string;
    modelsUrl?: string;
  };
  capabilities: ProviderPluginCapability[];
  passthroughModels: boolean;
  defaultContextLength?: number;
  timeoutMs?: number;
  models: ProviderPluginModel[];
  sidecar: {
    eligible: boolean;
    reasons: string[];
  };
}

export interface ProviderPluginManifest {
  schemaVersion: 1;
  generatedFrom: "open-sse/config/providers";
  providers: ProviderPluginManifestEntry[];
}

const SIDECAR_COMPATIBLE_EXECUTORS = new Set(["default"]);

/**
 * Providers with a wired `getUsageForProvider` implementation (#11722). The list mixes
 * canonical ids ("hyperagent") with aliases ("ha") because it is keyed by the strings the
 * usage dispatcher accepts, so `capabilitiesFor` resolves an entry on both.
 */
const USAGE_FETCHER_PROVIDER_SET = new Set<string>(USAGE_FETCHER_PROVIDERS);

/**
 * Providers whose usage API is accepted by dashboard/server routes (#10078).
 * Unlike USAGE_FETCHER_PROVIDERS this gate is checked with a plain
 * `USAGE_SUPPORTED_PROVIDERS.includes(providerId)` — no alias resolution —
 * so the manifest must emit on the identifier alone to stay faithful to the
 * runtime guard.
 */
const USAGE_SUPPORTED_PROVIDER_SET = new Set<string>(USAGE_SUPPORTED_PROVIDERS);

function compactObject<T extends Record<string, unknown>>(value: T): Partial<T> {
  return Object.fromEntries(
    Object.entries(value).filter(([, entryValue]) => entryValue !== undefined)
  ) as Partial<T>;
}

function mapModel(model: RegistryModel): ProviderPluginModel {
  return compactObject({
    id: model.id,
    name: model.name,
    contextLength: model.contextLength,
    maxOutputTokens: model.maxOutputTokens,
    toolCalling: model.toolCalling,
    supportsReasoning: model.supportsReasoning,
    supportsVision: model.supportsVision,
    supportsVideo: model.supportsVideo,
    unsupportedParams: model.unsupportedParams,
    targetFormat: model.targetFormat,
  }) as ProviderPluginModel;
}

function sidecarEligibility(entry: RegistryEntry): { eligible: boolean; reasons: string[] } {
  const reasons: string[] = [];

  if (!SIDECAR_COMPATIBLE_EXECUTORS.has(entry.executor)) {
    reasons.push(`custom executor: ${entry.executor}`);
  }
  if (entry.authType !== "apikey" && entry.authType !== "optional" && entry.authType !== "none") {
    reasons.push(`auth type requires TS handling: ${entry.authType}`);
  }
  if (!entry.baseUrl && !entry.baseUrls?.length && !entry.responsesBaseUrl) {
    reasons.push("no static upstream endpoint");
  }
  if (typeof entry.urlBuilder === "function") {
    reasons.push("dynamic URL builder");
  }
  if (entry.oauth) {
    reasons.push("oauth metadata");
  }
  if (entry.poolConfig) {
    reasons.push("session pool config");
  }

  return {
    eligible: reasons.length === 0,
    reasons,
  };
}

function capabilitiesFor(entry: RegistryEntry, eligible: boolean): ProviderPluginCapability[] {
  const capabilities = new Set<ProviderPluginCapability>();

  if (entry.authType === "apikey" || entry.authType === "optional") {
    capabilities.add("apikey");
  }
  if (entry.authType === "oauth" || entry.oauth) {
    capabilities.add("oauth");
  }
  if (entry.responsesBaseUrl) {
    capabilities.add("responses");
  }
  if (entry.passthroughModels) {
    capabilities.add("passthrough-models");
  }
  if (entry.executor !== "default") {
    capabilities.add("custom-executor");
  }
  if (eligible) {
    capabilities.add("sidecar-candidate");
  }
  if (
    USAGE_FETCHER_PROVIDER_SET.has(entry.id) ||
    (entry.alias !== undefined && USAGE_FETCHER_PROVIDER_SET.has(entry.alias))
  ) {
    capabilities.add("usage-fetch");
  }
  if (USAGE_SUPPORTED_PROVIDER_SET.has(entry.id)) {
    capabilities.add("usage-supported");
  }
  if ([entry.id, entry.alias].some(hasFreeTierProvider)) {
    capabilities.add("free-tier");
  }

  return [...capabilities].sort();
}

export function createProviderPluginManifestEntry(
  entry: RegistryEntry
): ProviderPluginManifestEntry {
  const sidecar = sidecarEligibility(entry);

  return {
    id: entry.id,
    ...(entry.alias ? { alias: entry.alias } : {}),
    format: entry.format,
    executor: entry.executor,
    auth: compactObject({
      type: entry.authType,
      header: entry.authHeader,
      prefix: entry.authPrefix,
    }) as ProviderPluginManifestEntry["auth"],
    endpoints: compactObject({
      baseUrl: entry.baseUrl,
      baseUrls: entry.baseUrls,
      responsesBaseUrl: entry.responsesBaseUrl,
      chatPath: entry.chatPath,
      modelsUrl: entry.modelsUrl,
    }) as ProviderPluginManifestEntry["endpoints"],
    capabilities: capabilitiesFor(entry, sidecar.eligible),
    passthroughModels: entry.passthroughModels === true,
    ...(typeof entry.defaultContextLength === "number"
      ? { defaultContextLength: entry.defaultContextLength }
      : {}),
    ...(typeof entry.timeoutMs === "number" ? { timeoutMs: entry.timeoutMs } : {}),
    models: (entry.models ?? []).map(mapModel),
    sidecar,
  };
}

export function generateProviderPluginManifestFromRegistry(
  registry: Record<string, RegistryEntry>
): ProviderPluginManifest {
  return {
    schemaVersion: 1,
    generatedFrom: "open-sse/config/providers",
    providers: Object.values(registry)
      .map(createProviderPluginManifestEntry)
      .sort((a, b) => a.id.localeCompare(b.id)),
  };
}

/**
 * Builds a `ProviderPluginManifestEntry` for an embedded-service backend (9router,
 * cliproxyapi) from its `SERVICE_BACKEND_MANIFEST_TEMPLATE` entry (#7333 Phase 1).
 *
 * Additive only — NOT called by `generateProviderPluginManifestFromRegistry()`, so the
 * static-registry manifest path (260+ providers) is byte-identical before/after this
 * function's introduction. Not wired into any live request path in this PR; that is
 * explicitly deferred to the cliproxyapi-migration follow-up.
 *
 * Service backends have no static model list of their own — their models come from
 * `getServiceModels()` at runtime, so `models` is always `[]` here.
 */
export function createServiceBackendManifestEntry(
  pluginId: string,
  template: Pick<
    ProviderPluginManifestEntry,
    "format" | "executor" | "auth" | "endpoints" | "capabilities" | "passthroughModels" | "sidecar"
  >
): ProviderPluginManifestEntry {
  return {
    id: pluginId,
    ...template,
    models: [],
  };
}

export function getProviderPluginManifestEntryFromRegistry(
  registry: Record<string, RegistryEntry>,
  provider: string
): ProviderPluginManifestEntry | null {
  const entry =
    registry[provider] || Object.values(registry).find((candidate) => candidate.alias === provider);

  return entry ? createProviderPluginManifestEntry(entry) : null;
}