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

6.9 KB
Raw Blame
/**
 * Fetch Cursor Available Models via HTTP (no cursor-agent binary required).
 * Uses Connect-RPC JSON against api2.cursor.sh AiService/AvailableModels.
 */

import { CURSOR_CONFIG } from "@/lib/oauth/constants/oauth";
import { CursorService } from "@/lib/oauth/services/cursor";
import {
  humanizeCursorModelId,
  type CursorAgentModelEntry,
} from "@/lib/providerModels/cursorAgent";
import { ensureCursorAutoCatalogEntry } from "@/lib/providerModels/cursorAutoCatalog";
import { cursorGrok47Catalog } from "@/lib/providerModels/cursorGrok47Catalog";
import { getConsistentMachineId } from "@/shared/utils/machineId";

export { ensureCursorAutoCatalogEntry } from "@/lib/providerModels/cursorAutoCatalog";

export type FetchCursorAvailableModelsOptions = {
  accessToken: string;
  machineId?: string | null;
  fetchImpl?: typeof fetch;
  signal?: AbortSignal;
};

function asRecord(value: unknown): Record<string, unknown> | null {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : null;
}

function pickModelId(entry: Record<string, unknown>): string | null {
  for (const key of ["name", "modelId", "model_id", "id", "slug"]) {
    const v = entry[key];
    if (typeof v === "string" && v.trim()) return v.trim();
  }
  return null;
}

function pickModelName(entry: Record<string, unknown>, id: string): string {
  for (const key of ["displayName", "display_name", "title", "label"]) {
    const v = entry[key];
    if (typeof v === "string" && v.trim()) return v.trim();
  }
  return humanizeCursorModelId(id);
}

function collectArrays(record: Record<string, unknown>, keys: string[]): unknown[] {
  return keys.flatMap((key) => (Array.isArray(record[key]) ? record[key] : []));
}

function collectModelCandidates(payload: unknown): unknown[] {
  const root = asRecord(payload) ?? {};
  const candidates = collectArrays(root, [
    "items",
    "models",
    "availableModels",
    "available_models",
    "model",
  ]);
  const nestedModels = asRecord(root.models);
  if (nestedModels) candidates.push(...collectArrays(nestedModels, ["models", "items", "list"]));
  if (Array.isArray(payload)) candidates.push(...payload);
  return candidates;
}

function isUnavailableModel(entry: Record<string, unknown>): boolean {
  return (
    entry.disabled === true ||
    entry.isDisabled === true ||
    entry.usable === false ||
    entry.isUsable === false
  );
}

function cursorContextLimit(entry: Record<string, unknown>): number | undefined {
  const value = entry.contextTokenLimit ?? entry.context_token_limit;
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
}

function cursorEffortValues(entry: Record<string, unknown>): string[] | undefined {
  const definitions = entry.parameterDefinitions ?? entry.parameter_definitions;
  if (!Array.isArray(definitions)) return undefined;
  const efforts = new Set<string>();
  for (const value of definitions) {
    const definition = asRecord(value);
    if (definition?.id !== "effort" && definition?.id !== "reasoning") continue;
    const parameterType = asRecord(definition.parameterType ?? definition.parameter_type);
    const enumerated = asRecord(parameterType?.enumParameter ?? parameterType?.enum_parameter);
    if (!Array.isArray(enumerated?.values)) continue;
    for (const item of enumerated.values) {
      const option = asRecord(item);
      if (option?.blockedByAdminAllowlist === true || option?.blocked_by_admin_allowlist === true) {
        continue;
      }
      if (typeof option?.value === "string" && option.value.trim()) {
        efforts.add(option.value.trim());
      }
    }
  }
  return efforts.size > 0 ? [...efforts] : undefined;
}

function normalizeModelCandidate(item: unknown): CursorAgentModelEntry | null {
  if (typeof item === "string") {
    const id = item.trim();
    return id ? { id, name: humanizeCursorModelId(id), owned_by: "cursor" } : null;
  }

  const entry = asRecord(item);
  if (!entry || isUnavailableModel(entry)) return null;
  const id = pickModelId(entry);
  if (!id) return null;
  const contextLength = cursorContextLimit(entry);
  const supportedThinkingEfforts = cursorEffortValues(entry);
  return {
    id,
    name: pickModelName(entry, id),
    owned_by: "cursor",
    ...(contextLength ? { contextLength } : {}),
    ...(supportedThinkingEfforts ? { supportedThinkingEfforts } : {}),
  };
}

/**
 * Normalize AvailableModels JSON (Connect JSON or protobuf-json) into catalog rows.
 * Exported for unit tests.
 *
 * Always ensures catalog id `auto` is present (Cursor often returns wire id `default`
 * only). OmniRoute clients request `cu/auto`; resolveRequestedModel maps it to `default`.
 */
export function normalizeCursorAvailableModelsPayload(payload: unknown): CursorAgentModelEntry[] {
  const seen = new Set<string>();
  const out: CursorAgentModelEntry[] = [];
  for (const item of collectModelCandidates(payload)) {
    const model = normalizeModelCandidate(item);
    if (!model || seen.has(model.id)) continue;
    seen.add(model.id);
    const grok = cursorGrok47Catalog(item);
    if (grok) {
      model.contextLength = grok.contextLength;
      model.supportedThinkingEfforts = grok.supportedThinkingEfforts;
    }
    out.push(model);
    for (const variant of grok?.variants ?? []) {
      if (seen.has(variant.id)) continue;
      seen.add(variant.id);
      out.push(variant);
    }
  }

  return ensureCursorAutoCatalogEntry(out);
}

export async function fetchCursorAvailableModels(
  options: FetchCursorAvailableModelsOptions
): Promise<CursorAgentModelEntry[]> {
  const { accessToken, signal } = options;
  if (!accessToken) throw new Error("Cursor access token is required for AvailableModels");

  const machineId = options.machineId || (await getConsistentMachineId());
  const cursorService = new CursorService();
  const headers = {
    ...cursorService.buildHeaders(accessToken, machineId),
    // Prefer Connect JSON so we can parse without a protobuf schema
    "Content-Type": "application/json",
    Accept: "application/json",
  };

  const url = `${CURSOR_CONFIG.apiEndpoint}${CURSOR_CONFIG.modelsEndpoint}`;
  const fetchImpl = options.fetchImpl || fetch;
  const response = await fetchImpl(url, {
    method: "POST",
    headers,
    body: "{}",
    signal,
  });

  if (!response.ok) {
    const text = await response.text().catch(() => "");
    throw new Error(
      `Cursor AvailableModels failed: ${response.status}${text ? ` ${text.slice(0, 200)}` : ""}`
    );
  }

  const contentType = response.headers.get("content-type") || "";
  if (contentType.includes("proto") || contentType.includes("protobuf")) {
    throw new Error(
      "Cursor AvailableModels returned protobuf; JSON catalog unavailable for this client version"
    );
  }

  const payload = await response.json();
  const models = normalizeCursorAvailableModelsPayload(payload);
  if (models.length === 0) {
    throw new Error("Cursor AvailableModels returned no models");
  }
  return models;
}