Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(model-providers): load catalog from public API (#330)

JiangJiahao71f6e8c01ca9
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index 6ccd4ff5fc..7736e38038 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -2,12 +2,12 @@
* createDesktopProviderService —— 桌面端目录加载落地 + provider-service 接线。
*
* 两块职责:
- * 1. 目录加载器 `ensureActiveCatalogLoaded`:用 electron net.request 拉 OSS、node fs 读 dev
+ * 1. 目录加载器 `ensureActiveCatalogLoaded`:用 electron net.request 拉公共 Catalog、node fs 读 dev
* 本地文件,把结果写进 active-catalog 单例(getActiveCatalog 同步读)。
- * - release:由 manifestService.getBaseUrl() 推 `{base}/cfg/providers.json`(与 notice 同 bucket)。
+ * - release:优先从区域化 Model Access 公共接口加载,失败时回退旧 OSS 目录。
* - dev:关闭联网(与 manifestService 一致),可由 XDT_MODELS_PATH 指向本地文件即时生效。
* - env 兜底:XDT_MODELS_URL(完整覆盖 URL)/ XDT_DISABLE_MODELS_FETCH(强制不联网)。
- * **每进程拉一次、存内存、无 TTL、无磁盘缓存**:OSS 是运行时真源,bundled 是兜底。
+ * **每进程拉一次、存内存、无 TTL、无磁盘缓存**:远端目录是运行时真源,bundled 是最终兜底。
* 启动期(splash)由 bootstrap-electron 在构造 Maker 前 await 一次(见 registerMakerIpcsAfterSplash)。
* 2. `getDesktopProviderService`:把 active-catalog + 连接状态读取器注入 provider-service。
* 连接状态直接复用现有凭证存储——XD = 托管 gateway key 是否存在、
@@ -21,6 +21,7 @@ import path from 'node:path';
import {
buildUserProvider,
+ DEFAULT_REMOTE_CATALOG_BUDGET_MS,
loadCatalog,
type Catalog,
type CatalogIO,
@@ -29,6 +30,7 @@ import {
import { createLogger } from '../logger.js';
import { getBaseUrl, isDev } from '../manifestService.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
import { getActiveCatalog, setActiveCatalog, setCustomProviders, setDiscoveredCodexModels } from './active-catalog.js';
import {
readCodexDiscoveredModels,
@@ -70,14 +72,11 @@ import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';
const log = createLogger('provider-service');
-/** OSS 拉取超时(与 manifest fetch 同量级)。 */
-const FETCH_TIMEOUT_MS = 15_000;
-
/**
* electron net.request GET → 文本。非 200 / 超时 / 网络错均 reject,
* 由 loadCatalog 兜底到内置目录(绝不让目录加载抛穿)。
*/
-function fetchText(url: string): Promise<string> {
+function fetchText(url: string, timeoutMs: number): Promise<string> {
return new Promise<string>((resolve, reject) => {
let settled = false;
const settle = (fn: () => void): void => {
@@ -92,7 +91,7 @@ function fetchText(url: string): Promise<string> {
const timer = setTimeout(() => {
request.abort();
settle(() => reject(new Error(`catalog fetch timeout: ${url}`)));
- }, FETCH_TIMEOUT_MS);
+ }, timeoutMs);
request.on('response', (response) => {
if (response.statusCode !== 200) {
@@ -139,17 +138,19 @@ const io: CatalogIO = {
};
/**
- * 构建目录源配置。release 取当前内外网探测得到的 OSS base;dev 不联网。
+ * 构建目录源配置。release 使用区域化 Model Access 公共接口,旧 OSS 保留为迁移期回退;dev 不联网。
*
- * 注:内外网 base 在会话中途切换(办公室↔家)只会让下次进程的远端拉取退化到内置目录——
- * 属安全降级(external CDN 本就公网可达),不影响可用性。
+ * 注:区域 endpoint 或 OSS base 在会话中途切换(办公室↔家)只影响下次进程加载;本进程仍持有
+ * 已校验目录。远端不可用时依次退化到旧 OSS 与 bundled,不影响基础 Provider 可用性。
*/
function buildSource(): CatalogSourceConfig {
const dev = isDev();
return {
url: process.env.XDT_MODELS_URL,
localPath: process.env.XDT_MODELS_PATH,
- baseUrl: dev ? undefined : getBaseUrl(),
+ baseUrl: dev ? undefined : getClientEndpoint('modelAccessApiBaseUrl'),
+ fallbackBaseUrl: dev ? undefined : getBaseUrl(),
+ remoteBudgetMs: DEFAULT_REMOTE_CATALOG_BUDGET_MS,
disableFetch: dev || process.env.XDT_DISABLE_MODELS_FETCH === '1',
};
}
@@ -174,7 +175,7 @@ let activeLoaded = false;
let activeInflight: Promise<Catalog> | null = null;
/**
- * 启动期(splash)await 一次:拉 OSS 目录写入 active-catalog。幂等 + 并发去重。
+ * 启动期(splash)await 一次:加载远端目录写入 active-catalog。幂等 + 并发去重。
* loadCatalog 永不抛(最差回落 bundled),故本函数也不会抛。
* 调用点:bootstrap-electron 的 registerMakerIpcsAfterSplash,第一次 getMaker() 构造之前。
*/
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index 7af2814948..e4d0746226 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -12,6 +12,7 @@ import { BUNDLED_CATALOG } from '../catalog.js';
import {
loadCatalog,
resolveCatalogUrl,
+ resolveFallbackCatalogUrl,
mergeWithBundled,
CATALOG_CFG_PATH,
type CatalogIO,
@@ -77,8 +78,13 @@ describe('resolveCatalogUrl', () => {
it('prefers explicit url', () => {
expect(resolveCatalogUrl({ url: 'https://x/y.json', baseUrl: 'https://b' })).toBe('https://x/y.json');
});
- it('builds from baseUrl + cfg path', () => {
- expect(resolveCatalogUrl({ baseUrl: 'https://cdn.example.com/base/' })).toBe(
+ it('builds from baseUrl + public catalog API path', () => {
+ expect(resolveCatalogUrl({ baseUrl: 'https://model-access.example.com/' })).toBe(
+ 'https://model-access.example.com/api/model-catalog/catalog',
+ );
+ });
+ it('builds the migration OSS fallback URL', () => {
+ expect(resolveFallbackCatalogUrl({ fallbackBaseUrl: 'https://cdn.example.com/base/' })).toBe(
`https://cdn.example.com/base${CATALOG_CFG_PATH}`,
);
});
@@ -179,13 +185,122 @@ describe('loadCatalog', () => {
expect(cat.providers.find((p) => p.id === 'anthropic')).toBeTruthy();
});
- it('fetches remote then merges bundled', async () => {
- const io: CatalogIO = { fetchText: vi.fn(async () => JSON.stringify(MINIMAL)) };
- const cat = await loadCatalog({ url: 'https://x/y.json' }, io);
- expect(io.fetchText).toHaveBeenCalledWith('https://x/y.json');
+ it('falls back from public API to legacy OSS before bundled', async () => {
+ const fetchText = vi.fn()
+ .mockRejectedValueOnce(new Error('api unavailable'))
+ .mockResolvedValueOnce(JSON.stringify(MINIMAL));
+ const cat = await loadCatalog(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ now: () => 0,
+ },
+ { fetchText },
+ );
+ expect(fetchText).toHaveBeenNthCalledWith(
+ 1,
+ 'https://model-access.example.com/api/model-catalog/catalog',
+ 15_000,
+ );
+ expect(fetchText).toHaveBeenNthCalledWith(
+ 2,
+ 'https://cdn.example.com/cindy/cfg/providers.json',
+ expect.any(Number),
+ );
expect(cat.version).toBe('test');
- // 远端目录裁剪到只有 anthropic,bundled 补回 openai/xai/xd(mergeWithBundled)。
- expect(cat.providers.map((p) => p.id).sort()).toEqual(['anthropic', 'openai', 'xai', 'xd']);
+ });
+ it('falls back from invalid public API payload to legacy OSS before bundled', async () => {
+ const fetchText = vi.fn()
+ .mockResolvedValueOnce('{"version":"broken","providers":[]}')
+ .mockResolvedValueOnce(JSON.stringify(MINIMAL));
+ const cat = await loadCatalog(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ now: () => 0,
+ },
+ { fetchText },
+ );
+ expect(fetchText).toHaveBeenNthCalledWith(
+ 1,
+ 'https://model-access.example.com/api/model-catalog/catalog',
+ 15_000,
+ );
+ expect(fetchText).toHaveBeenNthCalledWith(
+ 2,
+ 'https://cdn.example.com/cindy/cfg/providers.json',
+ expect.any(Number),
+ );
+ expect(cat.version).toBe('test');
+ });
+
+ it('shares one remote budget across the public API and legacy OSS fallback', async () => {
+ const now = vi.fn()
+ .mockReturnValueOnce(1_000)
+ .mockReturnValueOnce(1_000)
+ .mockReturnValueOnce(11_000);
+ const fetchText = vi.fn()
+ .mockRejectedValueOnce(new Error('api timeout'))
+ .mockResolvedValueOnce(JSON.stringify(MINIMAL));
+ const cat = await loadCatalog(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ remoteBudgetMs: 15_000,
+ now,
+ },
+ { fetchText },
+ );
+ expect(fetchText).toHaveBeenNthCalledWith(
+ 1,
+ 'https://model-access.example.com/api/model-catalog/catalog',
+ 15_000,
+ );
+ expect(fetchText).toHaveBeenNthCalledWith(
+ 2,
+ 'https://cdn.example.com/cindy/cfg/providers.json',
+ 5_000,
+ );
+ expect(cat.version).toBe('test');
+ });
+
+ it('does not start legacy OSS after the shared remote budget is exhausted', async () => {
+ const now = vi.fn()
+ .mockReturnValueOnce(1_000)
+ .mockReturnValueOnce(1_000)
+ .mockReturnValueOnce(16_000);
+ const fetchText = vi.fn().mockRejectedValueOnce(new Error('api timeout'));
+ const cat = await loadCatalog(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ remoteBudgetMs: 15_000,
+ now,
+ },
+ { fetchText },
+ );
+ expect(fetchText).toHaveBeenCalledTimes(1);
+ expect(fetchText).toHaveBeenCalledWith(
+ 'https://model-access.example.com/api/model-catalog/catalog',
+ 15_000,
+ );
+ expect(cat.version).toBe(BUNDLED_CATALOG.version);
+ });
+
+ it('uses explicit URL without also retrying the legacy OSS fallback', async () => {
+ const fetchText = vi.fn().mockRejectedValue(new Error('override unavailable'));
+ const cat = await loadCatalog(
+ {
+ url: 'https://override.example.com/providers.json',
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ now: () => 0,
+ },
+ { fetchText },
+ );
+ expect(fetchText).toHaveBeenCalledTimes(1);
+ expect(fetchText).toHaveBeenCalledWith('https://override.example.com/providers.json', 15_000);
+ expect(cat.version).toBe(BUNDLED_CATALOG.version);
});
it('falls back to bundled when fetch fails', async () => {
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index df9f36a52b..0ef73b7b3b 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -3,7 +3,7 @@
*
* - types:Provider / CatalogModel / RoutingDescriptor(models.dev 形状 + agents/routing/runtime 扩展)
* - catalog:内置目录 BUNDLED_CATALOG + parseCatalog 校验
- * - source:目录源解析与加载(OSS / 本地 / 缓存 / 兜底,IO 由 host 注入)
+ * - source:目录源解析与加载(公共 API / 旧 OSS / 本地 / bundled 兜底,IO 由 host 注入)
* - registry:连接状态合成、按 agent 算可见性、resolveRoute 解析路由素材
*/
@@ -33,8 +33,11 @@ export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sa
export { buildUserProvider, DEFAULT_CUSTOM_CONTEXT_WINDOW } from './user-provider.js';
export {
+ CATALOG_API_PATH,
CATALOG_CFG_PATH,
+ DEFAULT_REMOTE_CATALOG_BUDGET_MS,
resolveCatalogUrl,
+ resolveFallbackCatalogUrl,
mergeWithBundled,
loadCatalog,
} from './source.js';
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index 22f39cc3f8..66aec3afc4 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -1,13 +1,13 @@
/**
* 目录源解析与加载(纯逻辑,IO 由 host 注入,零 Electron / node 依赖)。
*
- * - release:从 OSS `{base}/cfg/providers.json` 拉取(base 复用 manifest 的内外网探测)。
- * - dev:直接读仓库本地文件(`localPath`),改了即时生效、不联网。
- * - 兜底优先级:本地(dev) → 远端拉取 → 内置 bundled。
+ * - release:优先从 Model Access 公共匿名接口拉取完整 Catalog;失败时回退旧 OSS 目录。
+ * - dev:直接读仓库本地文件(`localPath`),改了即时生效、默认不联网。
+ * - 兜底优先级:本地(dev) → 公共 API → 旧 OSS → 内置 bundled。
*
* 目录每进程加载一次、存内存、**无 TTL**(由 host 的 active-catalog 在启动期 await 一次);
- * 本模块刻意**不做磁盘缓存**——OSS 是运行时真源、bundled 是兜底,无需在两者之间再缓一层
- * (否则磁盘缓存的新鲜窗口会让「重启即拉最新」失效)。
+ * 本模块刻意**不做磁盘缓存**——公共 API 与迁移期 OSS 都是远端目录源,bundled 是最终兜底,
+ * 无需再引入会让「重启即拉最新」失效的磁盘新鲜窗口。
*
* 本模块不碰文件系统 / 网络 / userData——这些能力由 host 通过 `CatalogIO` 注入,
* 保证包可独立单测,也保证跨平台路径 / CORS 等细节留在 host。
@@ -16,38 +16,55 @@
import { BUNDLED_CATALOG, parseCatalog } from './catalog.js';
import type { Catalog, Provider } from './types.js';
-/** OSS bucket 下目录文件的相对路径(与 notice 同 bucket、并列)。 */
+/** 公共模型目录 API 路径。发布版由 model-access-server 匿名提供完整 Catalog。 */
+export const CATALOG_API_PATH = '/api/model-catalog/catalog';
+/** 旧客户端目录的 OSS 相对路径。迁移期作为公共 API 失败后的兼容回退。 */
export const CATALOG_CFG_PATH = '/cfg/providers.json';
+/** 整条远端 Catalog fallback 链共享的默认启动等待预算。 */
+export const DEFAULT_REMOTE_CATALOG_BUDGET_MS = 15_000;
+
export interface CatalogSourceConfig {
- /** 完整覆盖源 URL(env XDT_MODELS_URL);缺省由 baseUrl 拼。 */
+ /** 完整覆盖源 URL(env XDT_MODELS_URL);缺省使用公共 catalog API。 */
url?: string;
+ /** 公共 catalog API 基址(modelAccessApiBaseUrl)。 */
+ baseUrl?: string;
+ /** 迁移期旧 OSS/CDN 基址;公共 API 失败后读取 `${fallbackBaseUrl}/cfg/providers.json`。 */
+ fallbackBaseUrl?: string;
/** dev 本地文件路径(env XDT_MODELS_PATH);命中则只读它、不联网。 */
localPath?: string;
- /** 关闭远端拉取(env XDT_DISABLE_MODELS_FETCH);只用缓存 / 内置。 */
+ /** 整条远端 fallback 链共享的等待预算;缺省 15 秒。 */
+ remoteBudgetMs?: number;
+ /** 注入单调时钟(测试用);缺省 Date.now。 */
+ now?: () => number;
+ /** 关闭远端拉取(env XDT_DISABLE_MODELS_FETCH);不影响 localPath 覆盖。 */
disableFetch?: boolean;
- /** OSS base(复用 manifestService.getBaseUrl());拼成 `${base}/cfg/providers.json`。 */
- baseUrl?: string;
}
export interface CatalogIO {
- /** 拉取远端文本(host 用 electron net.request 绕 CORS)。 */
- fetchText?: (url: string) => Promise<string>;
+ /** 拉取远端文本(host 用 electron net.request 绕 CORS;timeoutMs 为本次剩余共享预算)。 */
+ fetchText?: (url: string, timeoutMs: number) => Promise<string>;
/** 读本地文件(dev / localPath);不存在返回 null。 */
readFile?: (path: string) => Promise<string | null>;
/** 诊断日志(可选)。 */
log?: (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void;
}
-/** 解析最终要拉取的 URL:显式 url 优先,否则 `${baseUrl}${CATALOG_CFG_PATH}`。 */
+/** 解析主 catalog URL:显式 url 优先,否则 `${baseUrl}${CATALOG_API_PATH}`。 */
export function resolveCatalogUrl(cfg: CatalogSourceConfig): string | null {
if (cfg.url && cfg.url.trim()) return cfg.url.trim();
if (cfg.baseUrl && cfg.baseUrl.trim()) {
- return cfg.baseUrl.trim().replace(/\/+$/, '') + CATALOG_CFG_PATH;
+ return cfg.baseUrl.trim().replace(/\/+$/, '') + CATALOG_API_PATH;
}
return null;
}
+/** 解析迁移期旧 OSS 回退 URL。 */
+export function resolveFallbackCatalogUrl(cfg: CatalogSourceConfig): string | null {
+ if (!cfg.fallbackBaseUrl?.trim()) return null;
+ return cfg.fallbackBaseUrl.trim().replace(/\/+$/, '') + CATALOG_CFG_PATH;
+}
+
/** 只给仍保持 bundled 鉴权与上游路由形状的旧条目迁移 access,不能仅凭 provider id 猜计费。 */
function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access'] {
if (primary.auth.method !== bundled.auth.method) return undefined;
@@ -112,8 +129,8 @@ function log(io: CatalogIO, level: 'info' | 'warn' | 'error', msg: string, meta?
*
* 顺序:
* 1. dev:cfg.localPath + io.readFile → 读本地、合并 bundled、直接返回(不联网)。
- * 2. 远端拉取(除非 disableFetch / 无 url / 无 fetchText)→ 合并 bundled、用之。
- * 3. 任意上述失败 → 内置 bundled。
+ * 2. 远端依次尝试公共 API、迁移期旧 OSS(除非 disableFetch / 无 URL / 无 fetchText)。
+ * 3. 任意上述来源均不可用 → 内置 bundled。
*/
export async function loadCatalog(cfg: CatalogSourceConfig, io: CatalogIO): Promise<Catalog> {
// 1) dev 本地文件优先(命中即用,不联网)。
@@ -130,16 +147,34 @@ export async function loadCatalog(cfg: CatalogSourceConfig, io: CatalogIO): Prom
}
}
- // 2) 远端 OSS 拉取(每进程一次,不落盘缓存)。
+ // 2) 公共 model-access catalog API;迁移期失败后尝试旧 OSS 目录。
const url = resolveCatalogUrl(cfg);
- if (!cfg.disableFetch && url && io.fetchText) {
- try {
- const text = await io.fetchText(url);
- const parsed = parseCatalog(text);
- log(io, 'info', 'loaded catalog from remote', { url });
- return mergeWithBundled(parsed);
- } catch (err) {
- log(io, 'warn', 'remote catalog fetch/parse failed, falling back to bundled', { url, err: String(err) });
+ const fallbackUrl = resolveFallbackCatalogUrl(cfg);
+ if (!cfg.disableFetch && io.fetchText) {
+ const remoteUrls = cfg.url?.trim()
+ ? [url].filter((value): value is string => !!value)
+ : [url, fallbackUrl].filter((value): value is string => !!value);
+ const now = cfg.now ?? Date.now;
+ const configuredBudget = cfg.remoteBudgetMs ?? DEFAULT_REMOTE_CATALOG_BUDGET_MS;
+ const budgetMs = Number.isFinite(configuredBudget) ? Math.max(0, configuredBudget) : 0;
+ const deadline = now() + budgetMs;
+ for (const remoteUrl of remoteUrls) {
+ const remainingMs = Math.max(0, deadline - now());
+ if (remainingMs === 0) {
+ log(io, 'warn', 'remote catalog fallback budget exhausted');
+ break;
+ }
+ try {
+ const text = await io.fetchText(remoteUrl, remainingMs);
+ const parsed = parseCatalog(text);
+ log(io, 'info', 'loaded catalog from remote', { url: remoteUrl });
+ return mergeWithBundled(parsed);
+ } catch (err) {
+ log(io, 'warn', 'remote catalog read/parse failed, trying fallback', {
+ url: remoteUrl,
+ err: String(err),
+ });
+ }
}
}