Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

6.5 KB
Raw Blame
import { invoke } from "@tauri-apps/api/core";
import type { TFunction } from "i18next";
import { toast } from "@/lib/toast";
import { parseHeaderOverrideJson } from "@/lib/requestOverrides";

// 矩阵起源 Genesis 的 /v1/models 会混入 embedding / rerank 模型。除 Claude 外
// 的表单不读预设的 modelsUrl,所以在这里按地址补上 ?type=chat。
const GENESIS_ORIGIN = "https://token.moi.matrixorigin.cn";
const GENESIS_CHAT_MODELS_URL = `${GENESIS_ORIGIN}/v1/models?type=chat`;

export interface FetchedModel {
  id: string;
  ownedBy: string | null;
  billing?: { auto_discount?: number };
  /** Marker for the Copilot virtual Auto entry; it is not an upstream model. */
  isCopilotAuto?: boolean;
}

export interface ModelFetchOptions {
  apiFormat?: string;
  requestHeaders?: Record<string, string>;
  /** 保留中转标成图片 / 视频 / 向量的模型(默认滤掉,见 #10026)。 */
  includeNonChatModels?: boolean;
}

/**
 * Claude / Claude Desktop 卡片的 `meta.apiFormat` 换成取模型列表要用的格式名。
 *
 * 只有 Gemini Native 需要换:Google 原生接口只认 `x-goog-api-key` 头里的
 * AI Studio Key,按默认的 `Authorization: Bearer` 发会被回 401。其余格式
 * 沿用默认(Bearer + `/v1/models`),不改变既有行为。
 */
export function claudeModelFetchApiFormat(
  apiFormat: string | undefined,
): string | undefined {
  return apiFormat === "gemini_native" ? "google-generative-ai" : undefined;
}

/**
 * 把表单里的本地代理 Header 覆盖 JSON 解析成取模型列表时要携带的请求头。
 *
 * 与转发路径共用 parseHeaderOverrideJson 的校验规则;解析失败或覆盖为空时
 * 静默返回 undefined(回退到不带覆盖头取模型),格式错误由表单字段本身提示。
 */
export function modelFetchRequestHeaders(
  headersJson: string,
): Record<string, string> | undefined {
  const { headers, error } = parseHeaderOverrideJson(headersJson);
  if (error || !headers || Object.keys(headers).length === 0) {
    return undefined;
  }
  return headers;
}

/**
 * 从供应商获取可用模型列表
 *
 * 使用 OpenAI 兼容的 GET /v1/models 端点。优先用 `modelsUrl` 精确覆写;
 * 否则后端会对 baseURL 生成候选列表并按序尝试(含"剥离 /anthropic 等兼容子路径"兜底)。
 *
 * 该接口可以获取数据格式为
 * OpenAI Chat Completion {"data": [{"id": "xxx","owned_by": "xxx"}]} 文档:https://developers.openai.com/api/reference/resources/models/methods/list
 * 和
 * Anthropic兼容 {"data":[{"id":"xxx"}]} 文档:https://platform.claude.com/docs/en/api/models/list
 * 这两种端点的模型列表
 * 特别支持智谱 OpenAI Responses {"models":[{"slug":"xxx"}]} 端点:https://open.bigmodel.cn/api/v1/models
 */
export async function fetchModelsForConfig(
  baseUrl: string,
  apiKey: string,
  isFullUrl?: boolean,
  modelsUrl?: string,
  customUserAgent?: string,
  options?: ModelFetchOptions,
): Promise<FetchedModel[]> {
  if (!modelsUrl) {
    try {
      const endpoint = new URL(baseUrl);
      if (
        endpoint.origin === GENESIS_ORIGIN &&
        (endpoint.pathname === "/" ||
          endpoint.pathname === "/v1" ||
          endpoint.pathname === "/v1/")
      ) {
        modelsUrl = GENESIS_CHAT_MODELS_URL;
      }
    } catch {
      // Keep the native fetcher's normal validation for malformed URLs.
    }
  }
  return invoke("fetch_models_for_config", {
    baseUrl,
    apiKey,
    isFullUrl,
    modelsUrl,
    customUserAgent,
    apiFormat: options?.apiFormat,
    requestHeaders: options?.requestHeaders,
    includeNonChatModels: options?.includeNonChatModels,
  });
}

/**
 * Models reported by the locally installed Antigravity runtime. With an API key it asks agy's
 * API-key mode, which only accepts its built-in Gemini models (by display name).
 */
export async function getAgyModels(options?: {
  apiKey?: string;
  baseUrl?: string;
}): Promise<FetchedModel[]> {
  return invoke("get_agy_models", {
    apiKey: options?.apiKey || null,
    baseUrl: options?.baseUrl || null,
  });
}

export interface OpenCodeModelRef {
  providerId: string;
  modelId: string;
}

/** 获取 OpenCode 当前运行时可用模型(包含 OAuth 与 Zen 免费模型)。 */
export async function getOpenCodeModels(): Promise<OpenCodeModelRef[]> {
  return invoke("get_opencode_models");
}

/**
 * 获取 Codex OAuth (ChatGPT Plus/Pro 反代) 可用模型列表
 *
 * Codex OAuth 使用 ChatGPT 的 backend-api/codex 端点,不兼容普通 /v1/models。
 */
export async function fetchCodexOauthModels(
  accountId?: string | null,
): Promise<FetchedModel[]> {
  return invoke("get_codex_oauth_models", {
    accountId: accountId || null,
  });
}

/** 获取当前 xAI OAuth 账号可访问的模型列表。 */
export async function fetchXaiOauthModels(
  accountId?: string | null,
): Promise<FetchedModel[]> {
  return invoke("get_xai_oauth_models", {
    accountId: accountId || null,
  });
}

/**
 * 根据错误类型显示对应的 toast 提示
 */
export function showFetchModelsError(
  err: unknown,
  t: TFunction,
  opts?: { hasApiKey: boolean; hasBaseUrl: boolean },
): void {
  // 前端预检:缺少必填字段
  if (opts && !opts.hasBaseUrl && !opts.hasApiKey) {
    toast.error(t("providerForm.fetchModelsNeedConfig"));
    return;
  }
  if (opts && !opts.hasApiKey) {
    toast.error(t("providerForm.fetchModelsNeedApiKey"));
    return;
  }
  if (opts && !opts.hasBaseUrl) {
    toast.error(t("providerForm.fetchModelsNeedEndpoint"));
    return;
  }

  // 解析后端错误字符串
  const msg = String(err);

  // Google 对无效的 AI Studio Key 回 400 + reason API_KEY_INVALID,而不是 401
  if (
    msg.includes("HTTP 401") ||
    msg.includes("HTTP 403") ||
    msg.includes("API_KEY_INVALID")
  ) {
    toast.error(t("providerForm.fetchModelsAuthFailed"));
    return;
  }
  // 所有候选端点均返回 404/405:供应商可能未开放 /models 接口,或 Base URL 有误
  if (msg.includes("All candidates failed")) {
    toast.error(t("providerForm.fetchModelsEndpointNotFound"));
    return;
  }
  if (msg.includes("HTTP 404") || msg.includes("HTTP 405")) {
    toast.error(t("providerForm.fetchModelsEndpointNotFound"));
    return;
  }
  if (msg.includes("timeout") || msg.includes("timed out")) {
    toast.error(t("providerForm.fetchModelsTimeout"));
    return;
  }
  if (msg.includes("Failed to parse")) {
    toast.error(t("providerForm.fetchModelsNotSupported"));
    return;
  }

  // 通用兜底
  toast.error(t("providerForm.fetchModelsFailed"));
}