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(models): 统一模型资料优先级并接入服务端本地目录 (#4108)

Dash7bf942a9ba5a
diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts
index f43e9b02f2..e7b52747f8 100644
--- a/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts
+++ b/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts
@@ -75,6 +75,26 @@ describe('managed Ollama model identity', () => {
expect(saved.runtimes.pi?.models.map((model) => model.id)).not.toContain('gone-local');
});
+ it.each(['Remote catalog name', 'glm-4.7-flash:latest'])(
+ 'preserves the resolved name %s through import and projection sync',
+ async (name) => {
+ let existing = providerWith('glm-4.7-flash:latest');
+ vi.mocked(getCustomProvider).mockImplementation(async () => existing);
+ vi.mocked(updateCustomProvider).mockImplementation(async (_id, next) => {
+ existing = next as typeof existing;
+ return next;
+ });
+ await upsertManagedOllamaModel({ id: 'glm-4.7-flash:latest', name });
+ for (const runtime of Object.values(existing.runtimes)) {
+ expect(runtime.models[0].name).toBe(name);
+ }
+ await syncManagedOllamaAgentProjections();
+ for (const runtime of Object.values(existing.runtimes)) {
+ expect(runtime.models[0].name).toBe(name);
+ }
+ },
+ );
+
it('does not write when the captured owner is no longer active', async () => {
const existing = providerWith('glm-4.7-flash');
vi.mocked(getCustomProvider).mockResolvedValue(existing);
diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts
index 4b265384f7..d446b0d547 100644
--- a/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts
+++ b/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts
@@ -47,6 +47,23 @@ function readyFetch(models: string[] = ['gpt-oss:20b']) {
}
describe('owner change during pull', () => {
+ it.each(['qwen3.8:27b', 'qwen3.8:27b-mxfp8', 'qwen3.8:27b-mlx'])(
+ 'retains client Qwen capabilities after curation withdrawal: %s',
+ async (name) => {
+ const service = createLocalModelService({
+ fetchImpl: readyFetch([name]),
+ getLocalCatalog: () => ({ version: 1, models: [], featuredIds: [] }),
+ });
+ await service.setModelInPicker(name, true);
+ expect(vi.mocked(upsertManagedOllamaModel).mock.calls.at(-1)?.[0]).toMatchObject({
+ reasoning: true,
+ reasoningEfforts: ['xhigh'],
+ reasoningDefaultEffort: 'xhigh',
+ supportsImageInput: true,
+ thinkingToggle: true,
+ });
+ },
+ );
beforeEach(() => {
vi.mocked(upsertManagedOllamaModel).mockClear();
vi.mocked(upsertManagedOllamaModels).mockClear();
@@ -82,16 +99,16 @@ describe('owner change during pull', () => {
});
await service.list({ owner: { dataOwnerId: 'bob', generation: 2 } });
- const importedByBob = vi.mocked(upsertManagedOllamaModels).mock.calls.flatMap(
- ([entries]) => entries.map((entry) => entry.model.id),
- );
+ const importedByBob = vi
+ .mocked(upsertManagedOllamaModels)
+ .mock.calls.flatMap(([entries]) => entries.map((entry) => entry.model.id));
expect(importedByBob).not.toContain('gpt-oss:20b');
vi.mocked(upsertManagedOllamaModels).mockClear();
await service.list({ owner: { dataOwnerId: 'alice', generation: 1 } });
- const importedByAlice = vi.mocked(upsertManagedOllamaModels).mock.calls.flatMap(
- ([entries]) => entries.map((entry) => entry.model.id),
- );
+ const importedByAlice = vi
+ .mocked(upsertManagedOllamaModels)
+ .mock.calls.flatMap(([entries]) => entries.map((entry) => entry.model.id));
expect(importedByAlice).toContain('gpt-oss:20b');
});
diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/service.pull.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/service.pull.test.ts
index d7e19dd924..b4fb2fd643 100644
--- a/apps/desktop/src/main/local-model-runtime/__tests__/service.pull.test.ts
+++ b/apps/desktop/src/main/local-model-runtime/__tests__/service.pull.test.ts
@@ -6,8 +6,10 @@ import type { PausedPullRecord } from '../pausedPullStore.js';
function memoryPausedStore(initial: PausedPullRecord[] = []) {
const items = new Map(initial.map((item) => [item.name, item]));
return {
- read: async (name?: string) => (name ? items.get(name) ?? null : [...items.values()][0] ?? null),
- readSync: (name?: string) => (name ? items.get(name) ?? null : [...items.values()][0] ?? null),
+ read: async (name?: string) =>
+ name ? (items.get(name) ?? null) : ([...items.values()][0] ?? null),
+ readSync: (name?: string) =>
+ name ? (items.get(name) ?? null) : ([...items.values()][0] ?? null),
readAll: async () => [...items.values()],
readAllSync: () => [...items.values()],
write: async (
@@ -46,8 +48,47 @@ function hangingPull(signal?: AbortSignal) {
}
describe('local model pull state machine', () => {
+ it('returns no recommendation when only unvalidated candidates fit', () => {
+ const service = createLocalModelService({
+ platform: 'darwin',
+ arch: 'arm64',
+ totalmem: () => 16 * 1024 ** 3,
+ pausedPullStore: memoryPausedStore(),
+ });
+ expect(service.recommend()).toBeNull();
+ });
+
+ it('reads the latest accepted catalog and observes recommendation withdrawal', () => {
+ let snapshot: unknown = { version: 1, models: [], featuredIds: [] };
+ const service = createLocalModelService({
+ platform: 'darwin',
+ arch: 'arm64',
+ totalmem: () => 16 * 1024 ** 3,
+ pausedPullStore: memoryPausedStore(),
+ getLocalCatalog: () => snapshot,
+ });
+ expect(service.recommend()).toBeNull();
+ snapshot = {
+ version: 1,
+ featuredIds: ['remote'],
+ models: [
+ {
+ id: 'remote',
+ name: 'Remote model',
+ aliases: [],
+ variants: [{ libraryName: 'remote:4b', sizeBytes: 4 * 1024 ** 3, minUnifiedMemoryGb: 8 }],
+ },
+ ],
+ };
+ expect(service.recommend()?.libraryName).toBe('remote:4b');
+ snapshot = { version: 1, models: [], featuredIds: [] };
+ expect(service.recommend()).toBeNull();
+ });
+
it('joins the same model and starts a second name in parallel', async () => {
- const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) => hangingPull(signal));
+ const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) =>
+ hangingPull(signal),
+ );
const service = createLocalModelService({
streamPull,
pausedPullStore: memoryPausedStore(),
@@ -59,10 +100,12 @@ describe('local model pull state machine', () => {
await vi.waitFor(() => {
expect(streamPull).toHaveBeenCalledTimes(2);
});
- expect(service.activePulls().map((item) => item.name).sort()).toEqual([
- 'gpt-oss:20b',
- 'llama3.1:8b',
- ]);
+ expect(
+ service
+ .activePulls()
+ .map((item) => item.name)
+ .sort(),
+ ).toEqual(['gpt-oss:20b', 'llama3.1:8b']);
expect(streamPull.mock.calls.filter((call) => call[0] === 'gpt-oss:20b')).toHaveLength(1);
await service.abortPull('pause', 'gpt-oss:20b');
await service.abortPull('pause', 'llama3.1:8b');
@@ -88,7 +131,9 @@ describe('local model pull state machine', () => {
});
it('joins an untagged pull with its :latest alias', async () => {
- const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) => hangingPull(signal));
+ const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) =>
+ hangingPull(signal),
+ );
const service = createLocalModelService({
streamPull,
pausedPullStore: memoryPausedStore(),
@@ -185,7 +230,9 @@ describe('local model pull state machine', () => {
it('does not delete an untagged pull that Ollama already lists as :latest', async () => {
const deleteModel = vi.fn(async () => undefined);
const purgeCancelledPull = vi.fn(async () => undefined);
- const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) => hangingPull(signal));
+ const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) =>
+ hangingPull(signal),
+ );
let installed: Array<{ name: string }> = [];
const service = createLocalModelService({
streamPull,
@@ -220,7 +267,9 @@ describe('local model pull state machine', () => {
it('remembers a paused pull so a new service can resume or discard it', async () => {
const pausedPullStore = memoryPausedStore();
- const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) => hangingPull(signal));
+ const streamPull = vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) =>
+ hangingPull(signal),
+ );
const first = createLocalModelService({
streamPull,
pausedPullStore,
@@ -257,7 +306,9 @@ describe('local model pull state machine', () => {
it('keeps an in-flight pull after the process restarts', async () => {
const pausedPullStore = memoryPausedStore();
const first = createLocalModelService({
- streamPull: vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) => hangingPull(signal)),
+ streamPull: vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) =>
+ hangingPull(signal),
+ ),
pausedPullStore,
fetchImpl: async () => new Response(JSON.stringify({ models: [] })),
});
@@ -283,7 +334,12 @@ describe('local model pull state machine', () => {
const streamPull = vi.fn(
(
_name: string,
- onEvent: (event: { status: string; digest?: string; completed?: number; total?: number }) => void,
+ onEvent: (event: {
+ status: string;
+ digest?: string;
+ completed?: number;
+ total?: number;
+ }) => void,
signal?: AbortSignal,
) => {
onEvent({ status: 'downloading', digest: 'sha256:ccc', completed: 1, total: 10 });
@@ -325,7 +381,12 @@ describe('local model pull state machine', () => {
const streamPull = vi.fn(
(
_name: string,
- onEvent: (event: { status: string; digest?: string; completed?: number; total?: number }) => void,
+ onEvent: (event: {
+ status: string;
+ digest?: string;
+ completed?: number;
+ total?: number;
+ }) => void,
signal?: AbortSignal,
) => {
onEvent({ status: 'downloading', digest: 'sha256:shared', completed: 1, total: 10 });
@@ -370,7 +431,9 @@ describe('local model pull state machine', () => {
const purgeCancelledPull = vi.fn(async () => undefined);
const pausedPullStore = memoryPausedStore();
const first = createLocalModelService({
- streamPull: vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) => hangingPull(signal)),
+ streamPull: vi.fn((_name: string, _onEvent: unknown, signal?: AbortSignal) =>
+ hangingPull(signal),
+ ),
pausedPullStore,
fetchImpl: async () => new Response(JSON.stringify({ models: [] })),
});
@@ -403,7 +466,12 @@ describe('local model pull state machine', () => {
const streamPull = vi.fn(
(
_name: string,
- onEvent: (event: { status: string; digest?: string; completed?: number; total?: number }) => void,
+ onEvent: (event: {
+ status: string;
+ digest?: string;
+ completed?: number;
+ total?: number;
+ }) => void,
) => {
onEvent({ status: 'downloading', digest: 'sha256:abc', completed: 1, total: 10 });
return Promise.resolve();
diff --git a/apps/desktop/src/main/local-model-runtime/ipc.ts b/apps/desktop/src/main/local-model-runtime/ipc.ts
index 5569d8b78f..87480b25d8 100644
--- a/apps/desktop/src/main/local-model-runtime/ipc.ts
+++ b/apps/desktop/src/main/local-model-runtime/ipc.ts
@@ -1,3 +1,4 @@
+import { getActiveLocalModelCatalog } from '../maker-host/active-catalog.js';
import {
normalizeOllamaPullName,
type LocalInstalledModel,
@@ -59,6 +60,7 @@ export function registerLocalModelHandlers(
const service =
deps.service ??
createLocalModelService({
+ getLocalCatalog: getActiveLocalModelCatalog,
onStatus: deps.broadcastStatus,
onPullProgress: deps.broadcastPullProgress,
onInstallProgress: deps.broadcastInstallProgress,
diff --git a/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts b/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts
index 0e8d5be0f7..c82052b723 100644
--- a/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts
+++ b/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts
@@ -129,7 +129,7 @@ function toAgentModel(
): ProviderRuntimeModelConfig {
const named = {
...model,
- name: curatedOllamaDisplayName(model.id) ?? model.name,
+ name: model.name || curatedOllamaDisplayName(model.id) || model.id,
};
if (agent === 'pi') return named;
return {
diff --git a/apps/desktop/src/main/local-model-runtime/service.ts b/apps/desktop/src/main/local-model-runtime/service.ts
index 56f7bc1e2a..bef92248d2 100644
--- a/apps/desktop/src/main/local-model-runtime/service.ts
+++ b/apps/desktop/src/main/local-model-runtime/service.ts
@@ -4,12 +4,12 @@ import path from 'node:path';
import { createLogger } from '../logger.js';
import {
canonicalOllamaModelRef,
+ findCuratedOllamaModel,
isCuratedQwen38Tag,
isOllamaModelName,
normalizeOllamaPullName,
ollamaModelRefsEqual,
recommendForHost,
- recommendQwen38,
resolveManagedOllamaAgents,
resolveOllamaModelLists,
type CuratedOllamaModel,
@@ -138,6 +138,7 @@ export interface LocalModelService {
}
export interface LocalModelServiceDeps {
+ getLocalCatalog?: () => unknown;
platform?: NodeJS.Platform;
arch?: string;
totalmem?: () => number;
@@ -216,10 +217,7 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
const pausedPullStore =
deps.pausedPullStore ??
createPausedPullStore(
- path.join(
- deps.userDataDir ?? os.tmpdir(),
- 'local-model-paused-pull.json',
- ),
+ path.join(deps.userDataDir ?? os.tmpdir(), 'local-model-paused-pull.json'),
);
const actives = new Map<string, ActivePull>();
const pausedByName = new Map<string, LocalModelPullProgress>();
@@ -249,10 +247,7 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
}
}
- function tagsIncludeModel(
- tags: readonly { name: string }[],
- name: string,
- ): boolean {
+ function tagsIncludeModel(tags: readonly { name: string }[], name: string): boolean {
return tags.some((tag) => ollamaModelRefsEqual(tag.name, name));
}
@@ -355,7 +350,10 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
return [...pausedByName.values()];
}
- async function rememberPaused(progress: LocalModelPullProgress, digests: readonly string[]): Promise<void> {
+ async function rememberPaused(
+ progress: LocalModelPullProgress,
+ digests: readonly string[],
+ ): Promise<void> {
const next: LocalModelPullProgress = {
...progress,
phase: 'paused',
@@ -387,10 +385,13 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
return record;
}
- function visiblePulls(extraPaused: readonly LocalModelPullProgress[] = []): LocalModelPullProgress[] {
+ function visiblePulls(
+ extraPaused: readonly LocalModelPullProgress[] = [],
+ ): LocalModelPullProgress[] {
const byName = new Map<string, LocalModelPullProgress>();
for (const item of extraPaused) byName.set(canonicalOllamaModelRef(item.name), item);
- for (const op of actives.values()) byName.set(canonicalOllamaModelRef(op.name), op.lastProgress);
+ for (const op of actives.values())
+ byName.set(canonicalOllamaModelRef(op.name), op.lastProgress);
return [...byName.values()];
}
@@ -433,20 +434,8 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
arch: deps.arch ?? process.arch,
totalmemBytes: (deps.totalmem ?? os.totalmem)(),
};
- return (
- recommendQwen38(input) ??
- (() => {
- const primary = recommendForHost(input).primary;
- return {
- id: primary.libraryName,
- name: primary.name,
- libraryName: primary.libraryName,
- sizeBytes: primary.sizeBytes,
- minUnifiedMemoryGb: primary.minUnifiedMemoryGb,
- appleSiliconOnly: primary.appleSiliconOnly,
- };
- })()
- );
+ const primary = recommendForHost(input, deps.getLocalCatalog?.()).primary;
+ return primary ? { ...primary, id: primary.libraryName } : null;
}
async function cindyModelIds(): Promise<Set<string>> {
@@ -457,11 +446,14 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
}
function listsForHost() {
- return resolveOllamaModelLists({
- platform,
- arch: deps.arch ?? process.arch,
- totalmemBytes: (deps.totalmem ?? os.totalmem)(),
- });
+ return resolveOllamaModelLists(
+ {
+ platform,
+ arch: deps.arch ?? process.arch,
+ totalmemBytes: (deps.totalmem ?? os.totalmem)(),
+ },
+ deps.getLocalCatalog?.(),
+ );
}
async function list(opts?: {
@@ -886,9 +878,11 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Local
} catch {
/* show is best-effort */
}
+ const curated = findCuratedOllamaModel(name, deps.getLocalCatalog?.());
const model = isCuratedQwen38Tag(name)
? toQwenRuntimeModel(name, contextLength)
: toPlainRuntimeModel(name, contextLength);
+ if (curated) model.name = curated.name;
return {
model,
agents: resolveManagedOllamaAgents({
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
index 27f66c502d..eaa740581f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -98,39 +98,71 @@ describe('active-catalog discovered augment', () => {
it('keeps native subscription maxima through Registry refresh and Claude projection', () => {
for (const window of [272000, 400000]) {
const catalog = structuredClone(BUNDLED_CATALOG);
- const entry = catalog.modelRegistry!.models.find((model) => model.id === 'openai/gpt-6-astra')!;
+ const entry = catalog.modelRegistry!.models.find(
+ (model) => model.id === 'openai/gpt-6-astra',
+ )!;
entry.contextWindow = window;
catalog.modelRegistry!.updatedAt = `2099-01-01T00:00:0${window === 272000 ? 1 : 2}.000Z`;
setActiveCatalog(catalog, { authorityCatalog: catalog });
- setDiscoveredCodexModels([{
- ...fake('gpt-6-astra'), contextWindow: 272000, contextWindowMax: 872000,
- contextWindowVerified: true, supportsImageInput: false, supportsFastMode: false,
- }]);
+ setDiscoveredCodexModels([
+ {
+ ...fake('gpt-6-astra'),
+ contextWindow: 272000,
+ contextWindowMax: 872000,
+ contextWindowVerified: true,
+ supportsImageInput: false,
+ supportsFastMode: false,
+ },
+ ]);
const openai = getActiveCatalog().providers.find((provider) => provider.id === 'openai')!;
for (const agent of ['codex', 'claude-code'] as const) {
- expect(openai.models[agent]!.find((model) => model.id.endsWith('gpt-6-astra'))).toMatchObject({
- contextWindow: 272000, contextWindowMax: 872000, supportsImageInput: false, supportsFastMode: false,
+ expect(
+ openai.models[agent]!.find((model) => model.id.endsWith('gpt-6-astra')),
+ ).toMatchObject({
+ contextWindow: 272000,
+ contextWindowMax: 872000,
+ supportsImageInput: false,
+ supportsFastMode: false,
});
}
// Independent Pi metadata does not acquire Codex-only native limits.
- expect(openai.models.pi!.find((model) => model.id.endsWith('gpt-6-astra'))?.contextWindowMax)
- .not.toBe(872000);
+ expect(
+ openai.models.pi!.find((model) => model.id.endsWith('gpt-6-astra'))?.contextWindowMax,
+ ).not.toBe(872000);
}
});
it('partial live lists retain cached metadata, replace membership, and respect auth clearing', () => {
setActiveCatalog(bundledWithoutRegistry(), { authorityCatalog: bundledWithoutRegistry() });
const cached = {
- ...fake('gpt-99'), contextWindow: 200000, contextWindowMax: 900000,
- contextWindowVerified: true, supportsImageInput: false, supportsFastMode: true,
+ ...fake('gpt-99'),
+ contextWindow: 200000,
+ contextWindowMax: 900000,
+ contextWindowVerified: true,
+ supportsImageInput: false,
+ supportsFastMode: true,
};
setDiscoveredCodexModels([cached, fake('gpt-removed')]);
- const live = { ...fake('gpt-99'), contextWindow: 272000, supportsFastMode: false };
+ const live = {
+ ...fake('gpt-99'),
+ contextWindow: 272000,
+ supportsFastMode: false,
+ discoveredMetadata: { supportsFastMode: false },
+ };
setDiscoveredCodexModels([live, fake('gpt-new')], { source: 'list' });
- const models = () => getActiveCatalog().providers.find((provider) => provider.id === 'openai')!.models.codex!;
+ const models = () =>
+ getActiveCatalog().providers.find((provider) => provider.id === 'openai')!.models.codex!;
expect(models().map((model) => model.id)).not.toContain('gpt-removed');
expect(models().find((model) => model.id === 'gpt-99')).toMatchObject({
- contextWindow: 200000, contextWindowMax: 900000, supportsImageInput: false, supportsFastMode: false,
+ contextWindow: 200000,
+ contextWindowMax: 900000,
+ supportsImageInput: false,
+ supportsFastMode: false,
+ discoveredMetadata: {
+ contextWindow: 200000,
+ supportsImageInput: false,
+ supportsFastMode: false,
+ },
});
setDiscoveredCodexModels([]);
setDiscoveredCodexModels([live], { source: 'list' });
@@ -238,15 +270,15 @@ describe('active-catalog discovered augment', () => {
});
});
- it('keeps official Grok 4.6 xhigh when SuperGrok discovery omits the new ladder rung', () => {
+ it('uses explicit SuperGrok capabilities while Pi retains its independent native facts', () => {
setActiveCatalog(BUNDLED_CATALOG);
setXaiDiscoveredModels([
{ id: 'xai/grok-4.6', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' },
]);
const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
- // Server Registry 和独立 Pi 目录均声明 xhigh,不被旧 discovery 降档。
+ // 供应商显式列表覆盖默认;Pi 使用自己的原生能力来源。
expect(xai?.models['claude-code']?.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({
- efforts: ['low', 'medium', 'high', 'xhigh'],
+ efforts: ['low', 'medium', 'high'],
defaultEffort: 'medium',
});
expect(xai?.models.pi?.find((model) => model.id === 'grok-4.6')).toMatchObject({
@@ -287,7 +319,7 @@ describe('active-catalog discovered augment', () => {
const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
expect(xai?.models['claude-code']?.find((model) => model.id === 'xai/grok-4.5')).toMatchObject({
efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
+ defaultEffort: 'high',
});
expect(xai?.models.pi?.find((model) => model.id === 'grok-4.5')).toMatchObject({
efforts: ['low', 'medium', 'high'],
@@ -295,7 +327,7 @@ describe('active-catalog discovered augment', () => {
});
});
- it('keeps the Cindy model default when SuperGrok discovery suggests a different default', () => {
+ it('uses the explicit SuperGrok default before registry defaults', () => {
setActiveCatalog(BUNDLED_CATALOG);
setXaiDiscoveredModels([
{ id: 'xai/grok-4.5', efforts: ['low', 'medium', 'high'], defaultEffort: 'low' },
@@ -304,7 +336,7 @@ describe('active-catalog discovered augment', () => {
const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
expect(xai?.models['claude-code']?.find((model) => model.id === 'xai/grok-4.5')).toMatchObject({
efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
+ defaultEffort: 'low',
});
expect(xai?.models.pi?.find((model) => model.id === 'grok-4.5')).toMatchObject({
efforts: ['low', 'medium', 'high'],
@@ -513,7 +545,7 @@ describe('anthropic 发现条目的 modelRegistry 元数据基线', () => {
setAnthropicDiscoveredModels([]);
});
- it('基线统一 Anthropic 名字与排序,新模型不透传 Claude 前缀', () => {
+ it('供应商显式名称优先,缺项继承公共名称与排序', () => {
setActiveCatalog(BUNDLED_CATALOG);
setAnthropicDiscoveredModels([
anthro('claude-opus-5', 'Claude Opus 5', 0),
@@ -528,23 +560,25 @@ describe('anthropic 发现条目的 modelRegistry 元数据基线', () => {
anthro('claude-sonnet-4-5', 'Claude Sonnet 4.5', 9),
]);
expect(anthropicList().map((m) => [m.id, m.name])).toEqual([
- ['claude-opus-5', 'Opus 5'],
- ['claude-fable-5', 'Fable 5'],
- ['claude-opus-4-8', 'Opus 4.8'],
- ['claude-opus-4-7', 'Opus 4.7'],
- ['claude-opus-4-6', 'Opus 4.6'],
- ['claude-opus-4-5', 'Opus 4.5'],
- ['claude-sonnet-5', 'Sonnet 5'],
- ['claude-sonnet-4-6', 'Sonnet 4.6'],
- ['claude-sonnet-4-5', 'Sonnet 4.5'],
- ['claude-haiku-4-5', 'Haiku 4.5'],
+ ['claude-opus-5', 'Claude Opus 5'],
+ ['claude-fable-5', 'Claude Fable 5'],
+ ['claude-opus-4-8', 'Claude Opus 4.8'],
+ ['claude-opus-4-7', 'Claude Opus 4.7'],
+ ['claude-opus-4-6', 'Claude Opus 4.6'],
+ ['claude-opus-4-5', 'Claude Opus 4.5'],
+ ['claude-sonnet-5', 'Claude Sonnet 5'],
+ ['claude-sonnet-4-6', 'Claude Sonnet 4.6'],
+ ['claude-sonnet-4-5', 'Claude Sonnet 4.5'],
+ ['claude-haiku-4-5', 'Claude Haiku 4.5'],
['claude-fable-5-1', 'Fable 5.1'],
['claude-mythos-5', 'Mythos 5'],
]);
- expect(anthropicList('claude-code').filter((model) => model.defaultEnabled !== false)
- .map((model) => model.id).sort()).toEqual([
- 'claude-fable-5-1', 'claude-haiku-4-5', 'claude-opus-5', 'claude-sonnet-5',
- ]);
+ expect(
+ anthropicList('claude-code')
+ .filter((model) => model.defaultEnabled !== false)
+ .map((model) => model.id)
+ .sort(),
+ ).toEqual(['claude-fable-5-1', 'claude-haiku-4-5', 'claude-opus-5', 'claude-sonnet-5']);
expect(anthropicList('codex')).toEqual(
anthropicList('claude-code').map((model) => ({
...model,
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
index ee7b75bf1c..f55bab7b9d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
@@ -39,26 +39,46 @@ afterEach(() => {
describe('XD 网关权威模型清单重建', () => {
it('defaults every maintained GPT route to 272K while retaining capacity and smaller/non-GPT windows', () => {
const ids = [
- 'codex/gpt-6-astra', 'openai/gpt-6-astra',
- 'codex/gpt-5.6-sol', 'codex/gpt-5.6-terra', 'codex/gpt-5.6-luna',
- 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna',
- 'codex/gpt-5.5', 'codex/gpt-5.5:auto', 'gpt-5.5',
- 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.4-nano', 'codex/gpt-5.4-mini',
+ 'codex/gpt-6-astra',
+ 'openai/gpt-6-astra',
+ 'codex/gpt-5.6-sol',
+ 'codex/gpt-5.6-terra',
+ 'codex/gpt-5.6-luna',
+ 'gpt-5.6-sol',
+ 'gpt-5.6-terra',
+ 'gpt-5.6-luna',
+ 'codex/gpt-5.5',
+ 'codex/gpt-5.5:auto',
+ 'gpt-5.5',
+ 'gpt-5.4',
+ 'gpt-5.4-mini',
+ 'gpt-5.4-nano',
+ 'codex/gpt-5.4-mini',
];
setActiveCatalog(BUNDLED_CATALOG);
- setXdGatewayModels([
- ...ids.map(id => ({ id, name: id, agents: ['claude-code', 'codex', 'pi'] as const,
- contextWindow: 1_050_000 })),
- { id: 'gpt-4-small', agents: ['codex'] as const, contextWindow: 128_000 },
- { id: 'z-ai/glm-5.3-flash', agents: ['codex'] as const, contextWindow: 1_000_000 },
- ].map(m => ({ ...m, agents: [...m.agents] })));
+ setXdGatewayModels(
+ [
+ ...ids.map((id) => ({
+ id,
+ name: id,
+ agents: ['claude-code', 'codex', 'pi'] as const,
+ contextWindow: 1_050_000,
+ })),
+ { id: 'gpt-4-small', agents: ['codex'] as const, contextWindow: 128_000 },
+ { id: 'z-ai/glm-5.3-flash', agents: ['codex'] as const, contextWindow: 1_000_000 },
+ ].map((m) => ({ ...m, agents: [...m.agents] })),
+ );
for (const agent of ['claude-code', 'codex', 'pi'] as const) {
- for (const id of ids) expect(xdModels(agent).find(m => m.id === id)).toMatchObject({
- contextWindow: 272_000, contextWindowMax: 1_050_000,
- });
+ for (const id of ids)
+ expect(xdModels(agent).find((m) => m.id === id)).toMatchObject({
+ contextWindow: 272_000,
+ contextWindowMax: 1_050_000,
+ });
}
- expect(xdModels('codex').find(m => m.id === 'gpt-4-small')?.contextWindow).toBe(128_000);
- expect(xdModels('codex').find(m => m.id === 'z-ai/glm-5.3-flash')?.contextWindow).toBe(1_000_000);
+ expect(xdModels('codex').find((m) => m.id === 'gpt-4-small')?.contextWindow).toBe(128_000);
+ expect(xdModels('codex').find((m) => m.id === 'z-ai/glm-5.3-flash')?.contextWindow).toBe(
+ 1_000_000,
+ );
});
it('未拉到实时清单时不暴露任何 XD 模型', () => {
@@ -276,19 +296,23 @@ describe('XD 网关权威模型清单重建', () => {
expect(activeXd?.embeddingDefaults).toBeUndefined();
});
- it('uses the model default for every Gateway harness and only adapts unsupported levels', () => {
+ it('uses supplier per-harness defaults and only adapts unsupported levels', () => {
setActiveCatalog(BUNDLED_CATALOG);
- setXdGatewayModels([{
- id: 'future-reasoner', agents: ['claude-code', 'codex', 'pi'],
- efforts: ['low', 'medium', 'high'], defaultEffort: 'high',
- perAgent: {
- codex: { defaultEffort: 'high' },
- pi: { defaultEffort: 'low' },
- 'claude-code': { efforts: ['low'], defaultEffort: 'low' },
- },
- }]);
- expect(xdModels('codex')[0]?.defaultEffort).toBe('medium');
- expect(xdModels('pi')[0]?.defaultEffort).toBe('medium');
+ setXdGatewayModels([
+ {
+ id: 'future-reasoner',
+ agents: ['claude-code', 'codex', 'pi'],
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'high',
+ perAgent: {
+ codex: { defaultEffort: 'high' },
+ pi: { defaultEffort: 'low' },
+ 'claude-code': { efforts: ['low'], defaultEffort: 'low' },
+ },
+ },
+ ]);
+ expect(xdModels('codex')[0]?.defaultEffort).toBe('high');
+ expect(xdModels('pi')[0]?.defaultEffort).toBe('low');
expect(xdModels('claude-code')[0]?.defaultEffort).toBe('low');
});
@@ -299,29 +323,44 @@ describe('XD 网关权威模型清单重建', () => {
['z-ai/glm-5.3-flash', 'max'],
['deepseek/deepseek-v4-flash-vision-exp', 'high'],
['tencent/hy4-preview', 'high'],
- ] as const)('常用模型 %s 的三个 Harness 都采用 Cindy 默认中,保留 Gateway 的窗口和能力', (id, oldDefault) => {
- setActiveCatalog(BUNDLED_CATALOG);
- setXdGatewayModels([{
- id, name: id, agents: ['claude-code', 'codex', 'pi'],
- efforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
- defaultEffort: oldDefault, contextWindow: 987654,
- perAgent: { pi: { defaultEffort: 'max' } },
- }]);
- for (const agent of ['claude-code', 'codex', 'pi'] as const) {
- expect(xdModels(agent)[0]).toMatchObject({ defaultEffort: 'medium', contextWindow: 987654 });
- }
- });
+ ] as const)(
+ '常用模型 %s 的三个 Harness 保留 Gateway 明示的默认、窗口和能力',
+ (id, oldDefault) => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setXdGatewayModels([
+ {
+ id,
+ name: id,
+ agents: ['claude-code', 'codex', 'pi'],
+ efforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
+ defaultEffort: oldDefault,
+ contextWindow: 987654,
+ perAgent: { pi: { defaultEffort: 'max' } },
+ },
+ ]);
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ expect(xdModels(agent)[0]).toMatchObject({
+ defaultEffort: agent === 'pi' ? 'max' : oldDefault,
+ contextWindow: 987654,
+ });
+ }
+ },
+ );
it('新的 Server Registry 可更新默认;实际不支持的档位只适配,不增加能力', () => {
const catalog = structuredClone(BUNDLED_CATALOG);
- const entry = catalog.modelRegistry!.models.find(m => m.id === 'xd/z-ai-glm-5.3-flash')!;
+ const entry = catalog.modelRegistry!.models.find((m) => m.id === 'xd/z-ai-glm-5.3-flash')!;
entry.defaultEffort = 'high';
setActiveCatalog(catalog);
- setXdGatewayModels([{
- id: 'z-ai/glm-5.3-flash', agents: ['claude-code', 'codex', 'pi'],
- efforts: ['low', 'medium', 'high'], defaultEffort: 'max',
- perAgent: { 'claude-code': { efforts: ['low'] }, codex: { efforts: [] } },
- }]);
+ setXdGatewayModels([
+ {
+ id: 'z-ai/glm-5.3-flash',
+ agents: ['claude-code', 'codex', 'pi'],
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'max',
+ perAgent: { 'claude-code': { efforts: ['low'] }, codex: { efforts: [] } },
+ },
+ ]);
expect(xdModels('pi')[0]?.defaultEffort).toBe('high');
expect(xdModels('claude-code')[0]).toMatchObject({ efforts: ['low'], defaultEffort: 'low' });
expect(xdModels('codex')[0]).toMatchObject({ efforts: [], defaultEffort: null });
@@ -517,7 +556,7 @@ describe('XD 网关权威模型清单重建', () => {
});
});
- it('服务端决定成员和能力,默认深度优先 Cindy Registry', () => {
+ it('服务端决定成员和能力,供应商显式默认优先于 Registry', () => {
setActiveCatalog(BUNDLED_CATALOG);
setXdGatewayModels([
{
@@ -541,7 +580,7 @@ describe('XD 网关权威模型清单重建', () => {
contextWindow: 272_000,
contextWindowMax: 372_000,
efforts: ['low', 'medium', 'high', 'xhigh'],
- defaultEffort: 'medium',
+ defaultEffort: 'high',
});
}
expect('codexCompatibilityWireProtocol' in xdModels('codex')[0]).toBe(false);
@@ -831,18 +870,34 @@ describe('gateway cross-harness defaults', () => {
['tencent/hy4-preview', ['text']],
] as const;
const live = candidates.map(([id, input]) => ({
- id, name: id, mode: 'chat', agents: ['claude-code', 'codex', 'pi'] as const,
- defaultEnabled: true, modalities: { input: [...input], output: ['text'] },
+ id,
+ name: id,
+ mode: 'chat',
+ agents: ['claude-code', 'codex', 'pi'] as const,
+ defaultEnabled: true,
+ modalities: { input: [...input], output: ['text'] },
perAgent: { pi: { wireProtocol: 'openai-responses' as const } },
}));
- setXdGatewayModels(live.map(model => ({ ...model, agents: [...model.agents] })));
- const enabled = () => xdModels('pi').filter(model => model.defaultEnabled !== false).map(model => model.id);
- expect(enabled().sort()).toEqual(['deepseek/deepseek-v4-flash-vision-exp', 'tencent/hy4-preview']);
+ setXdGatewayModels(live.map((model) => ({ ...model, agents: [...model.agents] })));
+ const enabled = () =>
+ xdModels('pi')
+ .filter((model) => model.defaultEnabled !== false)
+ .map((model) => model.id);
+ expect(enabled().sort()).toEqual([
+ 'deepseek/deepseek-v4-flash-vision-exp',
+ 'tencent/hy4-preview',
+ ]);
for (const agent of ['claude-code', 'codex'] as const) {
- expect(xdModels(agent).every(model => model.defaultEnabled === false)).toBe(true);
+ expect(xdModels(agent).every((model) => model.defaultEnabled === false)).toBe(true);
}
- expect(xdModels('pi').every(model => model.piApi === 'openai-completions')).toBe(true);
- setXdGatewayModels(live.map(model => ({ ...model, agents: [...model.agents], modalities: { input: ['text'], output: ['text'] } })));
+ expect(xdModels('pi').every((model) => model.piApi === 'openai-completions')).toBe(true);
+ setXdGatewayModels(
+ live.map((model) => ({
+ ...model,
+ agents: [...model.agents],
+ modalities: { input: ['text'], output: ['text'] },
+ })),
+ );
expect(enabled().sort()).toEqual(['deepseek/deepseek-v4-pro', 'tencent/hy4-preview']);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexModelDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexModelDiscovery.test.ts
index 602970c43d..de7351ddce 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexModelDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexModelDiscovery.test.ts
@@ -23,55 +23,149 @@ import {
// 取自本机 ~/.codex/models_cache.json 的真实结构(裁剪到关键字段)。
const SAMPLE = {
models: [
- { slug: 'gpt-5.5', display_name: 'GPT-5.5', description: 'Frontier model.', visibility: 'list', supported_in_api: true, context_window: 272000, default_reasoning_level: 'medium', priority: 7, supported_reasoning_levels: [{ effort: 'low' }, { effort: 'medium' }, { effort: 'high' }, { effort: 'xhigh' }], service_tiers: [{ id: 'priority', name: 'Fast', description: '1.5x speed, increased usage' }] },
- { slug: 'gpt-5.4', display_name: 'GPT-5.4', visibility: 'list', supported_in_api: true, context_window: 272000, default_reasoning_level: 'medium', priority: 16, supported_reasoning_levels: [{ effort: 'low' }, { effort: 'medium' }, { effort: 'high' }, { effort: 'xhigh' }], service_tiers: [] },
+ {
+ slug: 'gpt-5.5',
+ display_name: 'GPT-5.5',
+ description: 'Frontier model.',
+ visibility: 'list',
+ supported_in_api: true,
+ context_window: 272000,
+ default_reasoning_level: 'medium',
+ priority: 7,
+ supported_reasoning_levels: [
+ { effort: 'low' },
+ { effort: 'medium' },
+ { effort: 'high' },
+ { effort: 'xhigh' },
+ ],
+ service_tiers: [{ id: 'priority', name: 'Fast', description: '1.5x speed, increased usage' }],
+ },
+ {
+ slug: 'gpt-5.4',
+ display_name: 'GPT-5.4',
+ visibility: 'list',
+ supported_in_api: true,
+ context_window: 272000,
+ default_reasoning_level: 'medium',
+ priority: 16,
+ supported_reasoning_levels: [
+ { effort: 'low' },
+ { effort: 'medium' },
+ { effort: 'high' },
+ { effort: 'xhigh' },
+ ],
+ service_tiers: [],
+ },
// 未来新模型:应被自动纳入(这正是 live 发现要解决的"下周出 5.6")
- { slug: 'gpt-5.6', display_name: 'GPT-5.6', visibility: 'list', supported_in_api: true, context_window: 400000, default_reasoning_level: 'high', priority: 3, supported_reasoning_levels: [{ effort: 'low' }, { effort: 'high' }, { effort: 'xhigh' }, { effort: 'max' }, { effort: 'ultra' }] },
+ {
+ slug: 'gpt-5.6',
+ display_name: 'GPT-5.6',
+ visibility: 'list',
+ supported_in_api: true,
+ context_window: 400000,
+ default_reasoning_level: 'high',
+ priority: 3,
+ supported_reasoning_levels: [
+ { effort: 'low' },
+ { effort: 'high' },
+ { effort: 'xhigh' },
+ { effort: 'max' },
+ { effort: 'ultra' },
+ ],
+ },
// 隐藏 / 非 api 的内部货:应被过滤
- { slug: 'gpt-5.3-codex-spark', display_name: 'Spark', visibility: 'list', supported_in_api: false, context_window: 128000, supported_reasoning_levels: [{ effort: 'high' }] },
- { slug: 'codex-auto-review', display_name: 'Auto Review', visibility: 'hide', supported_in_api: true, context_window: 272000, supported_reasoning_levels: [{ effort: 'medium' }] },
+ {
+ slug: 'gpt-5.3-codex-spark',
+ display_name: 'Spark',
+ visibility: 'list',
+ supported_in_api: false,
+ context_window: 128000,
+ supported_reasoning_levels: [{ effort: 'high' }],
+ },
+ {
+ slug: 'codex-auto-review',
+ display_name: 'Auto Review',
+ visibility: 'hide',
+ supported_in_api: true,
+ context_window: 272000,
+ supported_reasoning_levels: [{ effort: 'medium' }],
+ },
],
};
const OAUTH_AUTH = JSON.stringify({ tokens: { access_token: 'oauth-token' } });
describe('mapCodexModelsToCatalog', () => {
it('retains native maximum and explicit image capability separately from defaults', () => {
- const [model] = mapCodexModelsToCatalog({ models: [{
- ...SAMPLE.models[0], context_window: 272000, max_context_window: 872000,
- input_modalities: ['text', 'image'],
- }] });
+ const [model] = mapCodexModelsToCatalog({
+ models: [
+ {
+ ...SAMPLE.models[0],
+ context_window: 272000,
+ max_context_window: 872000,
+ input_modalities: ['text', 'image'],
+ },
+ ],
+ });
expect(model).toMatchObject({
- contextWindow: 272000, contextWindowMax: 872000,
- contextWindowVerified: true, supportsImageInput: true,
+ contextWindow: 272000,
+ contextWindowMax: 872000,
+ contextWindowVerified: true,
+ supportsImageInput: true,
+ discoveredMetadata: { supportsImageInput: true },
+ });
+ const [textOnly] = mapCodexModelsToCatalog({
+ models: [
+ {
+ ...SAMPLE.models[0],
+ input_modalities: ['text'],
+ },
+ ],
});
- const [textOnly] = mapCodexModelsToCatalog({ models: [{
- ...SAMPLE.models[0], input_modalities: ['text'],
- }] });
expect(textOnly.supportsImageInput).toBe(false);
+ expect(textOnly.discoveredMetadata?.supportsImageInput).toBe(false);
expect(textOnly.contextWindowMax).toBeUndefined();
});
it.each([undefined, 0, -1, NaN, Infinity, 2.5, 128000])(
- 'does not claim an invalid maximum (%s)', (maximum) => {
- const [model] = mapCodexModelsToCatalog({ models: [{
- ...SAMPLE.models[0], max_context_window: maximum,
- }] });
+ 'does not claim an invalid maximum (%s)',
+ (maximum) => {
+ const [model] = mapCodexModelsToCatalog({
+ models: [
+ {
+ ...SAMPLE.models[0],
+ max_context_window: maximum,
+ },
+ ],
+ });
expect(model.contextWindowMax).toBeUndefined();
},
);
- it.each([0, -1, NaN, Infinity, 2.5])('does not mark an invalid working window verified (%s)', (window) => {
- const [model] = mapCodexModelsToCatalog({ models: [{
- ...SAMPLE.models[0], context_window: window,
- }] });
- expect(model.contextWindowVerified).toBeUndefined();
- });
+ it.each([0, -1, NaN, Infinity, 2.5])(
+ 'does not mark an invalid working window verified (%s)',
+ (window) => {
+ const [model] = mapCodexModelsToCatalog({
+ models: [
+ {
+ ...SAMPLE.models[0],
+ context_window: window,
+ },
+ ],
+ });
+ expect(model.contextWindowVerified).toBeUndefined();
+ },
+ );
it('adapts a stale native default to supported efforts without selecting an unsupported tier', () => {
- const [model] = mapCodexModelsToCatalog({ models: [{
- ...SAMPLE.models[0], default_reasoning_level: 'ultra',
- supported_reasoning_levels: [{ effort: 'low' }, { effort: 'medium' }],
- }] });
+ const [model] = mapCodexModelsToCatalog({
+ models: [
+ {
+ ...SAMPLE.models[0],
+ default_reasoning_level: 'ultra',
+ supported_reasoning_levels: [{ effort: 'low' }, { effort: 'medium' }],
+ },
+ ],
+ });
expect(model.defaultEffort).toBe('medium');
});
@@ -157,7 +251,13 @@ describe('mapCodexModelsToCatalog', () => {
const out = mapCodexModelsToCatalog(SAMPLE);
expect(out.every((m) => !m.name.includes('订阅'))).toBe(true);
// issue #352:max/ultra 是合法 Codex 档,不再被 CODEX_EFFORTS 白名单过滤掉。
- expect(out.find((m) => m.id === 'gpt-5.6')?.efforts).toEqual(['low', 'high', 'xhigh', 'max', 'ultra']);
+ expect(out.find((m) => m.id === 'gpt-5.6')?.efforts).toEqual([
+ 'low',
+ 'high',
+ 'xhigh',
+ 'max',
+ 'ultra',
+ ]);
expect(out.find((m) => m.id === 'gpt-5.6')?.sortOrder).toBe(19);
expect(out.find((m) => m.id === 'gpt-5.5')?.sortOrder).toBe(20);
expect(out.find((m) => m.id === 'gpt-5.4')?.sortOrder).toBe(21);
@@ -188,7 +288,15 @@ describe('mapCodexModelsToCatalog', () => {
it('legacy 默认隐藏策略:gpt-5.4-mini defaultEnabled:false(旧目录可见性不因清单动态化漂移)', () => {
const out = mapCodexModelsToCatalog({
models: [
- { slug: 'gpt-5.4-mini', display_name: 'GPT-5.4-Mini', visibility: 'list', supported_in_api: true, context_window: 272000, priority: 23, supported_reasoning_levels: [{ effort: 'high' }] },
+ {
+ slug: 'gpt-5.4-mini',
+ display_name: 'GPT-5.4-Mini',
+ visibility: 'list',
+ supported_in_api: true,
+ context_window: 272000,
+ priority: 23,
+ supported_reasoning_levels: [{ effort: 'high' }],
+ },
],
});
expect(out[0].defaultEnabled).toBe(false);
@@ -198,7 +306,11 @@ describe('mapCodexModelsToCatalog', () => {
expect(mapCodexModelsToCatalog(null)).toEqual([]);
expect(mapCodexModelsToCatalog({})).toEqual([]);
expect(mapCodexModelsToCatalog({ models: 'nope' })).toEqual([]);
- expect(mapCodexModelsToCatalog({ models: [{ slug: 'x', visibility: 'list', supported_in_api: true }] })[0].efforts).toEqual([]);
+ expect(
+ mapCodexModelsToCatalog({
+ models: [{ slug: 'x', visibility: 'list', supported_in_api: true }],
+ })[0].efforts,
+ ).toEqual([]);
});
});
@@ -240,19 +352,40 @@ describe('mapCodexAppServerModelsToCatalog', () => {
isDefault: true,
},
{
- id: 'hidden', model: 'hidden', displayName: 'Hidden', description: '', hidden: true,
- supportedReasoningEfforts: [], defaultReasoningEffort: 'medium', additionalSpeedTiers: [],
- serviceTiers: [], isDefault: false,
+ id: 'hidden',
+ model: 'hidden',
+ displayName: 'Hidden',
+ description: '',
+ hidden: true,
+ supportedReasoningEfforts: [],
+ defaultReasoningEffort: 'medium',
+ additionalSpeedTiers: [],
+ serviceTiers: [],
+ isDefault: false,
},
{
- id: 'duplicate', model: 'gpt-5.6', displayName: 'Duplicate', description: '', hidden: false,
- supportedReasoningEfforts: [], defaultReasoningEffort: 'medium', additionalSpeedTiers: [],
- serviceTiers: [], isDefault: false,
+ id: 'duplicate',
+ model: 'gpt-5.6',
+ displayName: 'Duplicate',
+ description: '',
+ hidden: false,
+ supportedReasoningEfforts: [],
+ defaultReasoningEffort: 'medium',
+ additionalSpeedTiers: [],
+ serviceTiers: [],
+ isDefault: false,
},
{
- id: 'gpt-5.4-mini', model: 'gpt-5.4-mini', displayName: 'GPT-5.4 Mini', description: '', hidden: false,
+ id: 'gpt-5.4-mini',
+ model: 'gpt-5.4-mini',
+ displayName: 'GPT-5.4 Mini',
+ description: '',
+ hidden: false,
supportedReasoningEfforts: [{ reasoningEffort: 'high', description: '' }],
- defaultReasoningEffort: 'high', additionalSpeedTiers: [], serviceTiers: [], isDefault: false,
+ defaultReasoningEffort: 'high',
+ additionalSpeedTiers: [],
+ serviceTiers: [],
+ isDefault: false,
},
] as CodexModelListItem[]);
@@ -319,12 +452,18 @@ describe('readCodexDiscoveredModelsForAuthRefresh', () => {
});
});
-
it('does not put an unknown working default above an explicit smaller maximum', () => {
- const [model] = mapCodexModelsToCatalog({ models: [{
- slug: 'small-test', display_name: 'Small', visibility: 'list', supported_in_api: true,
- max_context_window: 64_000,
- }] });
+ const [model] = mapCodexModelsToCatalog({
+ models: [
+ {
+ slug: 'small-test',
+ display_name: 'Small',
+ visibility: 'list',
+ supported_in_api: true,
+ max_context_window: 64_000,
+ },
+ ],
+ });
expect(model).toMatchObject({ contextWindow: 64_000, contextWindowMax: 64_000 });
expect(model.contextWindowVerified).not.toBe(true);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
index 8f95bc1c69..c2c0402941 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
@@ -37,7 +37,10 @@ const valid: CustomProviderConfig = {
id: 'openrouter',
name: 'OpenRouter',
runtimes: {
- codex: { baseUrl: 'https://openrouter.ai/api/v1', models: [{ id: 'meta/llama-4', name: 'Llama 4' }] },
+ codex: {
+ baseUrl: 'https://openrouter.ai/api/v1',
+ models: [{ id: 'meta/llama-4', name: 'Llama 4' }],
+ },
},
};
@@ -72,18 +75,64 @@ afterEach(() => {
});
describe('validateCustomProviderConfig (per-runtime)', () => {
+ it.each(['codex', 'claude-code', 'pi'] as const)(
+ 'round-trips opaque preset references for %s',
+ async (agent) => {
+ mountDb();
+ for (const catalogPresetId of ['My_Preset', 'vendor/preset:v2', '预设', 'x'.repeat(300)]) {
+ const config: CustomProviderConfig = {
+ id: 'preset-reference',
+ name: 'Reference',
+ runtimes: {
+ [agent]: {
+ baseUrl: 'https://example.test/v1',
+ catalogPresetId,
+ wireProtocol: agent === 'claude-code' ? 'anthropic-messages' : 'openai-chat',
+ models: [{ id: 'model', name: 'Model' }],
+ },
+ },
+ };
+ expect(validateCustomProviderConfig(config).ok).toBe(true);
+ await createCustomProvider(config);
+ expect((await getCustomProvider(config.id))?.runtimes[agent]?.catalogPresetId).toBe(
+ catalogPresetId,
+ );
+ expect((await listCustomProviders())[0]?.runtimes[agent]?.catalogPresetId).toBe(
+ catalogPresetId,
+ );
+ await deleteCustomProvider(config.id);
+ }
+ for (const catalogPresetId of ['', 42, null]) {
+ expect(
+ validateCustomProviderConfig({
+ ...valid,
+ runtimes: {
+ [agent]: {
+ baseUrl: 'https://example.test/v1',
+ wireProtocol: agent === 'claude-code' ? 'anthropic-messages' : 'openai-chat',
+ catalogPresetId,
+ models: [],
+ },
+ },
+ }).ok,
+ ).toBe(false);
+ }
+ },
+ );
it.each(['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'])(
'rejects credentials in modelsUrl without exposing them: %s',
(userinfo) => {
- expect(validateCustomProviderConfig({
- ...valid,
- runtimes: {
- codex: {
- ...valid.runtimes.codex!,
- modelsUrl: `https://${userinfo}openrouter.ai/api/v1/models`,
+ expect(
+ validateCustomProviderConfig({
+ ...valid,
+ runtimes: {
+ codex: {
+ ...valid.runtimes.codex!,
+ modelsUrl: `https://${userinfo}openrouter.ai/api/v1/models`,
+ },
},
- },
- })).toEqual({
+ }),
+ ).toEqual({
ok: false,
code: 'INVALID_PARAMS',
message: "runtime 'codex' modelsUrl must not contain embedded credentials",
@@ -128,7 +177,10 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
it('rejects runtime with bad baseUrl / missing model fields', () => {
expect(
- validateCustomProviderConfig({ ...valid, runtimes: { codex: { baseUrl: 'ftp://x', models: [] } } }).ok,
+ validateCustomProviderConfig({
+ ...valid,
+ runtimes: { codex: { baseUrl: 'ftp://x', models: [] } },
+ }).ok,
).toBe(false);
expect(
validateCustomProviderConfig({
@@ -194,7 +246,11 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
name: 'Local pi',
auth: { method: 'none' },
runtimes: {
- pi: { baseUrl: 'http://127.0.0.1:11434/v1', wireProtocol: wp, models: [{ id: 'm', name: 'M' }] },
+ pi: {
+ baseUrl: 'http://127.0.0.1:11434/v1',
+ wireProtocol: wp,
+ models: [{ id: 'm', name: 'M' }],
+ },
},
}).ok,
).toBe(true);
@@ -270,39 +326,45 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
'openai-completions',
'google-generative-ai',
]) {
- expect(validateCustomProviderConfig({
- id: 'pi-api',
- name: 'Pi API',
+ expect(
+ validateCustomProviderConfig({
+ id: 'pi-api',
+ name: 'Pi API',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://example.com/v1',
+ wireProtocol: 'openai-chat',
+ models: [{ id: 'm', name: 'M', piApi }],
+ },
+ },
+ }).ok,
+ ).toBe(true);
+ }
+ expect(
+ validateCustomProviderConfig({
+ id: 'bad-pi-api',
+ name: 'Bad Pi API',
runtimes: {
pi: {
baseUrl: 'https://example.com/v1',
wireProtocol: 'openai-chat',
- models: [{ id: 'm', name: 'M', piApi }],
+ models: [{ id: 'm', name: 'M', piApi: 'claude-v1' }],
},
},
- }).ok).toBe(true);
- }
- expect(validateCustomProviderConfig({
- id: 'bad-pi-api',
- name: 'Bad Pi API',
- runtimes: {
- pi: {
- baseUrl: 'https://example.com/v1',
- wireProtocol: 'openai-chat',
- models: [{ id: 'm', name: 'M', piApi: 'claude-v1' }],
- },
- },
- }).ok).toBe(false);
- expect(validateCustomProviderConfig({
- id: 'wrong-runtime-pi-api',
- name: 'Wrong runtime Pi API',
- runtimes: {
- codex: {
- baseUrl: 'https://example.com/v1',
- models: [{ id: 'm', name: 'M', piApi: 'openai-responses' }],
+ }).ok,
+ ).toBe(false);
+ expect(
+ validateCustomProviderConfig({
+ id: 'wrong-runtime-pi-api',
+ name: 'Wrong runtime Pi API',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://example.com/v1',
+ models: [{ id: 'm', name: 'M', piApi: 'openai-responses' }],
+ },
},
- },
- }).ok).toBe(false);
+ }).ok,
+ ).toBe(false);
});
it('accepts only explicit, non-empty, valid Pi reasoning effort capabilities', () => {
@@ -345,11 +407,15 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
).ok,
).toBe(false);
expect(validateCustomProviderConfig(config({ reasoningEfforts: ['high'] })).ok).toBe(false);
- expect(validateCustomProviderConfig(config({
- reasoning: true,
- reasoningEfforts: ['low', 'high'],
- reasoningDefaultEffort: 'max',
- })).ok).toBe(false);
+ expect(
+ validateCustomProviderConfig(
+ config({
+ reasoning: true,
+ reasoningEfforts: ['low', 'high'],
+ reasoningDefaultEffort: 'max',
+ }),
+ ).ok,
+ ).toBe(false);
expect(
validateCustomProviderConfig(
config(
@@ -381,7 +447,11 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
name: 'Local pi',
auth: { method: 'none' },
runtimes: {
- pi: { baseUrl: 'http://127.0.0.1:11434/v1', wireProtocol: 'bogus-proto', models: [{ id: 'm', name: 'M' }] },
+ pi: {
+ baseUrl: 'http://127.0.0.1:11434/v1',
+ wireProtocol: 'bogus-proto',
+ models: [{ id: 'm', name: 'M' }],
+ },
},
}).ok,
).toBe(false);
@@ -475,7 +545,10 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
name: 'OR v2',
runtimes: {
...valid.runtimes,
- 'claude-code': { baseUrl: 'https://openrouter.ai/anthropic', models: [{ id: 'x/y', name: 'XY' }] },
+ 'claude-code': {
+ baseUrl: 'https://openrouter.ai/anthropic',
+ models: [{ id: 'x/y', name: 'XY' }],
+ },
},
});
expect(updated?.name).toBe('OR v2');
@@ -499,28 +572,34 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
...snapshot!.runtimes,
codex: {
...snapshot!.runtimes.codex!,
- models: [
- ...snapshot!.runtimes.codex!.models,
- { id: 'new-model', name: 'New model' },
- ],
+ models: [...snapshot!.runtimes.codex!.models, { id: 'new-model', name: 'New model' }],
},
},
};
- expect(
- await updateCustomProviderIfUnchanged('openrouter', snapshot!, discovered, 1_000),
- ).toBe(true);
+ expect(await updateCustomProviderIfUnchanged('openrouter', snapshot!, discovered, 1_000)).toBe(
+ true,
+ );
expect((await getCustomProvider('openrouter'))?.runtimes.codex?.models).toHaveLength(2);
- await updateCustomProvider('openrouter', {
- ...valid,
- name: 'Edited in another window',
- }, 1_000);
+ await updateCustomProvider(
+ 'openrouter',
+ {
+ ...valid,
+ name: 'Edited in another window',
+ },
+ 1_000,
+ );
expect(
- await updateCustomProviderIfUnchanged('openrouter', discovered, {
- ...discovered,
- name: 'Stale discovery write',
- }, 1_000),
+ await updateCustomProviderIfUnchanged(
+ 'openrouter',
+ discovered,
+ {
+ ...discovered,
+ name: 'Stale discovery write',
+ },
+ 1_000,
+ ),
).toBe(false);
expect((await getCustomProvider('openrouter'))?.name).toBe('Edited in another window');
});
@@ -565,7 +644,9 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
),
).toBe(true);
- const updated = raw!.prepare('SELECT id, updated_at FROM custom_providers ORDER BY id').all() as Array<{
+ const updated = raw!
+ .prepare('SELECT id, updated_at FROM custom_providers ORDER BY id')
+ .all() as Array<{
id: string;
updated_at: unknown;
}>;
@@ -601,7 +682,7 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect(got?.runtimes.codex?.headers).toBeUndefined();
});
- it('round-trips only an explicitly enabled Pi image-input capability', async () => {
+ it('round-trips explicit true and false Pi image-input capabilities', async () => {
mountDb();
await createCustomProvider({
id: 'visual-pi',
@@ -621,7 +702,7 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect((await getCustomProvider('visual-pi'))?.runtimes.pi?.models).toEqual([
{ id: 'vision', name: 'Vision', supportsImageInput: true },
{ id: 'legacy', name: 'Legacy' },
- { id: 'explicit-text', name: 'Explicit text' },
+ { id: 'explicit-text', name: 'Explicit text', supportsImageInput: false },
]);
});
@@ -635,13 +716,19 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
baseUrl: 'https://example.com/v1',
wireProtocol: 'openai-responses',
supportsImageGeneration: true,
- models: [{ id: 'enabled', name: 'Enabled' }, { id: 'legacy', name: 'Legacy' }],
+ models: [
+ { id: 'enabled', name: 'Enabled' },
+ { id: 'legacy', name: 'Legacy' },
+ ],
},
},
});
expect((await getCustomProvider('imagegen-provider'))?.runtimes.codex).toMatchObject({
supportsImageGeneration: true,
- models: [{ id: 'enabled', name: 'Enabled' }, { id: 'legacy', name: 'Legacy' }],
+ models: [
+ { id: 'enabled', name: 'Enabled' },
+ { id: 'legacy', name: 'Legacy' },
+ ],
});
});
@@ -658,18 +745,22 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
},
},
});
- expect((await getCustomProvider('official-pi'))?.runtimes.pi?.piCatalogProviderId).toBe('deepseek');
- expect(validateCustomProviderConfig({
- id: 'bad-catalog-runtime',
- name: 'Bad',
- runtimes: {
- codex: {
- baseUrl: 'https://api.example/v1',
- piCatalogProviderId: 'deepseek',
- models: [{ id: 'm', name: 'M' }],
+ expect((await getCustomProvider('official-pi'))?.runtimes.pi?.piCatalogProviderId).toBe(
+ 'deepseek',
+ );
+ expect(
+ validateCustomProviderConfig({
+ id: 'bad-catalog-runtime',
+ name: 'Bad',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://api.example/v1',
+ piCatalogProviderId: 'deepseek',
+ models: [{ id: 'm', name: 'M' }],
+ },
},
- },
- }).ok).toBe(false);
+ }).ok,
+ ).toBe(false);
});
it('clears the Pi catalog marker when any write path changes saved model metadata', async () => {
@@ -682,14 +773,16 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
baseUrl: 'https://api.deepseek.com',
wireProtocol: 'openai-chat',
piCatalogProviderId: 'deepseek',
- models: [{
- id: 'deepseek-v4-pro',
- name: 'DeepSeek V4 Pro',
- contextWindow: 1_000_000,
- reasoning: true,
- reasoningEfforts: ['high', 'max'],
- reasoningDefaultEffort: 'high',
- }],
+ models: [
+ {
+ id: 'deepseek-v4-pro',
+ name: 'DeepSeek V4 Pro',
+ contextWindow: 1_000_000,
+ reasoning: true,
+ reasoningEfforts: ['high', 'max'],
+ reasoningDefaultEffort: 'high',
+ },
+ ],
},
},
});
@@ -699,21 +792,27 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
...original.runtimes,
pi: {
...original.runtimes.pi!,
- models: [{
- ...original.runtimes.pi!.models[0]!,
- name: 'My DeepSeek',
- contextWindow: 64_000,
- supportsImageInput: true,
- reasoningEfforts: ['low'],
- reasoningDefaultEffort: 'low',
- }],
+ models: [
+ {
+ ...original.runtimes.pi!.models[0]!,
+ name: 'My DeepSeek',
+ contextWindow: 64_000,
+ supportsImageInput: true,
+ reasoningEfforts: ['low'],
+ reasoningDefaultEffort: 'low',
+ },
+ ],
},
},
};
- expect((await updateCustomProvider('official-pi-edited', {
- ...original,
- name: 'Renamed provider only',
- }))?.runtimes.pi?.piCatalogProviderId).toBe('deepseek');
+ expect(
+ (
+ await updateCustomProvider('official-pi-edited', {
+ ...original,
+ name: 'Renamed provider only',
+ })
+ )?.runtimes.pi?.piCatalogProviderId,
+ ).toBe('deepseek');
const defaultProtocolRoundTrip: CustomProviderConfig = {
...original,
runtimes: {
@@ -721,32 +820,36 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
pi: { ...original.runtimes.pi!, wireProtocol: undefined },
},
};
- expect((await updateCustomProvider('official-pi-edited', defaultProtocolRoundTrip))
- ?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (await updateCustomProvider('official-pi-edited', defaultProtocolRoundTrip))?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
await updateCustomProvider('official-pi-edited', original);
- expect((await updateCustomProvider('official-pi-edited', {
- ...original,
- runtimes: {
- ...original.runtimes,
- pi: {
- ...original.runtimes.pi!,
- wireProtocol: 'anthropic-messages',
- },
- },
- }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (
+ await updateCustomProvider('official-pi-edited', {
+ ...original,
+ runtimes: {
+ ...original.runtimes,
+ pi: {
+ ...original.runtimes.pi!,
+ wireProtocol: 'anthropic-messages',
+ },
+ },
+ })
+ )?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
await updateCustomProvider('official-pi-edited', original);
- expect((await updateCustomProvider('official-pi-edited', edited))?.runtimes.pi)
- .not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (await updateCustomProvider('official-pi-edited', edited))?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
const second = await createCustomProvider({
...original,
id: 'official-pi-discovered',
});
- expect(await updateCustomProviderIfUnchanged(
- second.id,
- second,
- {
+ expect(
+ await updateCustomProviderIfUnchanged(second.id, second, {
...second,
runtimes: {
...second.runtimes,
@@ -758,88 +861,107 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
],
},
},
- },
- )).toBe(true);
- expect((await getCustomProvider(second.id))?.runtimes.pi?.piCatalogProviderId)
- .toBe('deepseek');
+ }),
+ ).toBe(true);
+ expect((await getCustomProvider(second.id))?.runtimes.pi?.piCatalogProviderId).toBe('deepseek');
const replaced = await createCustomProvider({
...original,
id: 'official-pi-replaced',
});
- expect((await updateCustomProvider(replaced.id, {
- ...replaced,
- runtimes: {
- ...replaced.runtimes,
- pi: {
- ...replaced.runtimes.pi!,
- models: [{
- id: 'deepseek-v4-flash',
- name: 'My Flash Model',
- contextWindow: 64_000,
- supportsImageInput: true,
- reasoning: true,
- reasoningEfforts: ['low'],
- reasoningDefaultEffort: 'low',
- }],
- },
- },
- }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (
+ await updateCustomProvider(replaced.id, {
+ ...replaced,
+ runtimes: {
+ ...replaced.runtimes,
+ pi: {
+ ...replaced.runtimes.pi!,
+ models: [
+ {
+ id: 'deepseek-v4-flash',
+ name: 'My Flash Model',
+ contextWindow: 64_000,
+ supportsImageInput: true,
+ reasoning: true,
+ reasoningEfforts: ['low'],
+ reasoningDefaultEffort: 'low',
+ },
+ ],
+ },
+ },
+ })
+ )?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
expect((await getCustomProvider(replaced.id))?.runtimes.pi).toMatchObject({
- models: [{
- id: 'deepseek-v4-flash',
- name: 'My Flash Model',
- contextWindow: 64_000,
- supportsImageInput: true,
- reasoning: true,
- reasoningEfforts: ['low'],
- reasoningDefaultEffort: 'low',
- }],
+ models: [
+ {
+ id: 'deepseek-v4-flash',
+ name: 'My Flash Model',
+ contextWindow: 64_000,
+ supportsImageInput: true,
+ reasoning: true,
+ reasoningEfforts: ['low'],
+ reasoningDefaultEffort: 'low',
+ },
+ ],
});
const deleted = await createCustomProvider({
...original,
id: 'official-pi-deleted',
});
- expect((await updateCustomProvider(deleted.id, {
- ...deleted,
- runtimes: {
- ...deleted.runtimes,
- pi: { ...deleted.runtimes.pi!, models: [] },
- },
- }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (
+ await updateCustomProvider(deleted.id, {
+ ...deleted,
+ runtimes: {
+ ...deleted.runtimes,
+ pi: { ...deleted.runtimes.pi!, models: [] },
+ },
+ })
+ )?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
const deletedSnapshot = await getCustomProvider(deleted.id);
- expect((await updateCustomProvider(deleted.id, {
- ...deletedSnapshot!,
- runtimes: {
- ...deletedSnapshot!.runtimes,
- pi: {
- ...deletedSnapshot!.runtimes.pi!,
- models: deleted.runtimes.pi!.models,
- },
- },
- }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (
+ await updateCustomProvider(deleted.id, {
+ ...deletedSnapshot!,
+ runtimes: {
+ ...deletedSnapshot!.runtimes,
+ pi: {
+ ...deletedSnapshot!.runtimes.pi!,
+ models: deleted.runtimes.pi!.models,
+ },
+ },
+ })
+ )?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
const duplicate = await createCustomProvider({
...original,
id: 'official-pi-duplicate',
});
- expect((await updateCustomProvider(duplicate.id, {
- ...duplicate,
- runtimes: {
- ...duplicate.runtimes,
- pi: {
- ...duplicate.runtimes.pi!,
- models: [
- { ...duplicate.runtimes.pi!.models[0]!, name: 'Edited first duplicate' },
- duplicate.runtimes.pi!.models[0]!,
- ],
- },
- },
- }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');
+ expect(
+ (
+ await updateCustomProvider(duplicate.id, {
+ ...duplicate,
+ runtimes: {
+ ...duplicate.runtimes,
+ pi: {
+ ...duplicate.runtimes.pi!,
+ models: [
+ { ...duplicate.runtimes.pi!.models[0]!, name: 'Edited first duplicate' },
+ duplicate.runtimes.pi!.models[0]!,
+ ],
+ },
+ },
+ })
+ )?.runtimes.pi,
+ ).not.toHaveProperty('piCatalogProviderId');
});
- it('round-trips only an explicitly enabled Pi reasoning capability', async () => {
+ it('round-trips explicit Pi reasoning choices separately from inheritance', async () => {
mountDb();
await createCustomProvider({
id: 'reasoning-pi',
@@ -871,10 +993,49 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
reasoningDefaultEffort: 'xhigh',
},
{ id: 'legacy', name: 'Legacy' },
- { id: 'explicit-off', name: 'Explicit off' },
+ { id: 'explicit-off', name: 'Explicit off', reasoning: false },
]);
});
+ it.each(['codex', 'claude-code', 'pi'] as const)(
+ 'preserves reasoning off across %s updates and restores inheritance on deletion',
+ async (agent) => {
+ mountDb();
+ const provider = await createCustomProvider({
+ id: 'reasoning-choice',
+ name: 'Choice',
+ auth: { method: 'none' },
+ runtimes: {
+ [agent]: {
+ baseUrl: 'https://example.test/v1',
+ models: [
+ {
+ id: 'model',
+ name: 'Model',
+ reasoning: true,
+ reasoningEfforts: ['low', 'high'],
+ reasoningDefaultEffort: 'high',
+ },
+ ],
+ },
+ },
+ });
+ provider.runtimes[agent]!.models = [{ id: 'model', name: 'Model', reasoning: false }];
+ await updateCustomProvider(provider.id, provider);
+ expect((await getCustomProvider(provider.id))?.runtimes[agent]?.models[0]).toEqual({
+ id: 'model',
+ name: 'Model',
+ reasoning: false,
+ });
+ expect((await listCustomProviders())[0]?.runtimes[agent]?.models[0]?.reasoning).toBe(false);
+ provider.runtimes[agent]!.models = [{ id: 'model', name: 'Model' }];
+ await updateCustomProvider(provider.id, provider);
+ expect((await getCustomProvider(provider.id))?.runtimes[agent]?.models[0]).not.toHaveProperty(
+ 'reasoning',
+ );
+ },
+ );
+
it('round-trips Claude Code thinking toggle and reasoning efforts', async () => {
mountDb();
await createCustomProvider({
@@ -920,20 +1081,24 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
pi: {
baseUrl: 'https://api.deepseek.com',
wireProtocol: 'openai-responses',
- models: [{
- id: 'deepseek-v4-pro',
- name: 'DeepSeek V4 Pro',
- piApi: 'openai-responses',
- }],
+ models: [
+ {
+ id: 'deepseek-v4-pro',
+ name: 'DeepSeek V4 Pro',
+ piApi: 'openai-responses',
+ },
+ ],
},
},
});
- expect((await getCustomProvider('deepseek-pi'))?.runtimes.pi?.models).toEqual([{
- id: 'deepseek-v4-pro',
- name: 'DeepSeek V4 Pro',
- piApi: 'openai-responses',
- }]);
+ expect((await getCustomProvider('deepseek-pi'))?.runtimes.pi?.models).toEqual([
+ {
+ id: 'deepseek-v4-pro',
+ name: 'DeepSeek V4 Pro',
+ piApi: 'openai-responses',
+ },
+ ]);
});
it('round-trips an explicit Chat Completions protocol', async () => {
@@ -947,7 +1112,9 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
},
},
});
- expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe('openai-chat');
+ expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe(
+ 'openai-chat',
+ );
});
it('round-trips an explicit Anthropic Messages protocol for Codex', async () => {
@@ -962,52 +1129,59 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
},
},
});
- expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe('anthropic-messages');
+ expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe(
+ 'anthropic-messages',
+ );
});
it('preserves legacy remote auth:none records for repair without deleting them', async () => {
mountDb();
- raw!.prepare(
- `INSERT INTO custom_providers
+ raw!
+ .prepare(
+ `INSERT INTO custom_providers
(id, name, runtimes, auth, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, 0, 1, 1)`,
- ).run(
- 'legacy-no-auth',
- 'Legacy no auth',
- JSON.stringify({
- codex: {
- baseUrl: 'https://remote.example/v1',
- models: [{ id: 'm', name: 'M' }],
- },
- }),
- JSON.stringify({ method: 'none' }),
- );
+ )
+ .run(
+ 'legacy-no-auth',
+ 'Legacy no auth',
+ JSON.stringify({
+ codex: {
+ baseUrl: 'https://remote.example/v1',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ }),
+ JSON.stringify({ method: 'none' }),
+ );
const [loaded] = await listCustomProviders();
expect(loaded.id).toBe('legacy-no-auth');
expect(loaded.auth).toEqual({ method: 'none' });
expect(loaded.runtimes.codex?.baseUrl).toBe('https://remote.example/v1');
- expect(raw!.prepare('SELECT auth FROM custom_providers WHERE id = ?').get('legacy-no-auth'))
- .toEqual({ auth: JSON.stringify({ method: 'none' }) });
+ expect(
+ raw!.prepare('SELECT auth FROM custom_providers WHERE id = ?').get('legacy-no-auth'),
+ ).toEqual({ auth: JSON.stringify({ method: 'none' }) });
});
it('keeps legacy loopback auth:none records enabled when loading', async () => {
mountDb();
- raw!.prepare(
- `INSERT INTO custom_providers
+ raw!
+ .prepare(
+ `INSERT INTO custom_providers
(id, name, runtimes, auth, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, 0, 1, 1)`,
- ).run(
- 'legacy-loopback',
- 'Legacy loopback',
- JSON.stringify({
- codex: {
- baseUrl: 'http://127.0.0.1:4000/v1',
- models: [{ id: 'm', name: 'M' }],
- },
- }),
- JSON.stringify({ method: 'none' }),
- );
+ )
+ .run(
+ 'legacy-loopback',
+ 'Legacy loopback',
+ JSON.stringify({
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ }),
+ JSON.stringify({ method: 'none' }),
+ );
expect((await getCustomProvider('legacy-loopback'))?.auth).toEqual({ method: 'none' });
});
@@ -1023,11 +1197,13 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
],
},
});
- raw!.prepare(
- `INSERT INTO custom_providers
+ raw!
+ .prepare(
+ `INSERT INTO custom_providers
(id, name, runtimes, auth, sort_order, created_at, updated_at)
VALUES (?, ?, ?, NULL, 0, 1, 1)`,
- ).run('legacy-pi', 'Legacy Pi', storedRuntimes);
+ )
+ .run('legacy-pi', 'Legacy Pi', storedRuntimes);
const loaded = await getCustomProvider('legacy-pi');
expect(loaded?.runtimes.pi).toMatchObject({
@@ -1037,8 +1213,9 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
{ id: 'explicit', name: 'Explicit', piApi: 'openai-responses' },
],
});
- expect(raw!.prepare('SELECT runtimes FROM custom_providers WHERE id = ?').get('legacy-pi'))
- .toEqual({ runtimes: storedRuntimes });
+ expect(
+ raw!.prepare('SELECT runtimes FROM custom_providers WHERE id = ?').get('legacy-pi'),
+ ).toEqual({ runtimes: storedRuntimes });
});
it('round-trips a validated exact inference request path', async () => {
@@ -1052,8 +1229,9 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
},
},
});
- expect((await getCustomProvider('openrouter'))?.runtimes.codex?.requestPath)
- .toBe('/tenant/acme/v2/infer?stream=1');
+ expect((await getCustomProvider('openrouter'))?.runtimes.codex?.requestPath).toBe(
+ '/tenant/acme/v2/infer?stream=1',
+ );
});
it('round-trips a validated model-specific route', async () => {
@@ -1108,29 +1286,30 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
'/infer\u0000mode',
'/模型',
'responses',
- ])(
- 'rejects unsafe or non-path requestPath %s',
- (requestPath) => {
- expect(validateCustomProviderConfig({
+ ])('rejects unsafe or non-path requestPath %s', (requestPath) => {
+ expect(
+ validateCustomProviderConfig({
...valid,
runtimes: {
codex: { ...valid.runtimes.codex!, requestPath },
},
- }).ok).toBe(false);
- },
- );
+ }).ok,
+ ).toBe(false);
+ });
it('rejects unsupported protocol/runtime combinations', () => {
- expect(validateCustomProviderConfig({
- ...valid,
- runtimes: {
- 'claude-code': {
- baseUrl: 'https://v.ai/chat',
- wireProtocol: 'openai-chat',
- models: [{ id: 'm', name: 'M' }],
+ expect(
+ validateCustomProviderConfig({
+ ...valid,
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://v.ai/chat',
+ wireProtocol: 'openai-chat',
+ models: [{ id: 'm', name: 'M' }],
+ },
},
- },
- }).ok).toBe(false);
+ }).ok,
+ ).toBe(false);
});
it('update returns null when row absent', async () => {
@@ -1148,15 +1327,23 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
.prepare('UPDATE custom_providers SET updated_at = ? WHERE id = ?')
.run('2026-08-19T01:45:07.003Z', 'openrouter');
expect(
- raw!.prepare("SELECT typeof(updated_at) AS t FROM custom_providers WHERE id = 'openrouter'").get(),
+ raw!
+ .prepare("SELECT typeof(updated_at) AS t FROM custom_providers WHERE id = 'openrouter'")
+ .get(),
).toEqual({ t: 'text' });
- const updated = await updateCustomProvider('openrouter', { ...valid, name: 'Recovered' }, 5_000);
+ const updated = await updateCustomProvider(
+ 'openrouter',
+ { ...valid, name: 'Recovered' },
+ 5_000,
+ );
expect(updated?.name).toBe('Recovered');
expect((await getCustomProvider('openrouter'))?.name).toBe('Recovered');
const row = raw!
- .prepare("SELECT updated_at AS updatedAt, typeof(updated_at) AS t FROM custom_providers WHERE id = 'openrouter'")
+ .prepare(
+ "SELECT updated_at AS updatedAt, typeof(updated_at) AS t FROM custom_providers WHERE id = 'openrouter'",
+ )
.get() as { updatedAt: number; t: string };
expect(row.t).toBe('integer');
expect(row.updatedAt).toBe(5_000);
@@ -1191,7 +1378,9 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
),
).toBe(true);
const row = raw!
- .prepare("SELECT updated_at AS updatedAt, typeof(updated_at) AS t FROM custom_providers WHERE id = 'openrouter'")
+ .prepare(
+ "SELECT updated_at AS updatedAt, typeof(updated_at) AS t FROM custom_providers WHERE id = 'openrouter'",
+ )
.get() as { updatedAt: number; t: string };
expect(row.t).toBe('integer');
expect(row.updatedAt).toBe(7_000);
@@ -1211,15 +1400,27 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
mountDb();
// Seed a provider with updated_at = MAX_SAFE_INTEGER (corrupted/legacy data)
- raw!.prepare(
- `INSERT INTO custom_providers
+ raw!
+ .prepare(
+ `INSERT INTO custom_providers
(id, name, runtimes, auth, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
- ).run('max-cas', 'MaxCAS', JSON.stringify(valid.runtimes), null, 0, 1, Number.MAX_SAFE_INTEGER);
+ )
+ .run(
+ 'max-cas',
+ 'MaxCAS',
+ JSON.stringify(valid.runtimes),
+ null,
+ 0,
+ 1,
+ Number.MAX_SAFE_INTEGER,
+ );
// Read raw updated_at to snapshot version
const versionA = (
- raw!.prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?').get('max-cas') as { updatedAt: number }
+ raw!
+ .prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?')
+ .get('max-cas') as { updatedAt: number }
).updatedAt;
expect(versionA).toBe(Number.MAX_SAFE_INTEGER);
@@ -1228,15 +1429,21 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect(readerA).not.toBeNull();
// Writer B performs a normal edit
- await updateCustomProvider('max-cas', {
- ...valid,
- id: 'max-cas',
- name: 'MaxCAS Edited by B',
- }, 1_700_000_000_000);
+ await updateCustomProvider(
+ 'max-cas',
+ {
+ ...valid,
+ id: 'max-cas',
+ name: 'MaxCAS Edited by B',
+ },
+ 1_700_000_000_000,
+ );
// B's write must produce a different updated_at
const versionB = (
- raw!.prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?').get('max-cas') as { updatedAt: number }
+ raw!
+ .prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?')
+ .get('max-cas') as { updatedAt: number }
).updatedAt;
expect(versionB).not.toBe(Number.MAX_SAFE_INTEGER);
expect(versionB).not.toBe(versionA);
@@ -1270,15 +1477,19 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
mountDb();
// Seed with normal updated_at
- raw!.prepare(
- `INSERT INTO custom_providers
+ raw!
+ .prepare(
+ `INSERT INTO custom_providers
(id, name, runtimes, auth, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
- ).run('normal-cas', 'NormalCAS', JSON.stringify(valid.runtimes), null, 0, 1, 1000);
+ )
+ .run('normal-cas', 'NormalCAS', JSON.stringify(valid.runtimes), null, 0, 1, 1000);
// Reader A snapshots the version
const versionA = (
- raw!.prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?').get('normal-cas') as { updatedAt: number }
+ raw!
+ .prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?')
+ .get('normal-cas') as { updatedAt: number }
).updatedAt;
expect(versionA).toBe(1000);
@@ -1287,15 +1498,21 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect(readerA).not.toBeNull();
// Writer B edits
- await updateCustomProvider('normal-cas', {
- ...valid,
- id: 'normal-cas',
- name: 'NormalCAS Edited by B',
- }, 2000);
+ await updateCustomProvider(
+ 'normal-cas',
+ {
+ ...valid,
+ id: 'normal-cas',
+ name: 'NormalCAS Edited by B',
+ },
+ 2000,
+ );
// B's updated_at changed
const versionB = (
- raw!.prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?').get('normal-cas') as { updatedAt: number }
+ raw!
+ .prepare('SELECT updated_at AS updatedAt FROM custom_providers WHERE id = ?')
+ .get('normal-cas') as { updatedAt: number }
).updatedAt;
expect(versionB).not.toBe(versionA);
@@ -1314,5 +1531,57 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect(final_).not.toBeNull();
expect(final_!.name).toBe('NormalCAS Edited by B');
});
+});
+describe('supplier metadata persistence', () => {
+ it('refreshes supplier facts without converting them into explicit user preferences', async () => {
+ mountDb();
+ const metadata = { name: 'Supplier', contextWindow: 1000, supportsImageInput: true };
+ await createCustomProvider({
+ ...valid,
+ runtimes: {
+ codex: {
+ ...valid.runtimes.codex!,
+ models: [
+ {
+ id: 'model',
+ name: 'My label',
+ nameExplicit: true,
+ contextWindow: 2000,
+ supportsImageInput: false,
+ discoveredMetadata: metadata,
+ },
+ ],
+ },
+ },
+ });
+ const saved = await getCustomProvider(valid.id);
+ expect(saved?.runtimes.codex?.models[0]).toMatchObject({
+ nameExplicit: true,
+ contextWindow: 2000,
+ supportsImageInput: false,
+ discoveredMetadata: metadata,
+ });
+ const next = {
+ ...saved!,
+ runtimes: {
+ codex: {
+ ...saved!.runtimes.codex!,
+ models: [
+ {
+ ...saved!.runtimes.codex!.models[0],
+ discoveredMetadata: { ...metadata, contextWindow: 3000 },
+ },
+ ],
+ },
+ },
+ };
+ await updateCustomProvider(valid.id, next);
+ expect((await getCustomProvider(valid.id))?.runtimes.codex?.models[0]).toMatchObject({
+ name: 'My label',
+ contextWindow: 2000,
+ supportsImageInput: false,
+ discoveredMetadata: { contextWindow: 3000 },
+ });
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts
index 9d7f84e70d..9dab1f98b1 100644
--- a/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts
@@ -9,7 +9,10 @@ import { describe, it, expect } from 'vitest';
import { buildUserProvider, type CustomProviderConfig } from '@cindy/model-providers';
-import { mergeDiscoveredModelsIntoConfig, validateCustomProviderConfig } from '../custom-provider-store.js';
+import {
+ mergeDiscoveredModelsIntoConfig,
+ validateCustomProviderConfig,
+} from '../custom-provider-store.js';
import { parseModelsListResponse } from '../generic-oauth.js';
import { createProviderService } from '../provider-service.js';
@@ -32,7 +35,10 @@ const BASE: CustomProviderConfig = {
name: 'Acme Sub',
auth: { method: 'oauth', oauth: OAUTH },
runtimes: {
- 'claude-code': { baseUrl: 'https://api.acme.example/anthropic', models: [{ id: 'm1', name: 'M1' }] },
+ 'claude-code': {
+ baseUrl: 'https://api.acme.example/anthropic',
+ models: [{ id: 'm1', name: 'M1' }],
+ },
},
};
@@ -62,13 +68,16 @@ describe('validateCustomProviderConfig auth 段', () => {
auth: { method: 'oauth', oauth: DEVICE_OAUTH },
}).ok,
).toBe(true);
- expect(bad({ ...DEVICE_OAUTH, deviceAuthorizationUrl: 'http://auth.acme.example/device' }).ok)
- .toBe(false);
+ expect(
+ bad({ ...DEVICE_OAUTH, deviceAuthorizationUrl: 'http://auth.acme.example/device' }).ok,
+ ).toBe(false);
expect(bad({ ...DEVICE_OAUTH, redirectPort: 9123 }).ok).toBe(false);
});
it('apiKey method 不允许携带 oauth 描述符;非法 method 拒绝', () => {
- expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'apiKey', oauth: OAUTH } }).ok).toBe(false);
+ expect(
+ validateCustomProviderConfig({ ...BASE, auth: { method: 'apiKey', oauth: OAUTH } }).ok,
+ ).toBe(false);
expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'weird' } }).ok).toBe(false);
expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'apiKey' } }).ok).toBe(true);
});
@@ -133,8 +142,9 @@ describe('validateCustomProviderConfig auth 段', () => {
it('拒绝与 OAuth flow 不兼容的字段和带 userinfo 的上游地址', () => {
const bad = (oauth: object) =>
validateCustomProviderConfig({ ...BASE, auth: { method: 'oauth', oauth } });
- expect(bad({ ...OAUTH, deviceAuthorizationUrl: DEVICE_OAUTH.deviceAuthorizationUrl }).ok)
- .toBe(false);
+ expect(bad({ ...OAUTH, deviceAuthorizationUrl: DEVICE_OAUTH.deviceAuthorizationUrl }).ok).toBe(
+ false,
+ );
expect(bad({ ...DEVICE_OAUTH, authorizeUrl: OAUTH.authorizeUrl }).ok).toBe(false);
expect(
validateCustomProviderConfig({
@@ -158,21 +168,30 @@ describe('validateCustomProviderConfig auth 段', () => {
});
});
-describe('mergeDiscoveredModelsIntoConfig(发现结果持久化的 additions-only 合并)', () => {
- it('只追加新 id,已有条目 first-wins;无新增返回 null;runtime 未配置返回 null', () => {
+describe('mergeDiscoveredModelsIntoConfig(发现资料刷新并保留用户字段)', () => {
+ it('刷新发现资料并保留旧名称;无变化返回 null;runtime 未配置返回 null', () => {
const merged = mergeDiscoveredModelsIntoConfig(BASE, 'claude-code', [
{ id: 'm1', name: 'OVERRIDE-IGNORED' },
{ id: 'm2', name: 'M2' },
{ id: '', name: 'bad' },
]);
expect(merged?.runtimes['claude-code']?.models).toEqual([
- { id: 'm1', name: 'M1' },
- { id: 'm2', name: 'M2' },
+ {
+ id: 'm1',
+ name: 'M1',
+ nameExplicit: true,
+ discoveredMetadata: { name: 'OVERRIDE-IGNORED' },
+ },
+ { id: 'm2', name: 'M2', discoveredMetadata: { name: 'M2' } },
]);
// 原配置不被就地修改(纯函数)。
expect(BASE.runtimes['claude-code']?.models).toEqual([{ id: 'm1', name: 'M1' }]);
- expect(mergeDiscoveredModelsIntoConfig(BASE, 'claude-code', [{ id: 'm1', name: 'M1' }])).toBeNull();
+ expect(
+ mergeDiscoveredModelsIntoConfig(merged!, 'claude-code', [
+ { id: 'm1', name: 'OVERRIDE-IGNORED' },
+ ]),
+ ).toBeNull();
expect(mergeDiscoveredModelsIntoConfig(BASE, 'codex', [{ id: 'x', name: 'X' }])).toBeNull();
});
@@ -183,8 +202,8 @@ describe('mergeDiscoveredModelsIntoConfig(发现结果持久化的 additions-o
]);
expect(merged?.runtimes['claude-code']?.models).toEqual([
{ id: 'm1', name: 'M1' },
- { id: 'big', name: 'Big', contextWindow: 1_000_000 },
- { id: 'bogus', name: 'Bogus' },
+ { id: 'big', name: 'Big', discoveredMetadata: { name: 'Big', contextWindow: 1_000_000 } },
+ { id: 'bogus', name: 'Bogus', discoveredMetadata: { name: 'Bogus' } },
]);
});
});
@@ -211,19 +230,36 @@ describe('parseModelsListResponse contextWindow 提取(#386)', () => {
],
}),
).toEqual([
- { id: 'a', name: 'a', contextWindow: 1_048_576 },
- { id: 'b', name: 'B', contextWindow: 262144 },
- { id: 'c', name: 'c', contextWindow: 131072 },
- { id: 'f', name: 'f', contextWindow: 200_000 },
- { id: 'd', name: 'd' },
- { id: 'e', name: 'e' },
- { id: 'g', name: 'g' },
- { id: 'h', name: 'h' },
+ {
+ id: 'a',
+ name: 'a',
+ contextWindow: 1_048_576,
+ discoveredMetadata: { contextWindow: 1_048_576 },
+ },
+ {
+ id: 'b',
+ name: 'B',
+ contextWindow: 262144,
+ discoveredMetadata: { name: 'B', contextWindow: 262144 },
+ },
+ { id: 'c', name: 'c', contextWindow: 131072, discoveredMetadata: { contextWindow: 131072 } },
+ {
+ id: 'f',
+ name: 'f',
+ contextWindow: 200_000,
+ discoveredMetadata: { contextWindow: 200_000 },
+ },
+ { id: 'd', name: 'd', discoveredMetadata: {} },
+ { id: 'e', name: 'e', discoveredMetadata: {} },
+ { id: 'g', name: 'g', discoveredMetadata: {} },
+ { id: 'h', name: 'h', discoveredMetadata: {} },
]);
});
it('字符串数组形状不携带 contextWindow', () => {
- expect(parseModelsListResponse({ models: ['m1'] })).toEqual([{ id: 'm1', name: 'm1' }]);
+ expect(parseModelsListResponse({ models: ['m1'] })).toEqual([
+ { id: 'm1', name: 'm1', discoveredMetadata: {} },
+ ]);
});
});
@@ -238,7 +274,12 @@ describe('provider-service 连接态', () => {
};
const svc = createProviderService({
getCatalog: () => catalog,
- connection: { xd: () => false, anthropic: () => false, openai: () => false, xai: () => false },
+ connection: {
+ xd: () => false,
+ anthropic: () => false,
+ openai: () => false,
+ xai: () => false,
+ },
genericOAuthConnected: (id) => id === 'acme-sub',
customApiKeyConnected: (provider) => provider.id === 'plain',
});
@@ -248,7 +289,12 @@ describe('provider-service 连接态', () => {
const svcLoggedOut = createProviderService({
getCatalog: () => catalog,
- connection: { xd: () => false, anthropic: () => false, openai: () => false, xai: () => false },
+ connection: {
+ xd: () => false,
+ anthropic: () => false,
+ openai: () => false,
+ xai: () => false,
+ },
genericOAuthConnected: () => false,
});
const views2 = await svcLoggedOut.listProviders();
diff --git a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
index cd29d41855..d4485a6b16 100644
--- a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
@@ -190,7 +190,10 @@ describe('临期刷新(单飞)', () => {
it('临期 + refresh_token → 交换新 token 并落盘', async () => {
seedBlob('acme', { access_token: 'old', refresh_token: 'rt-1', expires_at: nowMs + 1_000 });
fetchResponder = () =>
- new Response(JSON.stringify({ access_token: 'new', refresh_token: 'rt-2', expires_in: 3600 }), { status: 200 });
+ new Response(
+ JSON.stringify({ access_token: 'new', refresh_token: 'rt-2', expires_in: 3600 }),
+ { status: 200 },
+ );
await refreshGenericOAuthIfNeeded('acme', OAUTH);
expect(readCachedGenericOAuthAccessToken('acme', OAUTH)).toBe('new');
expect(fetchCalls[0]?.url).toBe(OAUTH.tokenUrl);
@@ -209,7 +212,9 @@ describe('临期刷新(单飞)', () => {
fetchResponder = () => {
// 刷新响应到达前用户登出。
logoutGenericOAuth('acme');
- return new Response(JSON.stringify({ access_token: 'new', expires_in: 3600 }), { status: 200 });
+ return new Response(JSON.stringify({ access_token: 'new', expires_in: 3600 }), {
+ status: 200,
+ });
};
await refreshGenericOAuthIfNeeded('acme', OAUTH);
expect(hasGenericOAuthLogin('acme')).toBe(false);
@@ -242,7 +247,10 @@ describe('登录流与凭证落盘失败', () => {
it('成功路径:token 交换后凭证落盘 + 内存可读', async () => {
autoAuthorize();
fetchResponder = () =>
- new Response(JSON.stringify({ access_token: 'at-new', refresh_token: 'rt', expires_in: 3600 }), { status: 200 });
+ new Response(
+ JSON.stringify({ access_token: 'at-new', refresh_token: 'rt', expires_in: 3600 }),
+ { status: 200 },
+ );
const res = await runGenericOAuthLogin({ id: 'acme', name: 'Acme' }, OAUTH);
expect(res.ok).toBe(true);
expect(hasGenericOAuthLogin('acme')).toBe(true);
@@ -255,11 +263,11 @@ describe('登录流与凭证落盘失败', () => {
new Response(JSON.stringify({ access_token: 'at-new', expires_in: 3600 }), { status: 200 });
let rollback: (() => boolean) | undefined;
- const res = await runGenericOAuthLogin(
- { id: 'acme', name: 'Acme' },
- OAUTH,
- { onCredentialPersisted: (fn) => { rollback = fn; } },
- );
+ const res = await runGenericOAuthLogin({ id: 'acme', name: 'Acme' }, OAUTH, {
+ onCredentialPersisted: (fn) => {
+ rollback = fn;
+ },
+ });
expect(res.ok).toBe(true);
expect(rollback).toBeTypeOf('function');
@@ -274,11 +282,11 @@ describe('登录流与凭证落盘失败', () => {
new Response(JSON.stringify({ access_token: 'at-new', expires_in: 3600 }), { status: 200 });
let rollback: (() => boolean) | undefined;
- await runGenericOAuthLogin(
- { id: 'acme', name: 'Acme' },
- OAUTH,
- { onCredentialPersisted: (fn) => { rollback = fn; } },
- );
+ await runGenericOAuthLogin({ id: 'acme', name: 'Acme' }, OAUTH, {
+ onCredentialPersisted: (fn) => {
+ rollback = fn;
+ },
+ });
storage.read = () => null;
expect(rollback?.()).toBe(true);
@@ -291,11 +299,11 @@ describe('登录流与凭证落盘失败', () => {
new Response(JSON.stringify({ access_token: 'at-new', expires_in: 3600 }), { status: 200 });
let rollback: (() => boolean) | undefined;
- await runGenericOAuthLogin(
- { id: 'acme', name: 'Acme' },
- OAUTH,
- { onCredentialPersisted: (fn) => { rollback = fn; } },
- );
+ await runGenericOAuthLogin({ id: 'acme', name: 'Acme' }, OAUTH, {
+ onCredentialPersisted: (fn) => {
+ rollback = fn;
+ },
+ });
storage.readStrict = () => {
throw new Error('safeStorage unavailable');
};
@@ -521,11 +529,13 @@ describe('discoverGenericOAuthModels', () => {
it('解析 {data:[{id}]} 形状并去重', async () => {
seedBlob('acme', { access_token: 'at' });
fetchResponder = () =>
- new Response(JSON.stringify({ data: [{ id: 'm-1' }, { id: 'm-2' }, { id: 'm-1' }] }), { status: 200 });
+ new Response(JSON.stringify({ data: [{ id: 'm-1' }, { id: 'm-2' }, { id: 'm-1' }] }), {
+ status: 200,
+ });
const models = await discoverGenericOAuthModels('acme', OAUTH);
expect(models).toEqual([
- { id: 'm-1', name: 'm-1' },
- { id: 'm-2', name: 'm-2' },
+ { id: 'm-1', name: 'm-1', discoveredMetadata: {} },
+ { id: 'm-2', name: 'm-2', discoveredMetadata: {} },
]);
});
@@ -565,11 +575,15 @@ describe('discoverGenericOAuthModels', () => {
describe('deriveModelsDiscoveryUrl', () => {
it('/vN 结尾只追加 /models,其余追加 /v1/models(尾斜杠归一)', () => {
- expect(deriveModelsDiscoveryUrl('https://openrouter.ai/api/v1')).toBe('https://openrouter.ai/api/v1/models');
+ expect(deriveModelsDiscoveryUrl('https://openrouter.ai/api/v1')).toBe(
+ 'https://openrouter.ai/api/v1/models',
+ );
expect(deriveModelsDiscoveryUrl('https://api.acme.example/anthropic')).toBe(
'https://api.acme.example/anthropic/v1/models',
);
- expect(deriveModelsDiscoveryUrl('https://api.acme.example/')).toBe('https://api.acme.example/v1/models');
+ expect(deriveModelsDiscoveryUrl('https://api.acme.example/')).toBe(
+ 'https://api.acme.example/v1/models',
+ );
});
it('基于 pathname 追加模型端点,保留 query 并丢弃 fragment', () => {
@@ -601,7 +615,13 @@ describe('oauth-token 路由分支', () => {
// (ChatGPT OAuth spawn 的子进程会带这些头,发往第三方上游前必须抹掉;
// 自定义供应商目录条目无法声明 headerDelete,只能靠 oauth-token 分支代码层兜底)。
expect(dc?.headerDelete).toEqual(
- expect.arrayContaining(['anthropic-beta', 'chatgpt-account-id', 'openai-beta', 'originator', 'session_id']),
+ expect.arrayContaining([
+ 'anthropic-beta',
+ 'chatgpt-account-id',
+ 'openai-beta',
+ 'originator',
+ 'session_id',
+ ]),
);
expect(dc?.headerDelete).toHaveLength(5);
});
@@ -645,7 +665,11 @@ describe('oauth-token 路由分支', () => {
agents: ['claude-code'],
auth: { method: 'oauth', oauth: OAUTH },
routing: { 'claude-code': routing },
- models: { 'claude-code': [{ id: 'acme-1', name: 'A1', contextWindow: 1000, efforts: [], defaultEffort: null }] },
+ models: {
+ 'claude-code': [
+ { id: 'acme-1', name: 'A1', contextWindow: 1000, efforts: [], defaultEffort: null },
+ ],
+ },
},
],
});
@@ -669,16 +693,38 @@ describe('setDiscoveredProviderModels additions-only merge', () => {
source: 'builtin',
agents: ['claude-code'],
auth: { method: 'oauth', oauth: OAUTH },
- routing: { 'claude-code': { upstream: 'https://api.acme.example', authStrategy: 'oauth-token' } },
+ routing: {
+ 'claude-code': { upstream: 'https://api.acme.example', authStrategy: 'oauth-token' },
+ },
models: {
- 'claude-code': [{ id: 'static-1', name: 'Static', contextWindow: 1000, efforts: [], defaultEffort: null }],
+ 'claude-code': [
+ {
+ id: 'static-1',
+ name: 'Static',
+ contextWindow: 1000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
},
],
});
setDiscoveredProviderModels('acme', 'claude-code', [
- { id: 'static-1', name: 'OVERRIDE-IGNORED', contextWindow: 1, efforts: [], defaultEffort: null },
- { id: 'disc-1', name: 'Discovered', contextWindow: 200_000, efforts: [], defaultEffort: null },
+ {
+ id: 'static-1',
+ name: 'OVERRIDE-IGNORED',
+ contextWindow: 1,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: 'disc-1',
+ name: 'Discovered',
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
]);
const p = getActiveCatalog().providers.find((x) => x.id === 'acme')!;
expect(p.models['claude-code']!.map((m) => m.name)).toEqual(['Static', 'Discovered']);
@@ -697,7 +743,9 @@ describe('setDiscoveredProviderModels additions-only merge', () => {
source: 'user',
agents: ['claude-code'],
auth: { method: 'oauth', oauth: OAUTH },
- routing: { 'claude-code': { upstream: 'https://api.my.example', authStrategy: 'oauth-token' } },
+ routing: {
+ 'claude-code': { upstream: 'https://api.my.example', authStrategy: 'oauth-token' },
+ },
models: { 'claude-code': [] },
},
]);
@@ -753,3 +801,38 @@ describe('close() 回执路径(裸 done 消除)', () => {
expect(body).toContain('Acme');
});
});
+
+describe('explicit provider metadata fields', () => {
+ it('preserves false, empty efforts and null defaults without inventing a supplied name', async () => {
+ const { parseModelsListResponse } = await import('../generic-oauth.js');
+ expect(
+ parseModelsListResponse({
+ data: [
+ {
+ id: 'model',
+ name: '',
+ context_length: 64000,
+ max_output_tokens: 8000,
+ reasoning: { supportedEfforts: [], defaultEffort: null },
+ supports_fast_mode: false,
+ supports_image_input: false,
+ },
+ ],
+ }),
+ ).toEqual([
+ {
+ id: 'model',
+ name: 'model',
+ contextWindow: 64000,
+ discoveredMetadata: {
+ contextWindow: 64000,
+ maxOutputTokens: 8000,
+ efforts: [],
+ defaultEffort: null,
+ supportsFastMode: false,
+ supportsImageInput: false,
+ },
+ },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/model-catalog-override-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-catalog-override-store.test.ts
index 4beab5bb9e..e2cd120ef4 100644
--- a/apps/desktop/src/main/maker-host/__tests__/model-catalog-override-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/model-catalog-override-store.test.ts
@@ -71,7 +71,7 @@ describe('model-catalog-override-store', () => {
},
});
const read = readModelCatalogOverrides();
- expect(Object.keys(read.patches)).toEqual(['openai:gpt-6']);
+ expect(Object.keys(read.patches)).toEqual(['openai:gpt-6', 'xd:fake']);
expect(read.patches['openai:gpt-6']).toEqual({ base: { name: 'Hand Edited' } });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts
new file mode 100644
index 0000000000..9c0725ff22
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts
@@ -0,0 +1,522 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+it('isolates excess additions and duplicate tags without discarding valid local overrides', () => {
+ const model = (n: number) => ({
+ id: 'local-' + n,
+ name: 'Local ' + n,
+ aliases: [],
+ variants: [
+ { libraryName: 'local-' + n + ':latest', sizeBytes: 2 ** 30, minUnifiedMemoryGb: 4 },
+ ],
+ });
+ const base = { version: 1 as const, models: [model(0), model(1)], featuredIds: ['local-0'] };
+ const result = applyLocalModelCatalogOverrides(base, {
+ removedIds: ['local-1'],
+ patches: { 'local-0': { name: 'Kept patch' } },
+ additions: [
+ { ...model(99), variants: model(0).variants },
+ ...Array.from({ length: 33 }, (_, n) => model(n + 2)),
+ { ...model(2), name: 'Replacement at capacity' },
+ ],
+ featuredIds: [],
+ })!;
+ expect(result.models).toHaveLength(32);
+ expect(result.models.find((m) => m.id === 'local-0')?.name).toBe('Kept patch');
+ expect(result.models.find((m) => m.id === 'local-2')?.name).toBe('Replacement at capacity');
+ expect(result.models.some((m) => m.id === 'local-1' || m.id === 'local-99')).toBe(false);
+ expect(result.featuredIds).toEqual([]);
+ const invalidFeatured = applyLocalModelCatalogOverrides(result, {
+ patches: { 'local-0': { variants: model(2).variants }, 'local-3': { name: 'Still valid' } },
+ featuredIds: ['local-0', 'local-0'],
+ })!;
+ expect(invalidFeatured.models.find((m) => m.id === 'local-0')?.variants).toEqual(
+ model(0).variants,
+ );
+ expect(invalidFeatured.models.find((m) => m.id === 'local-3')?.name).toBe('Still valid');
+});
+
+import {
+ BUNDLED_CATALOG,
+ buildUserProvider,
+ type Catalog,
+ type ModelRegistry,
+} from '@cindy/model-providers';
+import {
+ getActiveCatalog,
+ getActiveLocalModelCatalog,
+ setActiveCatalog,
+ setCustomProviders,
+ setLocalCatalogOverrides,
+ setXdGatewayModels,
+} from '../active-catalog.js';
+import {
+ EMPTY_MODEL_CATALOG_OVERRIDES,
+ applyLocalModelCatalogOverrides,
+ applyExistingModelLocalPatch,
+ sanitizeModelCatalogOverrides,
+} from '../model-plane/localCatalogOverrides.js';
+
+function registry(): ModelRegistry {
+ return {
+ schemaVersion: 4,
+ updatedAt: '2026-09-08T07:00:00.000Z',
+ baseModels: [
+ {
+ id: 'maker/model',
+ aliases: ['model'],
+ defaults: {
+ name: 'Public',
+ contextWindow: 1000,
+ efforts: ['low', 'high'],
+ defaultEffort: 'low',
+ },
+ },
+ ],
+ models: [
+ {
+ id: 'saved',
+ name: 'Public',
+ modelRef: 'maker/model',
+ routes: [
+ {
+ providerId: 'xd',
+ modelId: 'model',
+ agents: ['claude-code', 'codex'],
+ defaults: { contextWindow: 2000 },
+ forceOverrides: { maxOutputTokens: 50 },
+ overrideReason: 'Verified output limit',
+ },
+ {
+ providerId: 'relay',
+ modelId: 'model',
+ agents: ['codex'],
+ forceOverrides: { contextWindow: 4000, supportsImageInput: true },
+ overrideReason: 'Verified supplier capability correction',
+ },
+ ],
+ },
+ ],
+ };
+}
+function model(provider: string, agent: 'codex' | 'pi' = 'codex') {
+ return getActiveCatalog().providers.find((p) => p.id === provider)?.models[agent]?.[0];
+}
+afterEach(() => {
+ setCustomProviders([]);
+ setXdGatewayModels([]);
+ setLocalCatalogOverrides(EMPTY_MODEL_CATALOG_OVERRIDES);
+ setActiveCatalog(BUNDLED_CATALOG);
+});
+describe('metadata layers through the active catalog', () => {
+ it.each(['absent', 'legacy', 'empty'] as const)(
+ 'applies local overrides after %s registry fallback',
+ (kind) => {
+ const bundled = BUNDLED_CATALOG.modelRegistry!.localModels!;
+ const [first, second] = bundled.models;
+ const modelRegistry: ModelRegistry | undefined =
+ kind === 'absent'
+ ? undefined
+ : {
+ schemaVersion: 2,
+ updatedAt: '2026-09-08T13:00:00.000Z',
+ models: [],
+ ...(kind === 'empty'
+ ? { localModels: { version: 1 as const, models: [], featuredIds: [] } }
+ : {}),
+ };
+ setActiveCatalog({ ...BUNDLED_CATALOG, modelRegistry });
+ setLocalCatalogOverrides(
+ sanitizeModelCatalogOverrides({
+ version: 1,
+ localModels: {
+ removedIds: [second.id],
+ patches: { [first.id]: { name: 'My fallback model' } },
+ additions: [
+ {
+ id: 'user-local',
+ name: 'User local',
+ aliases: [],
+ variants: [
+ { libraryName: 'user-local:latest', sizeBytes: 2 ** 30, minUnifiedMemoryGb: 4 },
+ ],
+ },
+ ],
+ featuredIds: [],
+ },
+ }).overrides,
+ );
+ const result = { localModels: getActiveLocalModelCatalog() };
+ expect(result.localModels?.featuredIds).toEqual([]);
+ expect(result.localModels?.models.some((m) => m.id === second.id)).toBe(false);
+ expect(result.localModels?.models.find((m) => m.id === 'user-local')?.name).toBe(
+ 'User local',
+ );
+ expect(result.localModels?.models.find((m) => m.id === first.id)?.name).toBe(
+ kind === 'empty' ? undefined : 'My fallback model',
+ );
+ expect(getActiveCatalog().modelRegistry?.models).toEqual(kind === 'absent' ? undefined : []);
+ setLocalCatalogOverrides(EMPTY_MODEL_CATALOG_OVERRIDES);
+ },
+ );
+ it('separates escaped supplier IDs from colon-containing model IDs', () => {
+ const { overrides, invalid } = sanitizeModelCatalogOverrides({
+ version: 1,
+ patches: {
+ 'custom%3Axai:grok:model': { base: { name: 'Migrated', contextWindow: 8000 } },
+ 'xai:grok:model': { base: { name: 'Built in' } },
+ 'custom:xai:grok:model': { base: { name: 'Other supplier' } },
+ 'custom%ZZ:grok:model': { base: { name: 'Malformed' } },
+ },
+ });
+ expect(invalid).toEqual(['patches:custom%ZZ:grok:model']);
+ const base = buildUserProvider({
+ id: 'relay',
+ name: 'Relay',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://relay.example/v1',
+ models: [{ id: 'grok:model', name: 'Original' }],
+ },
+ },
+ }).models.pi![0];
+ for (const agent of ['pi', 'codex', 'claude-code'] as const) {
+ expect(applyExistingModelLocalPatch('custom:xai', agent, base, overrides).name).toBe(
+ 'Migrated',
+ );
+ expect(applyExistingModelLocalPatch('xai', agent, base, overrides).name).toBe('Built in');
+ expect(
+ applyExistingModelLocalPatch('custom', agent, { ...base, id: 'xai:grok:model' }, overrides)
+ .name,
+ ).toBe('Other supplier');
+ }
+ });
+
+ it('projects every public user field onto local variants and adapts the final default', () => {
+ const r = registry();
+ r.localModels = {
+ version: 1,
+ models: [
+ {
+ id: 'local',
+ modelRef: 'maker/model',
+ name: 'Local',
+ aliases: [],
+ variants: [{ libraryName: 'local:quant', sizeBytes: 2 ** 30, minUnifiedMemoryGb: 4 }],
+ },
+ ],
+ featuredIds: [],
+ };
+ setActiveCatalog({ ...BUNDLED_CATALOG, modelRegistry: r });
+ const runtime = {
+ baseUrl: 'http://127.0.0.1:11434/v1',
+ models: [
+ {
+ id: 'local:quant',
+ name: 'Imported',
+ contextWindow: 2000,
+ reasoning: true,
+ reasoningEfforts: ['low', 'high'] as const,
+ reasoningDefaultEffort: 'high' as const,
+ },
+ ],
+ };
+ setCustomProviders(
+ ['cindy-local-ollama', 'relay'].map((id) =>
+ buildUserProvider(
+ {
+ id,
+ name: id,
+ runtimes: {
+ pi: {
+ ...runtime,
+ models: runtime.models.map((m) => ({
+ ...m,
+ reasoningEfforts: [...m.reasoningEfforts],
+ })),
+ },
+ codex: {
+ ...runtime,
+ models: runtime.models.map((m) => ({
+ ...m,
+ reasoningEfforts: [...m.reasoningEfforts],
+ })),
+ },
+ },
+ },
+ { modelRegistry: r },
+ ),
+ ),
+ );
+ const original = model('cindy-local-ollama', 'pi');
+ const apply = (specific = false, clear = false) =>
+ setLocalCatalogOverrides(
+ sanitizeModelCatalogOverrides({
+ version: 1,
+ baseModels: {
+ 'maker/model': {
+ name: 'User local',
+ description: 'User description',
+ group: 'User group',
+ contextWindow: 9000,
+ maxOutputTokens: 80,
+ supportsImageInput: true,
+ supportsFastMode: true,
+ efforts: ['low'],
+ ...(clear ? { defaultEffort: null } : {}),
+ },
+ },
+ ...(specific
+ ? {
+ patches: {
+ 'cindy-local-ollama:local:quant': {
+ base: { contextWindow: 12000, supportsImageInput: false },
+ },
+ },
+ }
+ : {}),
+ }).overrides,
+ );
+ apply();
+ for (const agent of ['pi', 'codex'] as const) {
+ expect(model('cindy-local-ollama', agent)).toMatchObject({
+ name: 'User local',
+ description: 'User description',
+ group: 'User group',
+ contextWindow: 9000,
+ maxOutput: 80,
+ supportsImageInput: true,
+ supportsFastMode: true,
+ efforts: ['low'],
+ defaultEffort: 'low',
+ });
+ expect(model('relay', agent)).toMatchObject({
+ name: 'Imported',
+ contextWindow: 2000,
+ defaultEffort: 'high',
+ });
+ }
+ apply(true, true);
+ expect(model('cindy-local-ollama', 'pi')).toMatchObject({
+ contextWindow: 12000,
+ supportsImageInput: false,
+ efforts: ['low'],
+ defaultEffort: null,
+ });
+ expect(getActiveCatalog().modelRegistry?.localModels?.featuredIds).toEqual([]);
+ expect(getActiveCatalog().modelRegistry?.localModels?.models).toHaveLength(1);
+ setLocalCatalogOverrides(EMPTY_MODEL_CATALOG_OVERRIDES);
+ expect(model('cindy-local-ollama', 'pi')).toEqual(original);
+ });
+ it.each([200, 201, 256, 257])(
+ 'aligns public override keys with the %i-character registry identity',
+ (length) => {
+ const r = registry();
+ const id = 'm'.repeat(length);
+ r.baseModels![0].id = id;
+ r.models[0].modelRef = id;
+ setActiveCatalog({ ...BUNDLED_CATALOG, modelRegistry: r });
+ setXdGatewayModels([
+ { id: 'model', name: 'Supplier', contextWindow: 3000, agents: ['codex'] },
+ ]);
+ const { overrides } = sanitizeModelCatalogOverrides({
+ version: 1,
+ baseModels: { [id]: { name: 'User name' } },
+ });
+ expect(overrides.baseModels?.[id]).toEqual(length <= 256 ? { name: 'User name' } : undefined);
+ if (length <= 256) {
+ setLocalCatalogOverrides(overrides);
+ expect(model('xd')?.name).toBe('User name');
+ }
+ },
+ );
+ it('merges sparse Gateway facts, server force and user patches without inventing membership', () => {
+ setActiveCatalog({ ...BUNDLED_CATALOG, modelRegistry: registry() });
+ setXdGatewayModels([
+ {
+ id: 'model',
+ name: 'Supplier',
+ contextWindow: 3000,
+ efforts: ['low', 'high'],
+ agents: ['codex'],
+ },
+ ]);
+ expect(model('xd')).toMatchObject({
+ name: 'Supplier',
+ contextWindow: 3000,
+ maxOutput: 50,
+ defaultEffort: 'low',
+ });
+ setLocalCatalogOverrides(
+ sanitizeModelCatalogOverrides({
+ version: 1,
+ baseModels: { 'maker/model': { name: 'My shared name', maxOutputTokens: 60 } },
+ patches: {
+ 'xd:model': {
+ base: {
+ contextWindow: 5000,
+ maxOutput: 70,
+ defaultEffort: null,
+ supportsImageInput: false,
+ },
+ },
+ 'xd:missing': { base: { name: 'Must stay absent' } },
+ },
+ }).overrides,
+ );
+ expect(model('xd')).toMatchObject({
+ name: 'My shared name',
+ contextWindow: 5000,
+ maxOutput: 70,
+ defaultEffort: null,
+ supportsImageInput: false,
+ });
+ setXdGatewayModels([
+ {
+ id: 'model',
+ name: 'New supplier name',
+ contextWindow: 3500,
+ efforts: ['low', 'high'],
+ defaultEffort: 'high',
+ agents: ['codex'],
+ },
+ ]);
+ expect(model('xd')).toMatchObject({
+ name: 'My shared name',
+ contextWindow: 5000,
+ defaultEffort: null,
+ });
+ expect(getActiveCatalog().providers.find((p) => p.id === 'xd')?.models.codex).toHaveLength(1);
+ });
+ it('keeps explicit custom Pi values above force and inherits public metadata for an unknown supplier', () => {
+ const r = registry();
+ setActiveCatalog({ ...BUNDLED_CATALOG, modelRegistry: r });
+ const config = {
+ id: 'relay',
+ name: 'Relay',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://relay.example/v1',
+ models: [
+ {
+ id: 'model',
+ name: 'My model',
+ nameExplicit: true,
+ contextWindow: 6000,
+ supportsImageInput: false,
+ reasoning: true,
+ reasoningEfforts: ['high' as const],
+ discoveredMetadata: { name: 'Supplier', contextWindow: 3000 },
+ },
+ ],
+ },
+ },
+ };
+ setCustomProviders([buildUserProvider(config, { modelRegistry: r })]);
+ expect(model('relay', 'pi')).toMatchObject({
+ name: 'My model',
+ contextWindow: 6000,
+ supportsImageInput: false,
+ });
+ setLocalCatalogOverrides(
+ sanitizeModelCatalogOverrides({
+ version: 1,
+ baseModels: {
+ 'maker/model': {
+ name: 'Shared rename',
+ contextWindow: 9000,
+ supportsImageInput: true,
+ maxOutputTokens: 80,
+ efforts: ['low'],
+ },
+ },
+ }).overrides,
+ );
+ expect(model('relay', 'pi')).toMatchObject({
+ name: 'My model',
+ contextWindow: 6000,
+ supportsImageInput: false,
+ maxOutput: 80,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ });
+ // Clearing specific user choices makes the shared patch visible again.
+ setCustomProviders([
+ buildUserProvider(
+ {
+ ...config,
+ runtimes: {
+ pi: {
+ ...config.runtimes.pi,
+ models: [
+ {
+ id: 'model',
+ name: 'Supplier',
+ discoveredMetadata: { name: 'Supplier' },
+ },
+ ],
+ },
+ },
+ },
+ { modelRegistry: r },
+ ),
+ ]);
+ expect(model('relay', 'pi')).toMatchObject({
+ name: 'Shared rename',
+ contextWindow: 9000,
+ supportsImageInput: true,
+ maxOutput: 80,
+ });
+ const unknown = buildUserProvider(
+ {
+ ...config,
+ id: 'new-supplier',
+ runtimes: {
+ pi: {
+ ...config.runtimes.pi,
+ models: [{ id: 'model', name: 'model', discoveredMetadata: {} }],
+ },
+ },
+ },
+ { modelRegistry: r },
+ );
+ expect(unknown.models.pi?.[0]).toMatchObject({
+ name: 'Public',
+ contextWindow: 1000,
+ defaultEffort: 'low',
+ });
+ expect(unknown.models.pi?.[0].supportsImageInput).toBeUndefined();
+ expect(unknown.routing.pi?.upstream).toBe('https://relay.example/v1');
+ });
+ it('overlays local recommendations after a remote refresh, supports empty recommendations and ignores malformed variants', () => {
+ const catalog = structuredClone(BUNDLED_CATALOG) as Catalog;
+ const id = catalog.modelRegistry!.localModels!.models[0].id;
+ setActiveCatalog(catalog);
+ setLocalCatalogOverrides(
+ sanitizeModelCatalogOverrides({
+ version: 1,
+ localModels: { featuredIds: [], patches: { [id]: { name: 'My local choice' } } },
+ }).overrides,
+ );
+ expect(getActiveCatalog().modelRegistry?.localModels).toMatchObject({
+ featuredIds: [],
+ models: [
+ expect.objectContaining({ id, name: 'My local choice' }),
+ ...catalog.modelRegistry!.localModels!.models.slice(1),
+ ],
+ });
+ catalog.modelRegistry!.localModels!.models[0].name = 'Remote rename';
+ setActiveCatalog(catalog);
+ expect(getActiveCatalog().modelRegistry?.localModels?.models[0].name).toBe('My local choice');
+ setLocalCatalogOverrides(
+ sanitizeModelCatalogOverrides({
+ localModels: {
+ additions: [null, 42, {}],
+ patches: { [id]: { variants: [{ libraryName: 'cloud:latest' }] } },
+ },
+ }).overrides,
+ );
+ expect(getActiveCatalog().modelRegistry?.localModels?.models[0].variants).toEqual(
+ catalog.modelRegistry!.localModels!.models[0].variants,
+ );
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
index b4364826b3..d24dd9c5c1 100644
--- a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
@@ -89,7 +89,12 @@ function withNativeMetadataAndDefaults(
const defaults: Record<string, readonly string[]> = {
xai: ['grok-4.6'],
anthropic: ['claude-fable-5-1', 'claude-opus-5', 'claude-sonnet-5', 'claude-haiku-4-5'],
- openai: ['chatgpt/gpt-6-astra', 'chatgpt/gpt-5.6-sol', 'chatgpt/gpt-5.6-terra', 'chatgpt/gpt-5.6-luna'],
+ openai: [
+ 'chatgpt/gpt-6-astra',
+ 'chatgpt/gpt-5.6-sol',
+ 'chatgpt/gpt-5.6-terra',
+ 'chatgpt/gpt-5.6-luna',
+ ],
};
return models.map((model) => {
const nativeApi = resolveModelNativeApi(BUNDLED_CATALOG.modelRegistry, providerId, model.id);
@@ -115,10 +120,12 @@ afterEach(() => {
});
describe('registry presence 实体化', () => {
- it('uses one model default across Codex, Claude and native Pi, including catalog refresh', () => {
+ it('inherits defaults per harness and refreshes public defaults for Pi', () => {
for (const effort of ['medium', 'high'] as const) {
const catalog = structuredClone(BUNDLED_CATALOG);
- const terra = catalog.modelRegistry!.models.find((entry) => entry.id === 'openai/gpt-5.6-terra')!;
+ const terra = catalog.modelRegistry!.models.find(
+ (entry) => entry.id === 'openai/gpt-5.6-terra',
+ )!;
terra.defaultEffort = effort;
terra.perAgent = {
...terra.perAgent,
@@ -128,7 +135,9 @@ describe('registry presence 实体化', () => {
setActiveCatalog(catalog);
for (const agent of ['codex', 'claude-code', 'pi'] as const) {
const id = agent === 'codex' ? 'gpt-5.6-terra' : 'chatgpt/gpt-5.6-terra';
- expect(models('openai', agent).find((m) => m.id === id)?.defaultEffort).toBe(effort);
+ expect(models('openai', agent).find((m) => m.id === id)?.defaultEffort).toBe(
+ agent === 'codex' ? 'xhigh' : agent === 'claude-code' ? 'low' : effort,
+ );
}
}
});
@@ -344,7 +353,9 @@ describe('registry presence 实体化', () => {
}),
);
expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-6[1m]')).toBeUndefined();
- expect(models('openai', 'claude-code').find(m => m.id === 'chatgpt/gpt-6[1m]')?.contextWindow).toBe(900_000);
+ expect(
+ models('openai', 'claude-code').find((m) => m.id === 'chatgpt/gpt-6[1m]')?.contextWindow,
+ ).toBe(900_000);
expect(getModelPlaneWarnings()).toEqual([]);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
index 9f67548239..04bcd23fbf 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
@@ -41,11 +41,7 @@ vi.mock('@cindy/model-providers', async (importOriginal) => {
return {
...actual,
loadCatalog: vi.fn(
- (
- source: Record<string, unknown>,
- _io: unknown,
- onResolved?: (result: unknown) => void,
- ) =>
+ (source: Record<string, unknown>, _io: unknown, onResolved?: (result: unknown) => void) =>
new Promise((resolve) => {
h.loads.push({
source,
@@ -267,9 +263,7 @@ describe('provider catalog realm reload', () => {
}),
).resolves.toBe('replacement-token');
- await expect(
- __testing.readXaiProviderOAuthToken({ forceRefresh: true }),
- ).resolves.toBeNull();
+ await expect(__testing.readXaiProviderOAuthToken({ forceRefresh: true })).resolves.toBeNull();
expect(h.recoverGrokAuthAfterRejection).toHaveBeenCalledTimes(3);
});
@@ -445,7 +439,9 @@ describe('provider catalog realm reload', () => {
);
if (!currentEntry) throw new Error('expected gpt-5.6-sol Registry entry');
current.modelRegistry!.models = [currentEntry];
- currentEntry.perAgent = { ...currentEntry.perAgent, codex: { efforts: ['high'] } };
+ current.modelRegistry!.baseModels!.find(
+ (model) => model.id === currentEntry.modelRef,
+ )!.defaults = { efforts: ['high'], defaultEffort: 'high' };
setActiveCatalog(current);
const config: CustomProviderConfig = {
@@ -461,14 +457,12 @@ describe('provider catalog realm reload', () => {
setCustomProviderConfigs([config]);
const next = structuredClone(catalogNamed('custom-after', '2026-08-12T11:00:00.000Z'));
- const nextEntry = next.modelRegistry?.models.find(
- (entry) => entry.id === 'openai/gpt-5.6-sol',
- );
+ const nextEntry = next.modelRegistry?.models.find((entry) => entry.id === 'openai/gpt-5.6-sol');
if (!nextEntry) throw new Error('expected gpt-5.6-sol Registry entry');
next.modelRegistry!.models = [nextEntry];
- nextEntry.perAgent = {
- ...nextEntry.perAgent,
- codex: { efforts: ['high', 'max', 'ultra'], defaultEffort: 'ultra' },
+ next.modelRegistry!.baseModels!.find((model) => model.id === nextEntry.modelRef)!.defaults = {
+ efforts: ['high', 'max', 'ultra'],
+ defaultEffort: 'high',
};
const events: number[] = [];
@@ -499,9 +493,9 @@ describe('provider catalog realm reload', () => {
);
if (!entry) throw new Error('expected gpt-5.6-sol Registry entry');
current.modelRegistry!.models = [entry];
- entry.perAgent = {
- ...entry.perAgent,
- codex: { efforts: ['minimal', 'max'], defaultEffort: 'max' },
+ current.modelRegistry!.baseModels!.find((model) => model.id === entry.modelRef)!.defaults = {
+ efforts: ['minimal', 'max'],
+ defaultEffort: 'minimal',
};
setActiveCatalog(current);
const config: CustomProviderConfig = {
@@ -738,9 +732,7 @@ describe('provider catalog realm reload', () => {
const catalogWithXaiMedia = structuredClone(catalogNamed('catalog-with-xai-media'));
const xai = catalogWithXaiMedia.providers.find((provider) => provider.id === 'xai');
if (!xai) throw new Error('expected xAI provider');
- xai.imageModels = [
- { id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' },
- ];
+ xai.imageModels = [{ id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' }];
xai.imageDefaults = { standard: 'xai/grok-imagine-image' };
xai.videoModels = [
{ id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
@@ -752,7 +744,9 @@ describe('provider catalog realm reload', () => {
const fallbackReload = reloadActiveCatalogForEndpointChange();
// The endpoint-switch window uses bundled data, but it cannot advertise Global XD media.
- const waitingXd = getDesktopSelectableCatalog().providers.find((provider) => provider.id === 'xd');
+ const waitingXd = getDesktopSelectableCatalog().providers.find(
+ (provider) => provider.id === 'xd',
+ );
expect(waitingXd?.imageModels).toEqual([]);
expect(waitingXd?.embeddingModels).toEqual([]);
expect(waitingXd?.videoModels?.map((model) => model.id)).not.toContain('happyhorse');
@@ -766,9 +760,9 @@ describe('provider catalog realm reload', () => {
expect(fallbackXd?.embeddingModels).toEqual([]);
expect(fallbackXd?.videoModels?.map((model) => model.id)).not.toContain('happyhorse');
expect(
- fallbackCatalog.providers.find((provider) => provider.id === 'xai')?.videoModels?.map(
- (model) => model.id,
- ),
+ fallbackCatalog.providers
+ .find((provider) => provider.id === 'xai')
+ ?.videoModels?.map((model) => model.id),
).toEqual(['xai/grok-imagine-video', 'xai/grok-imagine-video-1.5']);
expect(deriveCindyMediaConfig(fallbackCatalog.providers, 'embed')).toEqual({
models: [],
@@ -809,9 +803,9 @@ describe('provider catalog realm reload', () => {
defaults: null,
});
expect(
- currentCatalog.providers.find((provider) => provider.id === 'xai')?.videoModels?.map(
- (model) => model.id,
- ),
+ currentCatalog.providers
+ .find((provider) => provider.id === 'xai')
+ ?.videoModels?.map((model) => model.id),
).toEqual(['xai/grok-imagine-video', 'xai/grok-imagine-video-1.5']);
// Restore the baseline expected by the following realm-race tests.
@@ -825,20 +819,12 @@ describe('provider catalog realm reload', () => {
const inheritedAll = structuredClone(catalogNamed('current-with-bundled-xd'));
const inheritedXai = inheritedAll.providers.find((provider) => provider.id === 'xai');
if (!inheritedXai) throw new Error('expected xAI provider');
- inheritedXai.imageModels = [
- { id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' },
- ];
- inheritedXai.videoModels = [
- { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
- ];
+ inheritedXai.imageModels = [{ id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' }];
+ inheritedXai.videoModels = [{ id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' }];
h.endpoint = 'https://model.cn-primary-missing-xd.example';
const reload = reloadActiveCatalogForEndpointChange();
- h.loads.at(-1)!.resolve(
- inheritedAll,
- 'current',
- ['image', 'video', 'embedding'],
- );
+ h.loads.at(-1)!.resolve(inheritedAll, 'current', ['image', 'video', 'embedding']);
await reload;
const projectedAll = getDesktopSelectableCatalog();
@@ -890,8 +876,7 @@ describe('provider catalog realm reload', () => {
await evidenceUpgrade;
expect(
- getDesktopSelectableCatalog()
- .providers.find((provider) => provider.id === 'xd')
+ getDesktopSelectableCatalog().providers.find((provider) => provider.id === 'xd')
?.embeddingModels,
).toEqual(inheritedEmbeddingXd.embeddingModels);
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
index 5f742735d2..0533004ab0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
@@ -13,7 +13,12 @@ import {
} from '../provider-model-fetch.js';
function spec(over: Partial<ProviderModelsFetchSpec> = {}): ProviderModelsFetchSpec {
- return { agent: 'claude-code', baseUrl: 'https://api.acme.example/anthropic', apiKey: 'sk-test', ...over };
+ return {
+ agent: 'claude-code',
+ baseUrl: 'https://api.acme.example/anthropic',
+ apiKey: 'sk-test',
+ ...over,
+ };
}
function fakeResponse(status: number, body: string): Response {
@@ -23,18 +28,28 @@ function fakeResponse(status: number, body: string): Response {
describe('buildModelsFetchRequest', () => {
it.each(
(['baseUrl', 'modelsUrl'] as const).flatMap((field) =>
- ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({ field, userinfo })),
+ ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({
+ field,
+ userinfo,
+ })),
),
)('rejects credentials in $field before building a request: $userinfo', ({ field, userinfo }) => {
- expect(() => buildModelsFetchRequest(spec({
- [field]: `https://${userinfo}api.acme.example/anthropic/v1/models`,
- }))).toThrow('model discovery requires HTTP(S) URLs without embedded credentials');
+ expect(() =>
+ buildModelsFetchRequest(
+ spec({
+ [field]: `https://${userinfo}api.acme.example/anthropic/v1/models`,
+ }),
+ ),
+ ).toThrow('model discovery requires HTTP(S) URLs without embedded credentials');
});
it('derives {base}/v1/models for non-/vN baseUrl; appends /models when baseUrl ends with /vN', () => {
- expect(buildModelsFetchRequest(spec()).url).toBe('https://api.acme.example/anthropic/v1/models');
+ expect(buildModelsFetchRequest(spec()).url).toBe(
+ 'https://api.acme.example/anthropic/v1/models',
+ );
expect(
- buildModelsFetchRequest(spec({ agent: 'codex', baseUrl: 'https://openrouter.ai/api/v1' })).url,
+ buildModelsFetchRequest(spec({ agent: 'codex', baseUrl: 'https://openrouter.ai/api/v1' }))
+ .url,
).toBe('https://openrouter.ai/api/v1/models');
});
@@ -50,7 +65,10 @@ describe('buildModelsFetchRequest', () => {
// 同主机(Moonshot 形态:baseUrl …/anthropic,列模型在同 host 的 /v1/models)→ 采用。
expect(
buildModelsFetchRequest(
- spec({ baseUrl: 'https://api.moonshot.cn/anthropic', modelsUrl: 'https://api.moonshot.cn/v1/models' }),
+ spec({
+ baseUrl: 'https://api.moonshot.cn/anthropic',
+ modelsUrl: 'https://api.moonshot.cn/v1/models',
+ }),
).url,
).toBe('https://api.moonshot.cn/v1/models');
// 跨主机(用户改了 baseUrl、快照仍指旧主机)→ 忽略隐藏字段,回退 baseUrl 推导,防 key 误投。
@@ -60,13 +78,15 @@ describe('buildModelsFetchRequest', () => {
});
it('cc wire sends anthropic-version + x-api-key + Bearer; codex wire sends Bearer only', () => {
- const cc = buildModelsFetchRequest(spec({
- headers: {
- Authorization: 'Bearer stale',
- 'X-API-Key': 'stale',
- 'x-extra': '1',
- },
- })).init.headers as Record<string, string>;
+ const cc = buildModelsFetchRequest(
+ spec({
+ headers: {
+ Authorization: 'Bearer stale',
+ 'X-API-Key': 'stale',
+ 'x-extra': '1',
+ },
+ }),
+ ).init.headers as Record<string, string>;
expect(cc['anthropic-version']).toBe('2023-06-01');
expect(cc['x-api-key']).toBe('sk-test');
expect(cc['authorization']).toBe('Bearer sk-test');
@@ -74,7 +94,10 @@ describe('buildModelsFetchRequest', () => {
expect(cc['X-API-Key']).toBeUndefined();
expect(cc['x-extra']).toBe('1');
- const codex = buildModelsFetchRequest(spec({ agent: 'codex' })).init.headers as Record<string, string>;
+ const codex = buildModelsFetchRequest(spec({ agent: 'codex' })).init.headers as Record<
+ string,
+ string
+ >;
expect(codex['anthropic-version']).toBeUndefined();
expect(codex['x-api-key']).toBeUndefined();
expect(codex['authorization']).toBe('Bearer sk-test');
@@ -106,15 +129,17 @@ describe('buildModelsFetchRequest', () => {
it.each(['none', 'oauth'] as const)(
'strips legacy credential headers for %s auth even without an apiKey',
(authMethod) => {
- const h = buildModelsFetchRequest(spec({
- authMethod,
- apiKey: null,
- headers: {
- Authorization: 'Bearer legacy',
- 'X-API-Key': 'legacy',
- 'x-extra': '1',
- },
- })).init.headers as Record<string, string>;
+ const h = buildModelsFetchRequest(
+ spec({
+ authMethod,
+ apiKey: null,
+ headers: {
+ Authorization: 'Bearer legacy',
+ 'X-API-Key': 'legacy',
+ 'x-extra': '1',
+ },
+ }),
+ ).init.headers as Record<string, string>;
expect(h.Authorization).toBeUndefined();
expect(h['X-API-Key']).toBeUndefined();
@@ -128,21 +153,30 @@ describe('buildModelsFetchRequest', () => {
describe('fetchProviderModels', () => {
it.each(
(['baseUrl', 'modelsUrl'] as const).flatMap((field) =>
- ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({ field, userinfo })),
+ ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({
+ field,
+ userinfo,
+ })),
),
- )('does not dispatch a request with credentials in $field: $userinfo', async ({ field, userinfo }) => {
- const fetchImpl = vi.fn<typeof fetch>();
- const result = await fetchProviderModels(spec({
- [field]: `https://${userinfo}api.acme.example/anthropic/v1/models`,
- authMethod: 'apiKey',
- }), fetchImpl);
- expect(result).toEqual({
- ok: false,
- code: 'UNKNOWN',
- detail: 'model discovery requires HTTP(S) URLs without embedded credentials',
- });
- expect(fetchImpl).not.toHaveBeenCalled();
- });
+ )(
+ 'does not dispatch a request with credentials in $field: $userinfo',
+ async ({ field, userinfo }) => {
+ const fetchImpl = vi.fn<typeof fetch>();
+ const result = await fetchProviderModels(
+ spec({
+ [field]: `https://${userinfo}api.acme.example/anthropic/v1/models`,
+ authMethod: 'apiKey',
+ }),
+ fetchImpl,
+ );
+ expect(result).toEqual({
+ ok: false,
+ code: 'UNKNOWN',
+ detail: 'model discovery requires HTTP(S) URLs without embedded credentials',
+ });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ },
+ );
it.each([
{
@@ -188,9 +222,9 @@ describe('fetchProviderModels', () => {
);
expect(r.ok).toBe(true);
expect(r.models).toEqual([
- { id: 'kimi-k3', name: 'Kimi K3' },
- { id: 'kimi-k2.6', name: 'Kimi K2.6' },
- { id: 'bare-id', name: 'bare-id' },
+ { id: 'kimi-k3', name: 'Kimi K3', discoveredMetadata: { name: 'Kimi K3' } },
+ { id: 'kimi-k2.6', name: 'Kimi K2.6', discoveredMetadata: { name: 'Kimi K2.6' } },
+ { id: 'bare-id', name: 'bare-id', discoveredMetadata: {} },
]);
});
@@ -198,14 +232,14 @@ describe('fetchProviderModels', () => {
const a = await fetchProviderModels(spec(), async () =>
fakeResponse(200, JSON.stringify({ models: [{ id: 'm1' }] })),
);
- expect(a.models).toEqual([{ id: 'm1', name: 'm1' }]);
+ expect(a.models).toEqual([{ id: 'm1', name: 'm1', discoveredMetadata: {} }]);
const b = await fetchProviderModels(spec(), async () =>
fakeResponse(200, JSON.stringify({ data: ['m1', 'm2'] })),
);
expect(b.models).toEqual([
- { id: 'm1', name: 'm1' },
- { id: 'm2', name: 'm2' },
+ { id: 'm1', name: 'm1', discoveredMetadata: {} },
+ { id: 'm2', name: 'm2', discoveredMetadata: {} },
]);
});
@@ -214,15 +248,18 @@ describe('fetchProviderModels', () => {
fakeResponse(
200,
JSON.stringify({
- models: [
- { slug: 'glm-5.3', display_name: 'GLM-5.3', context_window: 202_752 },
- ],
+ models: [{ slug: 'glm-5.3', display_name: 'GLM-5.3', context_window: 202_752 }],
}),
),
);
expect(result.models).toEqual([
- { id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 202_752 },
+ {
+ id: 'glm-5.3',
+ name: 'GLM-5.3',
+ contextWindow: 202_752,
+ discoveredMetadata: { name: 'GLM-5.3', contextWindow: 202_752 },
+ },
]);
});
@@ -241,7 +278,9 @@ describe('fetchProviderModels', () => {
});
it('returns non-ok UNKNOWN for 200 with unrecognized / empty payload', async () => {
- const empty = await fetchProviderModels(spec(), async () => fakeResponse(200, JSON.stringify({ data: [] })));
+ const empty = await fetchProviderModels(spec(), async () =>
+ fakeResponse(200, JSON.stringify({ data: [] })),
+ );
expect(empty).toMatchObject({ ok: false, code: 'UNKNOWN' });
const weird = await fetchProviderModels(spec(), async () => fakeResponse(200, '"not-a-list"'));
expect(weird).toMatchObject({ ok: false, code: 'UNKNOWN' });
@@ -253,7 +292,10 @@ describe('fetchProviderModels', () => {
let seenUrl = '';
let seenHeaders: Record<string, string> = {};
await fetchProviderModels(
- spec({ baseUrl: 'https://api.moonshot.cn/anthropic', modelsUrl: 'https://api.moonshot.cn/v1/models' }),
+ spec({
+ baseUrl: 'https://api.moonshot.cn/anthropic',
+ modelsUrl: 'https://api.moonshot.cn/v1/models',
+ }),
async (url, init) => {
seenUrl = String(url);
seenHeaders = (init?.headers ?? {}) as Record<string, string>;
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 41cab2009a..b914d5954a 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -1,3 +1,14 @@
+import {
+ applyExistingModelLocalPatch,
+ applyLocalModelCatalogOverrides,
+} from './model-plane/localCatalogOverrides.js';
+import {
+ resolveModelMetadata,
+ catalogModelMetadata,
+ applyModelMetadata,
+ pickModelMetadata,
+ findBaseModel,
+} from '@cindy/model-providers';
/**
* active-catalog —— 进程级「当前生效目录」单例(纯状态 holder,零 Electron 依赖)。
*
@@ -29,6 +40,7 @@ import { isDeepStrictEqual } from 'node:util';
import {
BUNDLED_CATALOG,
buildUserProvider,
+ runtimeUserModelMetadata,
clampEffortToSupported,
modelDefaultEffort,
defaultEffortForCapabilities,
@@ -49,6 +61,10 @@ import {
import { selectDefaultModels } from './model-default-selection.js';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import {
+ MANAGED_OLLAMA_PROVIDER_ID,
+ ollamaModelRefsEqual,
+} from '../../shared/localModelRuntime.js';
import { CHATGPT_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
import { projectUnverifiedCatalogFallbackForBuildRegion } from './provider-access-policy.js';
import {
@@ -316,7 +332,8 @@ function resolveXaiAccountCapabilities(
: entry.efforts !== undefined
? canonicalEffortOrder(entry.efforts)
: canonicalEffortOrder(baselineEfforts);
- const adaptedRegistryDefault = clampEffortToSupported(registryDefault, efforts) as Effort | null | undefined;
+ const adaptedRegistryDefault = clampEffortToSupported(registryDefault, efforts) as
+ Effort | null | undefined;
const defaultEffort = isGrok46
? pickXaiDefaultEffort(
efforts,
@@ -336,6 +353,7 @@ function preserveNonGrok46DiscoveryEfforts(
models: readonly CatalogModel[],
discovered: readonly XaiDiscoveredModel[],
): CatalogModel[] {
+ if ((base ?? BUNDLED_CATALOG).modelRegistry?.schemaVersion === 4) return [...models];
const byId = new Map(discovered.map((entry) => [entry.id, entry]));
return models.map((model) => {
const entry = byId.get(model.id) ?? byId.get(`xai/${model.id}`);
@@ -664,9 +682,8 @@ function modelRegistryMetaFields(
const { entry } = matched;
const perAgent = registryAgent ? entry.perAgent?.[registryAgent] : undefined;
const efforts = perAgent?.efforts ?? entry.efforts;
- const defaultEffort = efforts?.length === 0
- ? null
- : clampEffortToSupported(modelDefaultEffort(entry), efforts);
+ const defaultEffort =
+ efforts?.length === 0 ? null : clampEffortToSupported(modelDefaultEffort(entry), efforts);
return {
name: entry.name,
...(entry.group !== undefined ? { group: entry.group } : {}),
@@ -783,12 +800,30 @@ function assembleRoot(
const native = nativeModels.get(model.id);
return {
...model,
- ...(native?.contextWindowMax !== undefined ? { contextWindowMax: native.contextWindowMax } : {}),
+ ...(native?.contextWindowMax !== undefined
+ ? { contextWindowMax: native.contextWindowMax }
+ : {}),
// A stale Registry cannot enable a speed tier absent from the account.
...(native?.supportsFastMode === false ? { supportsFastMode: false } : {}),
};
});
}
+ const registry = (base ?? BUNDLED_CATALOG).modelRegistry;
+ if (registry?.schemaVersion === 4) {
+ const live = new Map(models.map((model) => [model.id, model]));
+ out = out.map((model) => {
+ const upstream = live.get(model.id);
+ const metadata =
+ upstream?.discoveredMetadata ?? (upstream ? catalogModelMetadata(upstream) : undefined);
+ return {
+ ...applyModelMetadata(
+ model,
+ resolveModelMetadata(registry, providerId, model.id, metadata, undefined, agent),
+ ),
+ ...(metadata ? { discoveredMetadata: metadata } : {}),
+ };
+ });
+ }
out = applyLocalOverridesToRoot(providerId, agent, out, localOverrides, plan.warnings);
if (rootPlan && rootPlan.retired.size > 0) {
out = out.map((m) =>
@@ -803,6 +838,29 @@ function assembleRoot(
}
/** Registry / local override 只能补账号已返回的条目,不能重新实体化账号没有的成员。 */
+function applyLayeredConsumer(
+ model: CatalogModel,
+ providerId: string,
+ agent: RootAgentKind,
+ plan: ModelPlaneRegistryPlan,
+): CatalogModel {
+ const overlaid = applyRegistryConsumerOverlay(model, providerId, agent, model.id, plan);
+ const registry = (base ?? BUNDLED_CATALOG).modelRegistry;
+ return registry?.schemaVersion === 4
+ ? applyModelMetadata(
+ overlaid,
+ resolveModelMetadata(
+ registry,
+ providerId,
+ model.id,
+ model.discoveredMetadata,
+ undefined,
+ agent,
+ ),
+ )
+ : overlaid;
+}
+
function assembleAuthoritativeRoot(
providerId: string,
agent: RootAgentKind,
@@ -849,6 +907,10 @@ function materializeXaiAccountModels(
: registry?.contextWindow !== undefined || catalogModel?.contextWindowVerified === true;
return {
...catalogModel,
+ discoveredMetadata: {
+ ...catalogModelMetadata(entry),
+ ...(entry.efforts ? { efforts: canonicalEffortOrder(entry.efforts) } : {}),
+ },
id: entry.id,
name: entry.name ?? registry?.name ?? catalogModel?.name ?? entry.id.slice('xai/'.length),
...(entry.description !== undefined
@@ -1080,10 +1142,14 @@ function computeMerged(): Catalog {
'claude-code',
model.id,
{
- ...applyRegistryConsumerOverlay(model, 'openai', 'claude-code', model.id, plan),
- // This bridge calls the same subscription backend as the Codex root.
- ...(model.contextWindowMax !== undefined ? { contextWindowMax: model.contextWindowMax } : {}),
- ...(model.supportsFastMode === false ? { supportsFastMode: false } : {}),
+ ...applyLayeredConsumer(model, 'openai', 'claude-code', plan),
+ ...(model.contextWindowMax !== undefined
+ ? { contextWindowMax: model.contextWindowMax }
+ : {}),
+ ...((base ?? BUNDLED_CATALOG).modelRegistry?.schemaVersion !== 4 &&
+ model.supportsFastMode === false
+ ? { supportsFastMode: false }
+ : {}),
},
localOverrides,
plan.warnings,
@@ -1142,7 +1208,7 @@ function computeMerged(): Catalog {
'anthropic',
'codex',
model.id,
- applyRegistryConsumerOverlay(model, 'anthropic', 'codex', model.id, plan),
+ applyLayeredConsumer(model, 'anthropic', 'codex', plan),
localOverrides,
plan.warnings,
),
@@ -1252,17 +1318,28 @@ function computeMerged(): Catalog {
// Resolve their exact OpenAI model identity for display only. Do not inherit
// subscription perAgent tiers, route availability, prices or request IDs.
const standardId = /^(?:codex\/)?gpt-[^/]+$/.test(gm.id)
- ? `openai/${gm.id.replace(/^codex\//, '')}` : gm.id;
- const standardEntry = b.modelRegistry?.models.find((entry) => entry.id === standardId)
- ?? registryEntry;
+ ? `openai/${gm.id.replace(/^codex\//, '')}`
+ : gm.id;
+ const standardEntry =
+ b.modelRegistry?.models.find((entry) => entry.id === standardId) ?? registryEntry;
+ const standardEfforts =
+ standardEntry?.efforts ??
+ findBaseModel(b.modelRegistry, standardEntry?.modelRef ?? standardId)?.defaults.efforts;
const displayEfforts = canonicalEffortOrder([
- ...(standardEntry?.status === 'retired' ? [] : standardEntry?.efforts ?? []),
+ ...(standardEntry?.status === 'retired' ? [] : (standardEfforts ?? [])),
...efforts,
]);
const registryDefault = registryEntry ? modelDefaultEffort(registryEntry) : undefined;
- const intent = registryDefault !== undefined ? registryDefault : defaultEffortForCapabilities(efforts);
- const defaultEffort = efforts.length === 0 ? null
- : (clampEffortToSupported(intent, efforts) ?? null) as Effort | null;
+ const intent =
+ b.modelRegistry?.schemaVersion === 4
+ ? (ov.defaultEffort ?? gm.defaultEffort ?? defaultEffortForCapabilities(efforts))
+ : registryDefault !== undefined
+ ? registryDefault
+ : defaultEffortForCapabilities(efforts);
+ const defaultEffort =
+ efforts.length === 0
+ ? null
+ : ((clampEffortToSupported(intent, efforts) ?? null) as Effort | null);
// Canonical Registry API determines native versus compatibility defaults. Explicit
// per-harness policy remains an override; user visibility preferences are applied later.
const nativeApi = nativeApiForRoute('xd', gm.id);
@@ -1282,6 +1359,7 @@ function computeMerged(): Catalog {
const contextWindow = ov.contextWindow ?? gm.contextWindow;
const merged: CatalogModel = {
id: gm.id,
+ discoveredMetadata: { ...pickModelMetadata(gm), ...pickModelMetadata(ov) },
...(nativeApi !== undefined ? { nativeApi } : {}),
...(gm.availability ? { availability: gm.availability } : {}),
// name / contextWindow are required by Model Access v3 and therefore never synthesized.
@@ -1329,7 +1407,8 @@ function computeMerged(): Catalog {
);
for (const agent of agentKeys) {
models[agent] = models[agent]!.map((model) =>
- (!model.mode || model.mode === 'chat' || model.mode === 'responses') && !defaultGatewayModels.has(model.id)
+ (!model.mode || model.mode === 'chat' || model.mode === 'responses') &&
+ !defaultGatewayModels.has(model.id)
? { ...model, defaultEnabled: false }
: model,
);
@@ -1361,31 +1440,49 @@ function computeMerged(): Catalog {
const nativeApi = nativeApiForRoute(provider.id, model.id);
// Pi's independent catalog supplies capabilities, not a separate default.
// Membership remains native; a Registry match only contributes model intent.
- const entry = agent === 'pi' && provider.source !== 'user' && provider.id !== 'xd'
- ? findModelRegistryRoute(b.modelRegistry, provider.id,
- provider.id === 'xai' && !model.id.startsWith('xai/') ? `xai/${model.id}` : model.id)?.entry
- : undefined;
- const intent = entry ? modelDefaultEffort(entry) : undefined;
- const defaultEffort = intent !== undefined
- ? model.efforts.length === 0 ? null
- : clampEffortToSupported(intent, model.efforts) as Effort | null
- : model.defaultEffort;
+ const entry =
+ agent === 'pi' && provider.source !== 'user' && provider.id !== 'xd'
+ ? findModelRegistryRoute(
+ b.modelRegistry,
+ provider.id,
+ provider.id === 'xai' && !model.id.startsWith('xai/')
+ ? `xai/${model.id}`
+ : model.id,
+ )?.entry
+ : undefined;
+ const intent =
+ b.modelRegistry?.schemaVersion !== 4 && entry ? modelDefaultEffort(entry) : undefined;
+ const defaultEffort =
+ intent !== undefined
+ ? model.efforts.length === 0
+ ? null
+ : (clampEffortToSupported(intent, model.efforts) as Effort | null)
+ : model.defaultEffort;
// Product working defaults are distinct from the provider's advertised capacity.
// Apply to each built-in GPT route, including subscription and discount aliases.
// Never enlarge smaller models or overwrite BYOM / explicit preference overrides.
- const conservativeGptDefault = provider.source !== 'user' &&
+ const conservativeGptDefault =
+ provider.source !== 'user' &&
['openai', 'xd'].includes(provider.id) &&
/^(?:(?:codex|openai|chatgpt)\/)?gpt-/.test(model.id) &&
model.contextWindow > 272_000 &&
- !((agent === 'codex' || agent === 'claude-code') &&
- hasLocalContextWindowOverride(localOverrides, provider.id,
- provider.id === 'openai' ? model.id.replace(/^chatgpt\//, '') : model.id, agent));
+ !(
+ (agent === 'codex' || agent === 'claude-code') &&
+ hasLocalContextWindowOverride(
+ localOverrides,
+ provider.id,
+ provider.id === 'openai' ? model.id.replace(/^chatgpt\//, '') : model.id,
+ agent,
+ )
+ );
return {
...model,
- ...(conservativeGptDefault ? {
- contextWindow: 272_000,
- contextWindowMax: model.contextWindowMax ?? model.contextWindow,
- } : {}),
+ ...(conservativeGptDefault
+ ? {
+ contextWindow: 272_000,
+ contextWindowMax: model.contextWindowMax ?? model.contextWindow,
+ }
+ : {}),
defaultEffort,
...(nativeApi !== undefined ? { nativeApi } : {}),
};
@@ -1406,7 +1503,8 @@ function computeMerged(): Catalog {
return [
agent,
models?.map((model) =>
- (!model.mode || model.mode === 'chat' || model.mode === 'responses') && !selected.has(model.id)
+ (!model.mode || model.mode === 'chat' || model.mode === 'responses') &&
+ !selected.has(model.id)
? { ...model, defaultEnabled: false }
: model,
),
@@ -1424,8 +1522,124 @@ function computeMerged(): Catalog {
providers = [...projectedProviders];
}
- if (providers === b.providers) return b; // 无 augment、无 custom → 原样返回
- return { ...b, providers }; // spread 保留 presets 等目录顶层字段
+ if (providers === b.providers && !localOverrides.localModels && !localOverrides.baseModels)
+ return b;
+ const effectiveLocalModels = projectLocalModelCatalog(b);
+ providers = providers.map((provider) => ({
+ ...provider,
+ models: Object.fromEntries(
+ Object.entries(provider.models).map(([agent, models]) => [
+ agent,
+ models?.map((model) => {
+ let next = model;
+ if (
+ b.modelRegistry?.schemaVersion === 4 &&
+ provider.source !== 'user' &&
+ (provider.id === 'xd' || agent === 'pi')
+ ) {
+ next = applyModelMetadata(
+ model,
+ resolveModelMetadata(
+ b.modelRegistry,
+ provider.id,
+ model.id,
+ model.discoveredMetadata ?? catalogModelMetadata(model),
+ undefined,
+ agent,
+ ),
+ );
+ }
+ if (
+ provider.source !== 'user' &&
+ ['openai', 'xd'].includes(provider.id) &&
+ /^(?:(?:codex|openai|chatgpt)\/)?gpt-/.test(next.id) &&
+ next.contextWindow > 272_000 &&
+ !(
+ (agent === 'codex' || agent === 'claude-code') &&
+ hasLocalContextWindowOverride(
+ localOverrides,
+ provider.id,
+ next.id.replace(/^chatgpt\//, ''),
+ agent,
+ )
+ )
+ ) {
+ next = {
+ ...next,
+ contextWindowMax: Math.max(next.contextWindowMax ?? 0, next.contextWindow),
+ contextWindow: 272_000,
+ };
+ }
+ const identity =
+ findModelRegistryRoute(
+ b.modelRegistry,
+ provider.id,
+ model.id,
+ agent === 'pi' ? undefined : (agent as RootAgentKind),
+ )?.entry.modelRef ??
+ (provider.id === MANAGED_OLLAMA_PROVIDER_ID
+ ? effectiveLocalModels?.models.find((local) =>
+ local.variants.some((variant) =>
+ ollamaModelRefsEqual(variant.libraryName, model.id),
+ ),
+ )?.modelRef
+ : undefined) ??
+ findBaseModel(b.modelRegistry, model.id)?.id;
+ const publicPatch = identity ? localOverrides.baseModels?.[identity] : undefined;
+ if (publicPatch) {
+ next = applyModelMetadata(
+ next,
+ resolveModelMetadata(undefined, provider.id, model.id, catalogModelMetadata(next), {
+ ...publicPatch,
+ // Managed Ollama fields are generated import facts, not form edits.
+ ...(provider.source === 'user' &&
+ provider.id !== MANAGED_OLLAMA_PROVIDER_ID &&
+ model.userModelConfig
+ ? runtimeUserModelMetadata(model.userModelConfig)
+ : {}),
+ }),
+ );
+ }
+ return applyExistingModelLocalPatch(
+ provider.id,
+ agent as AgentKind,
+ next,
+ localOverrides,
+ );
+ }),
+ ]),
+ ),
+ }));
+ const modelRegistry = b.modelRegistry
+ ? { ...b.modelRegistry, localModels: effectiveLocalModels }
+ : undefined;
+ return { ...b, modelRegistry, providers };
+}
+
+function projectLocalModelCatalog(catalog: Catalog) {
+ // A local fallback is not a server Registry revision or a source of cloud routes.
+ const localModels =
+ catalog.modelRegistry?.localModels ?? BUNDLED_CATALOG.modelRegistry!.localModels;
+ const userNamedLocalModels = localModels
+ ? {
+ ...localModels,
+ models: localModels.models.map((model) => {
+ const name = model.modelRef
+ ? localOverrides.baseModels?.[model.modelRef]?.name
+ : undefined;
+ return name ? { ...model, name } : model;
+ }),
+ }
+ : undefined;
+ return applyLocalModelCatalogOverrides(
+ userNamedLocalModels,
+ localOverrides.localModels,
+ catalog.modelRegistry?.baseModels ?? BUNDLED_CATALOG.modelRegistry!.baseModels,
+ );
+}
+
+export function getActiveLocalModelCatalog() {
+ return projectLocalModelCatalog(base ?? BUNDLED_CATALOG);
}
/**
@@ -1490,7 +1704,7 @@ function installActiveCatalog(
baseUnverifiedXdMediaKinds = nextUnverifiedXdMediaKinds;
if (customConfigs) {
custom = customConfigs.map((config) =>
- buildUserProvider(config, { modelRegistry: projectionRegistry }),
+ buildUserProvider(config, { modelRegistry: projectionRegistry, presets: catalog.presets }),
);
}
markChanged();
@@ -1575,7 +1789,10 @@ export function commitModelPlaneFromCatalog(
}
if (customConfigs) {
custom = customConfigs.map((config) =>
- buildUserProvider(config, { modelRegistry: trustedCustomProviderRegistry }),
+ buildUserProvider(config, {
+ modelRegistry: trustedCustomProviderRegistry,
+ presets: (base ?? BUNDLED_CATALOG).presets,
+ }),
);
}
markChanged();
@@ -1617,7 +1834,10 @@ export function setCustomProviders(providers: Provider[]): void {
export function setCustomProviderConfigs(configs: CustomProviderConfig[]): void {
customConfigs = [...configs];
custom = customConfigs.map((config) =>
- buildUserProvider(config, { modelRegistry: trustedCustomProviderRegistry }),
+ buildUserProvider(config, {
+ modelRegistry: trustedCustomProviderRegistry,
+ presets: (base ?? BUNDLED_CATALOG).presets,
+ }),
);
markChanged();
}
@@ -1634,18 +1854,37 @@ export function setDiscoveredCodexModels(
// not report windows or image inputs. Preserve only those metadata fields for
// surviving IDs. Cache/auth refresh remains a complete replacement, including [].
const previous = new Map(discoveredCodex.map((model) => [model.id, model]));
- discoveredCodex = options.source === 'list' ? models.map((model) => {
- const known = previous.get(model.id);
- if (!known) return model;
- return {
- ...model,
- ...(known.contextWindowVerified === true ? {
- contextWindow: known.contextWindow, contextWindowVerified: true,
- } : {}),
- ...(known.contextWindowMax !== undefined ? { contextWindowMax: known.contextWindowMax } : {}),
- ...(known.supportsImageInput !== undefined ? { supportsImageInput: known.supportsImageInput } : {}),
- };
- }) : [...models];
+ discoveredCodex =
+ options.source === 'list'
+ ? models.map((model) => {
+ const known = previous.get(model.id);
+ if (!known) return model;
+ return {
+ ...model,
+ discoveredMetadata: {
+ ...(model.discoveredMetadata ?? catalogModelMetadata(model)),
+ ...(known.contextWindowVerified === true
+ ? { contextWindow: known.contextWindow }
+ : {}),
+ ...(known.supportsImageInput !== undefined
+ ? { supportsImageInput: known.supportsImageInput }
+ : {}),
+ },
+ ...(known.contextWindowVerified === true
+ ? {
+ contextWindow: known.contextWindow,
+ contextWindowVerified: true,
+ }
+ : {}),
+ ...(known.contextWindowMax !== undefined
+ ? { contextWindowMax: known.contextWindowMax }
+ : {}),
+ ...(known.supportsImageInput !== undefined
+ ? { supportsImageInput: known.supportsImageInput }
+ : {}),
+ };
+ })
+ : [...models];
markChanged();
}
diff --git a/apps/desktop/src/main/maker-host/codex-model-discovery.ts b/apps/desktop/src/main/maker-host/codex-model-discovery.ts
index 9d5003fc6a..c3b9772129 100644
--- a/apps/desktop/src/main/maker-host/codex-model-discovery.ts
+++ b/apps/desktop/src/main/maker-host/codex-model-discovery.ts
@@ -1,3 +1,4 @@
+import { pickModelMetadata } from '@cindy/model-providers';
/**
* codex-model-discovery —— 从 codex 的 `models_cache.json` 派生出规范化的 Codex 模型快照。
* active-catalog 再把同一份快照投影到 Codex 与 Claude bridge,避免两边名称、排序各维护一套。
@@ -125,24 +126,43 @@ export function mapCodexModelsToCatalog(raw: unknown): CatalogModel[] {
const displayName = str(m.display_name) ?? slug;
// cache 明示了才算真实上限;缺字段时补的 272k 只够展示(见下方 app-server mapper 注释)。
const contextWindowVerified = positiveTokens(m.context_window);
- const contextWindow = contextWindowVerified ? (m.context_window as number)
+ const contextWindow = contextWindowVerified
+ ? (m.context_window as number)
: Math.min(272_000, positiveTokens(m.max_context_window) ? m.max_context_window : 272_000);
// Native maximum and working default are separate facts. Never manufacture a
// maximum from the working window when the upstream omitted it.
- const contextWindowMax = positiveTokens(m.max_context_window) &&
+ const contextWindowMax =
+ positiveTokens(m.max_context_window) &&
(!contextWindowVerified || m.max_context_window >= contextWindow)
- ? m.max_context_window : undefined;
+ ? m.max_context_window
+ : undefined;
const requestedDefault = str(m.default_reasoning_level);
- const defaultEffort = requestedDefault && efforts.includes(requestedDefault)
- ? requestedDefault as CatalogModel['defaultEffort']
- : defaultEffortForCapabilities(efforts as CatalogModel['efforts']);
- const inputModalities = Array.isArray(m.input_modalities) &&
+ const defaultEffort =
+ requestedDefault && efforts.includes(requestedDefault)
+ ? (requestedDefault as CatalogModel['defaultEffort'])
+ : defaultEffortForCapabilities(efforts as CatalogModel['efforts']);
+ const inputModalities =
+ Array.isArray(m.input_modalities) &&
m.input_modalities.every((value) => typeof value === 'string')
- ? m.input_modalities as string[] : undefined;
- const priority = typeof m.priority === 'number' && Number.isFinite(m.priority) ? m.priority : 50;
+ ? (m.input_modalities as string[])
+ : undefined;
+ const priority =
+ typeof m.priority === 'number' && Number.isFinite(m.priority) ? m.priority : 50;
const model: CatalogModel = {
id: slug,
+ discoveredMetadata: pickModelMetadata({
+ name: str(m.display_name),
+ description: str(m.description),
+ contextWindow: m.context_window,
+ supportsImageInput:
+ inputModalities !== undefined ? inputModalities.includes('image') : undefined,
+ efforts: Array.isArray(m.supported_reasoning_levels) ? efforts : undefined,
+ defaultEffort: m.default_reasoning_level,
+ supportsFastMode: Array.isArray(m.service_tiers)
+ ? hasPriorityTier(m.service_tiers)
+ : undefined,
+ }),
name: displayName,
group: 'gpt',
// 以静态模型的已知 priority/order 为锚点插值;active-catalog 对新增项做稳定排序。
@@ -151,7 +171,8 @@ export function mapCodexModelsToCatalog(raw: unknown): CatalogModel[] {
contextWindow,
...(contextWindowMax !== undefined ? { contextWindowMax } : {}),
...(inputModalities !== undefined
- ? { supportsImageInput: inputModalities.includes('image') } : {}),
+ ? { supportsImageInput: inputModalities.includes('image') }
+ : {}),
...(contextWindowVerified ? { contextWindowVerified: true } : {}),
efforts: efforts as CatalogModel['efforts'],
defaultEffort,
@@ -209,6 +230,16 @@ export function mapCodexAppServerModelsToCatalog(
const supportsFastMode = tiers.some((tier) => tier === 'priority' || tier === 'fast');
const model: CatalogModel = {
id: slug,
+ discoveredMetadata: pickModelMetadata({
+ name: str(raw.displayName),
+ description: str(raw.description),
+ efforts: Array.isArray(raw.supportedReasoningEfforts) ? efforts : undefined,
+ defaultEffort: requestedDefault,
+ supportsFastMode:
+ Array.isArray(raw.serviceTiers) || Array.isArray(raw.additionalSpeedTiers)
+ ? supportsFastMode
+ : undefined,
+ }),
name: str(raw.displayName) ?? slug,
group: 'gpt',
// app-server 已按官方 picker 顺序返回;给每项稳定的小数锚点保住该顺序。
@@ -223,7 +254,8 @@ export function mapCodexAppServerModelsToCatalog(
status: 'active',
defaultEnabled: !DEFAULT_HIDDEN_SLUGS.has(slug),
...(Array.isArray(raw.serviceTiers) || Array.isArray(raw.additionalSpeedTiers)
- ? { supportsFastMode } : {}),
+ ? { supportsFastMode }
+ : {}),
};
if (efforts.includes('xhigh')) model.effortDisplayNames = { xhigh: 'Extra High' };
out.push(model);
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index 54b34b36a7..220ce671cf 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -1,3 +1,8 @@
+import {
+ mergeDiscoveredRuntimeModels,
+ validModelMetadata,
+ type DiscoveredModel,
+} from '@cindy/model-providers';
/**
* custom-provider-store —— 用户自定义供应商**非凭证配置**的 localDb CRUD。
*
@@ -86,7 +91,10 @@ function isPiReasoningEffort(value: unknown): value is PiReasoningEffort {
function isReasoningEffortForAgent(agent: string, value: unknown): boolean {
if (agent === 'pi') return isPiReasoningEffort(value);
- return typeof value === 'string' && (CINDY_RUNTIME_REASONING_EFFORTS as readonly string[]).includes(value);
+ return (
+ typeof value === 'string' &&
+ (CINDY_RUNTIME_REASONING_EFFORTS as readonly string[]).includes(value)
+ );
}
function isPiModelApi(value: unknown): value is PiModelApi {
@@ -97,6 +105,7 @@ function parseStoredReasoningCapability(
agent: AgentKind,
model: Record<string, unknown>,
): Partial<ProviderRuntimeModelConfig> {
+ if (model.reasoning === false) return { reasoning: false };
if (model.reasoning !== true || !Array.isArray(model.reasoningEfforts)) {
return {};
}
@@ -190,6 +199,11 @@ function isAllowedWireProtocol(agent: string, value: unknown): value is Provider
);
}
+/** ProviderPreset.id is an opaque, non-empty string in the catalog contract. */
+function isCatalogPresetId(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0;
+}
+
function validateRuntime(agent: string, rt: unknown): ValidationResult {
if (!rt || typeof rt !== 'object') return invalid(`runtime '${agent}' must be an object`);
const r = rt as Record<string, unknown>;
@@ -227,6 +241,8 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {
if (typeof mm.name !== 'string' || mm.name.trim().length === 0) {
return invalid(`runtime '${agent}' model.name required`);
}
+ if (mm.discoveredMetadata !== undefined && !validModelMetadata(mm.discoveredMetadata))
+ return invalid(`runtime '${agent}' discoveredMetadata invalid`);
if (
mm.contextWindow !== undefined &&
(typeof mm.contextWindow !== 'number' ||
@@ -350,6 +366,8 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {
return invalid(`runtime '${agent}' modelsUrl is not a valid URL`);
}
}
+ if (r.catalogPresetId !== undefined && !isCatalogPresetId(r.catalogPresetId))
+ return invalid(`runtime '${agent}' catalogPresetId invalid`);
if (
r.piCatalogProviderId !== undefined &&
(agent !== 'pi' ||
@@ -534,6 +552,8 @@ function normalizeRuntime(
.map((m) => ({
id: m.id.trim(),
name: m.name.trim(),
+ ...(m.discoveredMetadata ? { discoveredMetadata: m.discoveredMetadata } : {}),
+ ...(m.nameExplicit === true ? { nameExplicit: true } : {}),
...(agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.route
? {
@@ -546,7 +566,9 @@ function normalizeRuntime(
: {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
+ ...(typeof m.supportsImageInput === 'boolean'
+ ? { supportsImageInput: m.supportsImageInput }
+ : {}),
...(m.reasoning === true && m.reasoningEfforts?.length
? {
reasoning: true,
@@ -565,7 +587,11 @@ function normalizeRuntime(
seen.add(m.id);
return true;
});
- const out: CustomProviderRuntimeConfig = { baseUrl: rt.baseUrl.trim(), models };
+ const out: CustomProviderRuntimeConfig = {
+ baseUrl: rt.baseUrl.trim(),
+ models,
+ ...(rt.catalogPresetId ? { catalogPresetId: rt.catalogPresetId } : {}),
+ };
if (rt.wireProtocol) out.wireProtocol = rt.wireProtocol;
if (agent === 'codex' && rt.supportsImageGeneration === true) {
out.supportsImageGeneration = true;
@@ -659,35 +685,17 @@ function invalidateEditedPiCatalogMarker(
export function mergeDiscoveredModelsIntoConfig(
config: CustomProviderConfig,
agent: AgentKind,
- discovered: { id: string; name: string; contextWindow?: number }[],
+ discovered: DiscoveredModel[],
): CustomProviderConfig | null {
const rt = config.runtimes[agent];
if (!rt) return null;
- const existing = new Set(rt.models.map((m) => m.id));
- const fresh = discovered.filter((m) => m.id && m.name && !existing.has(m.id));
- if (fresh.length === 0) return null;
- return {
- ...config,
- runtimes: {
- ...config.runtimes,
- [agent]: {
- ...rt,
- models: [
- ...rt.models,
- // 端点声明了上下文长度就随发现落盘,缺省则回落保守默认(#386)。
- ...fresh.map((m) => ({
- id: m.id,
- name: m.name,
- ...(typeof m.contextWindow === 'number' &&
- Number.isFinite(m.contextWindow) &&
- m.contextWindow > 0
- ? { contextWindow: Math.floor(m.contextWindow) }
- : {}),
- })),
- ],
- },
- },
- };
+ const models = mergeDiscoveredRuntimeModels(rt.models, discovered);
+ return JSON.stringify(models) === JSON.stringify(rt.models)
+ ? null
+ : {
+ ...config,
+ runtimes: { ...config.runtimes, [agent]: { ...rt, models } },
+ };
}
/** 安全解析 auth 列 JSON(坏数据 / 结构不完整兜底为 undefined = API key 历史形态)。 */
@@ -742,19 +750,26 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRun
name: String(m.name ?? ''),
...(agent === 'pi' && isPiModelApi(m.piApi) ? { piApi: m.piApi } : {}),
...(route ? { route } : {}),
+ ...(validModelMetadata(m.discoveredMetadata)
+ ? { discoveredMetadata: m.discoveredMetadata }
+ : {}),
+ ...(m.nameExplicit === true ? { nameExplicit: true } : {}),
...(typeof m.contextWindow === 'number' &&
Number.isFinite(m.contextWindow) &&
m.contextWindow > 0
? { contextWindow: m.contextWindow }
: {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
+ ...(typeof m.supportsImageInput === 'boolean'
+ ? { supportsImageInput: m.supportsImageInput }
+ : {}),
...parseStoredReasoningCapability(agent, m),
...(m.thinkingToggle === true ? { thinkingToggle: true } : {}),
};
})
: [];
const entry: CustomProviderRuntimeConfig = {
+ ...(isCatalogPresetId(r.catalogPresetId) ? { catalogPresetId: r.catalogPresetId } : {}),
baseUrl,
models,
};
diff --git a/apps/desktop/src/main/maker-host/generic-oauth.ts b/apps/desktop/src/main/maker-host/generic-oauth.ts
index 4a2e9efe8e..11f3aed638 100644
--- a/apps/desktop/src/main/maker-host/generic-oauth.ts
+++ b/apps/desktop/src/main/maker-host/generic-oauth.ts
@@ -1,3 +1,4 @@
+import { pickModelMetadata, type DiscoveredModel } from '@cindy/model-providers';
/**
* generic-oauth —— 目录 `auth.oauth` 描述符驱动的通用 OAuth Runner。
*
@@ -509,10 +510,7 @@ export interface GenericOAuthLoginOptions {
}
// 同一时刻每个 provider 只允许一个登录流。
-const activeLogins = new Map<
- string,
- { abort: AbortController; close: () => void }
->();
+const activeLogins = new Map<string, { abort: AbortController; close: () => void }>();
/** 取消某供应商进行中的登录。 */
export function cancelGenericOAuthLogin(providerId: string): void {
@@ -574,9 +572,9 @@ async function runDeviceCodeGrant(
typeof authorization?.device_code === 'string' ? authorization.device_code : '';
const userCode = typeof authorization?.user_code === 'string' ? authorization.user_code : '';
const verificationUrl =
- safeVerificationUrl(authorization?.verification_uri_complete)
- ?? safeVerificationUrl(authorization?.verification_uri)
- ?? safeVerificationUrl(authorization?.verification_url);
+ safeVerificationUrl(authorization?.verification_uri_complete) ??
+ safeVerificationUrl(authorization?.verification_uri) ??
+ safeVerificationUrl(authorization?.verification_url);
const expiresInSeconds = positiveNumber(authorization?.expires_in);
if (!deviceCode || !userCode || !verificationUrl || !expiresInSeconds) {
throw new Error('invalid_device_authorization_response');
@@ -623,9 +621,9 @@ async function runDeviceCodeGrant(
});
const payload = await readJsonObject(response);
if (
- response.ok
- && typeof payload?.access_token === 'string'
- && payload.access_token.length > 0
+ response.ok &&
+ typeof payload?.access_token === 'string' &&
+ payload.access_token.length > 0
) {
return payload as unknown as TokenResponse;
}
@@ -639,9 +637,7 @@ async function runDeviceCodeGrant(
if (error === 'access_denied') throw new Error('device_access_denied');
if (error === 'expired_token') throw new Error('device_code_expired');
throw new Error(
- error
- ? `device_token_error_${error}`
- : `device_token_exchange_failed_${response.status}`,
+ error ? `device_token_error_${error}` : `device_token_exchange_failed_${response.status}`,
);
}
throw new Error('device_code_expired');
@@ -658,8 +654,7 @@ export async function runGenericOAuthLogin(
): Promise<GenericOAuthLoginResult> {
cancelGenericOAuthLogin(provider.id);
- const listener =
- oauth.flow === 'device-code' ? null : new CallbackListener(provider.name);
+ const listener = oauth.flow === 'device-code' ? null : new CallbackListener(provider.name);
const abort = new AbortController();
activeLogins.set(provider.id, {
abort,
@@ -803,7 +798,7 @@ export async function discoverGenericOAuthModels(
oauth: OAuthProviderDescriptor,
discoveryUrl?: string,
agent?: AgentKind,
-): Promise<{ id: string; name: string; contextWindow?: number }[] | null> {
+): Promise<DiscoveredModel[] | null> {
const url = discoveryUrl ?? oauth.modelsDiscoveryUrl;
if (!url) return null;
const token = readCachedGenericOAuthAccessToken(providerId, oauth);
@@ -839,9 +834,7 @@ export async function discoverGenericOAuthModels(
* 回落保守默认(#386)。
* 纯函数——OAuth 自动发现(本模块)与 API key 表单「获取模型列表」(provider-model-fetch)共用。
*/
-export function parseModelsListResponse(
- json: unknown,
-): { id: string; name: string; contextWindow?: number }[] | null {
+export function parseModelsListResponse(json: unknown): DiscoveredModel[] | null {
const list = (() => {
if (!json || typeof json !== 'object') return null;
const o = json as { data?: unknown; models?: unknown };
@@ -850,7 +843,7 @@ export function parseModelsListResponse(
return null;
})();
if (!list) return null;
- const out: { id: string; name: string; contextWindow?: number }[] = [];
+ const out: DiscoveredModel[] = [];
const seen = new Set<string>();
for (const item of list) {
const id =
@@ -890,11 +883,41 @@ export function parseModelsListResponse(
// 异常值(如 context_length: 1e20)——这类值会通过取整后为正的校验,但落盘后
// Main 的正数校验反而会因为超界而拒绝整份供应商配置,内置 OAuth 发现分支则会
// 把这个失真值当真实窗口注入目录(review P2)。
- (v) => typeof v === 'number' && Number.isFinite(v) && Math.floor(v) > 0 && Number.isSafeInteger(Math.floor(v)),
+ (v) =>
+ typeof v === 'number' &&
+ Number.isFinite(v) &&
+ Math.floor(v) > 0 &&
+ Number.isSafeInteger(Math.floor(v)),
)
: undefined;
+ const record = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
+ const architecture = record.architecture as { input_modalities?: unknown } | undefined;
+ const reasoning = record.reasoning as
+ { supportedEfforts?: unknown; defaultEffort?: unknown } | undefined;
+ const rawDefault =
+ reasoning?.defaultEffort !== undefined ? reasoning.defaultEffort : record.default_effort;
+ const discoveredMetadata = pickModelMetadata({
+ ...([rec?.display_name, rec?.name].some(
+ (value) => typeof value === 'string' && value.trim().length > 0,
+ )
+ ? { name }
+ : {}),
+ description: record.description,
+ group: record.group,
+ contextWindow: typeof rawWindow === 'number' ? Math.floor(rawWindow) : undefined,
+ maxOutputTokens: record.max_output_tokens ?? record.maxOutputTokens,
+ efforts: reasoning?.supportedEfforts ?? record.supported_efforts,
+ defaultEffort: rawDefault === 'none' ? null : rawDefault,
+ supportsFastMode: record.supports_fast_mode ?? record.supportsServiceTier,
+ supportsImageInput:
+ record.supports_image_input ??
+ (Array.isArray(architecture?.input_modalities)
+ ? architecture.input_modalities.includes('image')
+ : undefined),
+ });
out.push({
id,
+ discoveredMetadata,
name,
...(typeof rawWindow === 'number' ? { contextWindow: Math.floor(rawWindow) } : {}),
});
diff --git a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
index 63304d44ae..253b2fed94 100644
--- a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
+++ b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
@@ -1,3 +1,4 @@
+import { pickModelMetadata } from '@cindy/model-providers';
/**
* model-discovery/anthropic —— Anthropic(Claude.ai 订阅)模型清单的动态发现。
* ---------------------------------------------------------------------------
@@ -45,11 +46,7 @@ import { app } from 'electron';
import fsp from 'node:fs/promises';
import path from 'node:path';
-import type {
- CatalogModel,
- Effort,
- ProviderModelDiscoveryFailure,
-} from '@cindy/model-providers';
+import type { CatalogModel, Effort, ProviderModelDiscoveryFailure } from '@cindy/model-providers';
import { createLogger } from '../../logger.js';
import {
@@ -64,7 +61,14 @@ import { outboundFetch } from '../outbound-fetch.js';
const log = createLogger('model-discovery:anthropic');
-const VALID_EFFORTS: ReadonlySet<string> = new Set(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
+const VALID_EFFORTS: ReadonlySet<string> = new Set([
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ 'max',
+]);
const HTTP_TIMEOUT_MS = 15_000;
/** /v1/models 游标分页的最大页数(现实模型数远小于单页 1000,纯防御)。 */
const MAX_MODEL_PAGES = 5;
@@ -205,7 +209,9 @@ function resetHttpShrinkStreak(): void {
*/
function persistPendingShrink(): void {
const state =
- httpShrinkSignature !== null ? { signature: httpShrinkSignature, streak: httpShrinkStreak } : null;
+ httpShrinkSignature !== null
+ ? { signature: httpShrinkSignature, streak: httpShrinkStreak }
+ : null;
const generation = authGeneration;
void enqueueCacheMutation(async () => {
if (generation !== authGeneration || !hasClaudeAiOAuth()) return;
@@ -221,9 +227,10 @@ function persistPendingShrink(): void {
}
if (!raw) return;
if (state) raw.pendingShrink = state;
- else if (raw.pendingShrink === undefined) return; // 无变化不写盘
+ else if (raw.pendingShrink === undefined)
+ return; // 无变化不写盘
else delete raw.pendingShrink;
- const temp = `${file}.${process.pid}.${cacheTempSequence += 1}.tmp`;
+ const temp = `${file}.${process.pid}.${(cacheTempSequence += 1)}.tmp`;
try {
await fsp.writeFile(temp, JSON.stringify(raw, null, 2), 'utf-8');
if (generation !== authGeneration || !hasClaudeAiOAuth()) return;
@@ -245,7 +252,10 @@ function persistPendingShrink(): void {
* 只有 HTTP 通道参与收敛:它是 Anthropic 官方列模型端点,连续一致可作可用性证据;
* SDK 捕获(本地 CLI 注册表,正是打塌事故的退化来源)永不收敛,等 HTTP 纠正。
*/
-export function evaluateHttpShrink(prevCount: number, nextIds: readonly string[]): 'accept' | 'reject' {
+export function evaluateHttpShrink(
+ prevCount: number,
+ nextIds: readonly string[],
+): 'accept' | 'reject' {
let verdict: 'accept' | 'reject';
if (!isDegenerateModelListShrink(prevCount, nextIds.length)) {
resetHttpShrinkStreak();
@@ -280,9 +290,7 @@ export interface SdkMappedModel {
function fallbackEffortBaseline(id: string): { efforts: Effort[]; defaultEffort: Effort | null } {
const catalogBaseline = getCindyModelEffortBaseline(id);
if (catalogBaseline) return catalogBaseline;
- const efforts: Effort[] = /haiku/.test(id)
- ? []
- : ['low', 'medium', 'high', 'xhigh', 'max'];
+ const efforts: Effort[] = /haiku/.test(id) ? [] : ['low', 'medium', 'high', 'xhigh', 'max'];
return { efforts, defaultEffort: pickDefaultEffort(efforts) };
}
@@ -311,8 +319,7 @@ export function mapAnthropicSdkModels(raw: unknown): SdkMappedModel[] {
const id = normalizeModelId(e.value);
if (!id.startsWith('claude') || seen.has(id)) continue;
seen.add(id);
- const hasEffortInfo =
- e.supportsEffort !== undefined || e.supportedEffortLevels !== undefined;
+ const hasEffortInfo = e.supportsEffort !== undefined || e.supportedEffortLevels !== undefined;
const hasFastModeInfo = e.supportsFastMode !== undefined;
const fallback = fallbackEffortBaseline(id);
let efforts: Effort[];
@@ -326,7 +333,8 @@ export function mapAnthropicSdkModels(raw: unknown): SdkMappedModel[] {
} else {
const levels = toEfforts(e.supportedEffortLevels);
// supportsEffort=true 但没给档位清单:按目录基线 / 确定性默认合成,不解读为不可调。
- efforts = levels && levels.length > 0 ? levels : e.supportsEffort === true ? fallback.efforts : [];
+ efforts =
+ levels && levels.length > 0 ? levels : e.supportsEffort === true ? fallback.efforts : [];
defaultEffort =
levels && levels.length > 0
? pickDefaultEffort(efforts)
@@ -339,6 +347,13 @@ export function mapAnthropicSdkModels(raw: unknown): SdkMappedModel[] {
hasFastModeInfo,
model: {
id,
+ discoveredMetadata: pickModelMetadata({
+ name: e.displayName,
+ description: e.description,
+ efforts:
+ e.supportsEffort === false ? [] : (toEfforts(e.supportedEffortLevels) ?? undefined),
+ supportsFastMode: e.supportsFastMode,
+ }),
name: typeof e.displayName === 'string' && e.displayName.length > 0 ? e.displayName : id,
group: 'anthropic',
sortOrder: out.length,
@@ -378,9 +393,7 @@ interface CapabilityMappedModel {
* 把一份完整存在性快照与上一轮能力状态逐字段合并。缺席字段只有上一轮已标记为明确
* 来源时才保留旧值;否则直接使用 mapper 生成的当前目录基线。
*/
-function mergeCapabilitiesWithPrevious(
- mapped: readonly CapabilityMappedModel[],
-): {
+function mergeCapabilitiesWithPrevious(mapped: readonly CapabilityMappedModel[]): {
models: CatalogModel[];
explicitEffortIds: Set<string>;
explicitFastModeIds: Set<string>;
@@ -397,6 +410,13 @@ function mergeCapabilitiesWithPrevious(
nextExplicitEffort.add(model.id);
merged = {
...merged,
+ discoveredMetadata: {
+ ...merged.discoveredMetadata,
+ ...pickModelMetadata({
+ efforts: prev.discoveredMetadata?.efforts,
+ defaultEffort: prev.discoveredMetadata?.defaultEffort,
+ }),
+ },
efforts: prev.efforts,
defaultEffort: prev.defaultEffort,
};
@@ -405,7 +425,14 @@ function mergeCapabilitiesWithPrevious(
nextExplicitFastMode.add(model.id);
} else if (prev && explicitFastModeModelIds.has(model.id)) {
nextExplicitFastMode.add(model.id);
- merged = { ...merged, supportsFastMode: prev.supportsFastMode };
+ merged = {
+ ...merged,
+ discoveredMetadata: {
+ ...merged.discoveredMetadata,
+ ...pickModelMetadata({ supportsFastMode: prev.discoveredMetadata?.supportsFastMode }),
+ },
+ supportsFastMode: prev.supportsFastMode,
+ };
}
return merged;
});
@@ -460,6 +487,12 @@ export function mapAnthropicHttpModels(raw: unknown): HttpMappedModel[] {
explicitContextWindow: maxInput,
model: {
id,
+ discoveredMetadata: pickModelMetadata({
+ name: e.display_name,
+ contextWindow: maxInput,
+ efforts: capEfforts ?? undefined,
+ supportsFastMode: caps?.fast_mode,
+ }),
name: typeof e.display_name === 'string' && e.display_name.length > 0 ? e.display_name : id,
group: 'anthropic',
sortOrder: out.length,
@@ -534,7 +567,7 @@ async function applyModels(
await enqueueCacheMutation(async () => {
if (!generationCanApply(generation, models)) return;
const file = cacheFilePath();
- const temp = `${file}.${process.pid}.${cacheTempSequence += 1}.tmp`;
+ const temp = `${file}.${process.pid}.${(cacheTempSequence += 1)}.tmp`;
try {
await fsp.mkdir(path.dirname(file), { recursive: true });
if (!generationCanApply(generation, models)) return;
@@ -653,6 +686,15 @@ export async function loadAnthropicModelsFromDiskCache(): Promise<void> {
const { contextWindowVerified: _staleProvenance, ...rest } = model;
return {
...rest,
+ discoveredMetadata:
+ model.discoveredMetadata ??
+ pickModelMetadata({
+ contextWindow: explicitWindows.get(model.id),
+ efforts: restoredExplicitEffortIds.has(model.id) ? model.efforts : undefined,
+ supportsFastMode: restoredExplicitFastModeIds.has(model.id)
+ ? model.supportsFastMode
+ : undefined,
+ }),
...contextWindowFor(model.id, explicitWindows.get(model.id)),
...(effortBaseline ?? {}),
};
@@ -689,7 +731,12 @@ export function noteAnthropicSdkSupportedModels(raw: unknown): void {
// provenance 静默擦掉, 之后就不再拿这个真实上限去收敛虚高的上报值了。
const base =
explicit !== undefined
- ? { ...model, contextWindow: explicit, contextWindowVerified: true as const }
+ ? {
+ ...model,
+ discoveredMetadata: { ...model.discoveredMetadata, contextWindow: explicit },
+ contextWindow: explicit,
+ contextWindowVerified: true as const,
+ }
: model;
return { model: base, hasEffortInfo, hasFastModeInfo };
});
@@ -718,12 +765,28 @@ export function noteAnthropicSdkSupportedModels(raw: unknown): void {
if (patch.hasEffortInfo) {
next = {
...next,
+ discoveredMetadata: {
+ ...next.discoveredMetadata,
+ ...pickModelMetadata({
+ efforts: patch.model.discoveredMetadata?.efforts,
+ defaultEffort: patch.model.discoveredMetadata?.defaultEffort,
+ }),
+ },
efforts: patch.model.efforts,
defaultEffort: patch.model.defaultEffort,
};
}
if (patch.hasFastModeInfo) {
- next = { ...next, supportsFastMode: patch.model.supportsFastMode };
+ next = {
+ ...next,
+ discoveredMetadata: {
+ ...next.discoveredMetadata,
+ ...pickModelMetadata({
+ supportsFastMode: patch.model.discoveredMetadata?.supportsFastMode,
+ }),
+ },
+ supportsFastMode: patch.model.supportsFastMode,
+ };
}
return next;
});
@@ -749,9 +812,11 @@ export function noteAnthropicSdkSupportedModels(raw: unknown): void {
return;
}
log.info(`anthropic models captured from SDK init: ${models.length}`);
- void applyModels(models, true, generation, explicitEffortIds, explicitFastModeIds).catch((err) => {
- log.warn('apply anthropic SDK models failed', { error: String(err) });
- });
+ void applyModels(models, true, generation, explicitEffortIds, explicitFastModeIds).catch(
+ (err) => {
+ log.warn('apply anthropic SDK models failed', { error: String(err) });
+ },
+ );
}
/** 非 2xx 响应:带上状态码与响应体片段抛出 —— 地域拒绝只能从响应体认出来。 */
@@ -1088,7 +1153,8 @@ export function refreshAnthropicModelsFromHttp(options?: {
// 可用 —— 那两种同样是 unauthorized。凭证还在、也还能刷,才是暂时性故障。
if (refreshed == null) {
const credential = readClaudeAiOAuth();
- const stillRefreshable = typeof credential?.refreshToken === 'string' && credential.refreshToken.length > 0;
+ const stillRefreshable =
+ typeof credential?.refreshToken === 'string' && credential.refreshToken.length > 0;
if (refreshError !== null || stillRefreshable) {
noteDiscoveryFailure(
gen,
@@ -1131,7 +1197,12 @@ export function refreshAnthropicModelsFromHttp(options?: {
// 退化判定必须先于任何状态写入:被拒快照连 explicitWindows 也不许污染,
// 否则后续 SDK 捕获会把退化响应带来的窗口值用作精确记账(review P2)。
// 连续多次相同的骤减快照经 evaluateHttpShrink 收敛放行(真实批量下架自愈)。
- if (evaluateHttpShrink(lastApplied.length, mapped.map((m) => m.model.id)) === 'reject') {
+ if (
+ evaluateHttpShrink(
+ lastApplied.length,
+ mapped.map((m) => m.model.id),
+ ) === 'reject'
+ ) {
log.warn(
`anthropic /v1/models response looks degenerate (${lastApplied.length} -> ${mapped.length}); keeping current list (streak ${httpShrinkStreak}/${CONFIRMED_SHRINK_STREAK})`,
);
diff --git a/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts b/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
index 6bdfa444ee..58488491aa 100644
--- a/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
@@ -1,3 +1,12 @@
+import {
+ validModelMetadata,
+ type ModelMetadata,
+ type BaseModel,
+ parseLocalModelCatalog,
+ type LocalModelCatalog,
+ type LocalCatalogModel,
+ type AgentKind,
+} from '@cindy/model-providers';
/**
* localCatalogOverrides —— 用户本地模型目录 override 的**纯合并逻辑**(零 IO;
* 持久化见 maker-host/model-catalog-override-store.ts)。
@@ -9,7 +18,7 @@
* - 本地参考价 → usage/modelPriceOverrideStore;
* - RoutingDescriptor / auth / upstream → 永不属于任何 override 面。
*
- * 形状(v1):key = `${providerId}:${modelId}`(**不含 agent**),一条记录经
+ * 形状(v1):key = `${encodeURIComponent(providerId)}:${modelId}`(**不含 agent**),一条记录经
* base + perAgent(claude-code/codex) 表达跨 root 差异 —— 修 xAI Codex 专属
* 思考档 = 一条 { perAgent: { codex: { efforts } } } patch,不用双写。
* - additions:完整新实体(base+perAgent 合成后须能力自洽),同 key 整条
@@ -53,6 +62,7 @@ export interface ModelCatalogOverrideFields {
efforts?: Effort[];
defaultEffort?: Effort | null;
supportsFastMode?: boolean;
+ supportsImageInput?: boolean;
/** 与 Registry 使用同一作者侧 lifecycle 词汇;应用到 CatalogModel 时 preview→alpha。 */
status?: 'active' | 'preview' | 'deprecated';
}
@@ -63,19 +73,33 @@ export interface ModelCatalogOverrideFields {
*/
export type ModelCatalogPerAgentOverrideFields = Pick<
ModelCatalogOverrideFields,
- 'contextWindow' | 'maxOutput' | 'efforts' | 'defaultEffort' | 'supportsFastMode'
+ | 'contextWindow'
+ | 'maxOutput'
+ | 'efforts'
+ | 'defaultEffort'
+ | 'supportsFastMode'
+ | 'supportsImageInput'
>;
export interface ModelCatalogOverrideEntry {
/** 消费 membership;缺省 = provider policy 的全部 root + wire bridge,且必须含至少一个 root。 */
- agents?: RootAgentKind[];
+ agents?: AgentKind[];
base?: ModelCatalogOverrideFields;
- perAgent?: Partial<Record<RootAgentKind, ModelCatalogPerAgentOverrideFields>>;
+ perAgent?: Partial<Record<AgentKind, ModelCatalogPerAgentOverrideFields>>;
}
+export interface LocalModelCatalogOverrides {
+ featuredIds?: string[];
+ patches?: Record<string, Partial<LocalCatalogModel>>;
+ additions?: LocalCatalogModel[];
+ removedIds?: string[];
+}
export interface ModelCatalogOverrides {
+ /** Sparse user-owned public metadata patches, keyed by canonical model identity. */
+ baseModels?: Record<string, ModelMetadata>;
+ localModels?: LocalModelCatalogOverrides;
version: 1;
- /** key = `${providerId}:${modelId}`。 */
+ /** key = `${encodeURIComponent(providerId)}:${modelId}`。 */
additions: Record<string, ModelCatalogOverrideEntry>;
patches: Record<string, ModelCatalogOverrideEntry>;
}
@@ -102,10 +126,17 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
function parseKey(key: string): { providerId: string; modelId: string } | null {
const sep = key.indexOf(':');
if (sep <= 0 || sep === key.length - 1) return null;
- const providerId = key.slice(0, sep);
+ let providerId: string;
+ try {
+ providerId = decodeURIComponent(key.slice(0, sep));
+ } catch {
+ return null;
+ }
const modelId = key.slice(sep + 1);
- // allowlist 之外(含 xd 与任意未知 provider)一律无效:本地不能造 XD/未知供应商实体。
- if (!MODEL_PLANE_POLICIES.has(providerId)) return null;
+ // Escape only the provider segment; model IDs may already contain colons.
+ // Require canonical encoding so parsing and direct lookups share one key.
+ if (encodeURIComponent(providerId) !== key.slice(0, sep)) return null;
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(providerId)) return null;
if (modelId.length > 256) return null;
return { providerId, modelId };
}
@@ -123,7 +154,8 @@ function sanitizeFields(
k !== 'maxOutput' &&
k !== 'efforts' &&
k !== 'defaultEffort' &&
- k !== 'supportsFastMode'
+ k !== 'supportsFastMode' &&
+ k !== 'supportsImageInput'
) {
return null;
}
@@ -162,9 +194,10 @@ function sanitizeFields(
if (v !== null && (typeof v !== 'string' || !VALID_EFFORTS.has(v))) return null;
out.defaultEffort = v as Effort | null;
break;
+ case 'supportsImageInput':
case 'supportsFastMode':
if (typeof v !== 'boolean') return null;
- out.supportsFastMode = v;
+ out[k] = v;
break;
case 'status':
// 'retired' 在此被拒:本地禁写 tombstone,复活远端 retired 只能走完整 addition。
@@ -183,7 +216,7 @@ function sanitizeFields(
if (out.efforts !== undefined && out.defaultEffort !== undefined) {
if (out.efforts.length === 0) {
if (out.defaultEffort !== null) return null;
- } else if (out.defaultEffort === null || !out.efforts.includes(out.defaultEffort)) {
+ } else if (out.defaultEffort !== null && !out.efforts.includes(out.defaultEffort)) {
return null;
}
}
@@ -198,7 +231,7 @@ function sanitizeEntry(raw: unknown): ModelCatalogOverrideEntry | null {
if (
!Array.isArray(v) ||
v.length === 0 ||
- v.some((a) => a !== 'claude-code' && a !== 'codex') ||
+ v.some((a) => a !== 'claude-code' && a !== 'codex' && a !== 'pi') ||
new Set(v).size !== v.length
)
return null;
@@ -211,7 +244,7 @@ function sanitizeEntry(raw: unknown): ModelCatalogOverrideEntry | null {
if (!isPlainObject(v)) return null;
const perAgent: ModelCatalogOverrideEntry['perAgent'] = {};
for (const [agent, fields] of Object.entries(v)) {
- if (agent !== 'claude-code' && agent !== 'codex') return null;
+ if (agent !== 'claude-code' && agent !== 'codex' && agent !== 'pi') return null;
const sanitized = sanitizeFields(fields, 'perAgent');
if (!sanitized) return null;
perAgent[agent] = sanitized;
@@ -262,6 +295,7 @@ function additionModelFor(
efforts: f.efforts,
defaultEffort,
...(f.supportsFastMode !== undefined ? { supportsFastMode: f.supportsFastMode } : {}),
+ ...(f.supportsImageInput !== undefined ? { supportsImageInput: f.supportsImageInput } : {}),
...(f.status !== undefined
? { status: f.status === 'preview' ? ('alpha' as const) : f.status }
: {}),
@@ -280,10 +314,29 @@ export function sanitizeModelCatalogOverrides(raw: unknown): SanitizeResult {
return { overrides: out, invalid: ['version'] };
}
for (const key of Object.keys(raw)) {
- if (key !== 'version' && key !== 'additions' && key !== 'patches') {
+ if (
+ key !== 'version' &&
+ key !== 'additions' &&
+ key !== 'patches' &&
+ key !== 'localModels' &&
+ key !== 'baseModels'
+ ) {
invalid.push(`root:${key}`);
}
}
+ if (raw.baseModels !== undefined) {
+ if (!isPlainObject(raw.baseModels)) invalid.push('baseModels');
+ else {
+ out.baseModels = {};
+ for (const [key, value] of Object.entries(raw.baseModels).slice(
+ 0,
+ MAX_OVERRIDE_ENTRIES_PER_SECTION,
+ )) {
+ if (key && key.length <= 256 && validModelMetadata(value)) out.baseModels[key] = value;
+ else invalid.push(`baseModels:${key}`);
+ }
+ }
+ }
for (const section of ['additions', 'patches'] as const) {
const rawSection = raw[section];
if (rawSection === undefined) continue;
@@ -300,7 +353,7 @@ export function sanitizeModelCatalogOverrides(raw: unknown): SanitizeResult {
continue;
}
const agents = entryRootAgents(entry, parsed.providerId);
- if (agents.length === 0) {
+ if (section === 'additions' && agents.length === 0) {
invalid.push(`${section}:${key}`);
continue;
}
@@ -319,6 +372,16 @@ export function sanitizeModelCatalogOverrides(raw: unknown): SanitizeResult {
kept += 1;
}
}
+ if (raw.localModels !== undefined) {
+ if (
+ isPlainObject(raw.localModels) &&
+ Object.keys(raw.localModels).every((k) =>
+ ['featuredIds', 'patches', 'additions', 'removedIds'].includes(k),
+ )
+ )
+ out.localModels = raw.localModels as LocalModelCatalogOverrides;
+ else invalid.push('localModels');
+ }
return { overrides: out, invalid };
}
@@ -329,7 +392,11 @@ function entryMembershipAgents(
): RootAgentKind[] {
const policy = MODEL_PLANE_POLICIES.get(providerId);
if (!policy) return [];
- return entry.agents ?? [...new Set([...policy.roots, ...policy.membershipGatedBridges])];
+ return (
+ entry.agents?.filter((agent): agent is RootAgentKind => agent !== 'pi') ?? [
+ ...new Set([...policy.roots, ...policy.membershipGatedBridges]),
+ ]
+ );
}
/** entry 实际落实体的 roots;派生端只作为 membership,不接受直接写实体。 */
@@ -357,12 +424,13 @@ function overlayFields(model: CatalogModel, f: ModelCatalogOverrideFields): Cata
...(f.efforts !== undefined ? { efforts: f.efforts } : {}),
...(f.defaultEffort !== undefined ? { defaultEffort: f.defaultEffort } : {}),
...(f.supportsFastMode !== undefined ? { supportsFastMode: f.supportsFastMode } : {}),
+ ...(f.supportsImageInput !== undefined ? { supportsImageInput: f.supportsImageInput } : {}),
...(f.status !== undefined
? { status: f.status === 'preview' ? ('alpha' as const) : f.status }
: {}),
};
if (next.efforts.length === 0) next = { ...next, defaultEffort: null };
- else if (next.defaultEffort === null || !next.efforts.includes(next.defaultEffort)) {
+ else if (next.defaultEffort !== null && !next.efforts.includes(next.defaultEffort)) {
return 'local patch leaves defaultEffort outside effective efforts';
}
return next;
@@ -482,7 +550,7 @@ export function hasLocalAddition(
modelId: string,
agent: RootAgentKind,
): boolean {
- const entry = overrides.additions[`${providerId}:${modelId}`];
+ const entry = overrides.additions[`${encodeURIComponent(providerId)}:${modelId}`];
if (!entry) return false;
return entryRootAgents(entry, providerId).includes(agent);
}
@@ -494,9 +562,82 @@ export function hasLocalContextWindowOverride(
modelId: string,
agent: RootAgentKind,
): boolean {
- return (['additions', 'patches'] as const).some(section => {
- const entry = overrides[section][`${providerId}:${modelId}`];
- return entry && entryMembershipAgents(entry, providerId).includes(agent) &&
- effectiveFields(entry, agent).contextWindow !== undefined;
+ return (['additions', 'patches'] as const).some((section) => {
+ const entry = overrides[section][`${encodeURIComponent(providerId)}:${modelId}`];
+ return (
+ entry &&
+ entryMembershipAgents(entry, providerId).includes(agent) &&
+ effectiveFields(entry, agent).contextWindow !== undefined
+ );
});
}
+
+/** User patches affect existing members only, including XD, custom providers and Pi. */
+export function applyExistingModelLocalPatch(
+ providerId: string,
+ agent: AgentKind,
+ model: CatalogModel,
+ overrides: ModelCatalogOverrides,
+): CatalogModel {
+ const patch = overrides.patches[`${encodeURIComponent(providerId)}:${model.id}`];
+ if (!patch || (patch.agents && !patch.agents.includes(agent))) return model;
+ const result = overlayFields(model, { ...patch.base, ...patch.perAgent?.[agent] });
+ return typeof result === 'string'
+ ? model
+ : model.status === 'retired'
+ ? { ...result, status: 'retired' }
+ : result;
+}
+export function applyLocalModelCatalogOverrides(
+ base: LocalModelCatalog | undefined,
+ override: LocalModelCatalogOverrides | undefined,
+ baseModels?: readonly BaseModel[],
+): LocalModelCatalog | undefined {
+ if (!base || !override) return base;
+ const validRef = (model: LocalCatalogModel) =>
+ isPlainObject(model) &&
+ (model.modelRef === undefined ||
+ baseModels?.some((base) => base.id === model.modelRef) === true);
+ let models = base.models;
+ if (
+ Array.isArray(override.removedIds) &&
+ override.removedIds.every((id) => typeof id === 'string')
+ )
+ models = models.filter((model) => !override.removedIds!.includes(model.id));
+ if (isPlainObject(override.patches))
+ for (const [index, model] of models.entries()) {
+ const patch = override.patches?.[model.id];
+ if (!isPlainObject(patch)) continue;
+ const next = { ...model, ...patch, id: model.id };
+ const candidate = models.map((current, i) => (i === index ? next : current));
+ if (
+ validRef(next) &&
+ parseLocalModelCatalog({ version: 1, models: candidate, featuredIds: [] })
+ )
+ models = candidate;
+ }
+ if (Array.isArray(override.additions))
+ for (const model of override.additions) {
+ if (
+ !validRef(model) ||
+ !parseLocalModelCatalog({ version: 1, models: [model], featuredIds: [] })
+ )
+ continue;
+ const candidate = [...models.filter((m) => m.id !== model.id), model];
+ if (parseLocalModelCatalog({ version: 1, models: candidate, featuredIds: [] }))
+ models = candidate;
+ }
+ const ids = new Set(models.map((model) => model.id));
+ const featuredIds =
+ Array.isArray(override.featuredIds) &&
+ override.featuredIds.every((id) => typeof id === 'string' && ids.has(id))
+ ? override.featuredIds
+ : base.featuredIds.filter((id) => ids.has(id));
+ return (
+ parseLocalModelCatalog({ version: 1, models, featuredIds }) ?? {
+ version: 1,
+ models,
+ featuredIds: base.featuredIds.filter((id) => ids.has(id)),
+ }
+ );
+}
diff --git a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
index c3e71c3ad4..3cbd1fc481 100644
--- a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
@@ -1,3 +1,4 @@
+import { expandedRegistryEntries } from '@cindy/model-providers';
/**
* modelPlanePolicy —— 内置供应商模型平面的**表驱动 policy**(纯逻辑,零 IO)。
*
@@ -227,8 +228,8 @@ function effectiveRouteFields(
? candidateDefaultEffort !== undefined && VALID_EFFORTS.has(candidateDefaultEffort)
? (candidateDefaultEffort as Effort)
: undefined
- : (clampEffortToSupported(candidateDefaultEffort, validatedEfforts)
- ?? defaultEffortForCapabilities(validatedEfforts)) as Effort | null;
+ : ((clampEffortToSupported(candidateDefaultEffort, validatedEfforts) ??
+ defaultEffortForCapabilities(validatedEfforts)) as Effort | null);
return {
name: entry.name,
...(entry.group !== undefined ? { group: entry.group } : {}),
@@ -273,7 +274,7 @@ export function planRegistryRoots(registry: ModelRegistry | undefined): ModelPla
};
if (!registry) return plan;
const claimedRootRoutes = new Set<string>();
- for (const entry of registry.models) {
+ for (const entry of expandedRegistryEntries(registry)) {
const status = materializableStatus(entry.status);
for (const route of entry.routes) {
const policy = MODEL_PLANE_POLICIES.get(route.providerId);
@@ -519,10 +520,11 @@ function toMaterializedModel(
if (fields.efforts === undefined) {
return 'materializable route has no explicit efforts';
}
- const defaultEffort: Effort | null = fields.defaultEffort === null || fields.efforts.length === 0
- ? null
- : (clampEffortToSupported(fields.defaultEffort, fields.efforts)
- ?? defaultEffortForCapabilities(fields.efforts)) as Effort | null;
+ const defaultEffort: Effort | null =
+ fields.defaultEffort === null || fields.efforts.length === 0
+ ? null
+ : ((clampEffortToSupported(fields.defaultEffort, fields.efforts) ??
+ defaultEffortForCapabilities(fields.efforts)) as Effort | null);
return {
id: modelId,
name: fields.name,
diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
index 4442aea9ee..a62aaba24a 100644
--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
@@ -1,3 +1,4 @@
+import type { DiscoveredModel } from '@cindy/model-providers';
/**
* provider-model-fetch —— 供应商「获取模型列表」(自定义供应商表单消费)。
*
@@ -17,10 +18,7 @@ import {
type ProviderWireProtocol,
} from '@cindy/model-providers';
-import {
- classifyProviderError,
- type ProviderErrorCode,
-} from '../../shared/providerErrors.js';
+import { classifyProviderError, type ProviderErrorCode } from '../../shared/providerErrors.js';
import { deriveModelsDiscoveryUrl, parseModelsListResponse } from './generic-oauth.js';
import { outboundFetch } from './outbound-fetch.js';
@@ -56,7 +54,7 @@ export interface ProviderModelsFetchSpec {
export interface ProviderModelsFetchResult {
ok: boolean;
/** 拉到的模型清单(ok=true 时给出;已按 id 去重;contextWindow 为端点声明的上下文长度,尽力提取)。 */
- models?: { id: string; name: string; contextWindow?: number }[];
+ models?: DiscoveredModel[];
/** 失败分类码(ok=false 时给出)。 */
code?: ProviderErrorCode;
/** HTTP 状态码(网络层失败时缺省)。 */
@@ -98,7 +96,10 @@ function normalizedHeaders(headers: Record<string, string> | undefined): Record<
}
/** 构造列模型请求(纯函数,单测直断言)。鉴权头组合与 buildProbeRequest 同口径。 */
-export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: string; init: RequestInit } {
+export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): {
+ url: string;
+ init: RequestInit;
+} {
const baseUrl = parseModelsFetchUrl(spec.baseUrl);
const explicit = spec.modelsUrl?.trim();
const modelsUrl = explicit ? parseModelsFetchUrl(explicit) : null;
@@ -108,8 +109,8 @@ export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: s
? withoutCredentialHeaders(spec.headers)
: normalizedHeaders(spec.headers);
const anthropicMessages =
- spec.wireProtocol === 'anthropic-messages'
- || (spec.wireProtocol === undefined && spec.agent === 'claude-code');
+ spec.wireProtocol === 'anthropic-messages' ||
+ (spec.wireProtocol === undefined && spec.agent === 'claude-code');
if (anthropicMessages) {
// Anthropic wire 的所有端点(含 GET /v1/models)都要求 anthropic-version,缺失直接 400。
headers['anthropic-version'] = headers['anthropic-version'] ?? '2023-06-01';
@@ -125,7 +126,10 @@ export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: s
// modelsUrl 是用户不可见的隐藏字段(预设/配置快照)。只有与 baseUrl 同源才采用——
// 防止用户改了 baseUrl 后,key 仍被发往快照里的旧主机 / 被降级成明文(现有预设全部同源)。
return {
- url: explicit && modelsUrl?.origin === baseUrl.origin ? explicit : deriveModelsDiscoveryUrl(spec.baseUrl),
+ url:
+ explicit && modelsUrl?.origin === baseUrl.origin
+ ? explicit
+ : deriveModelsDiscoveryUrl(spec.baseUrl),
init: { method: 'GET', headers },
};
}
@@ -147,11 +151,9 @@ export async function fetchProviderModels(
fetchImpl: typeof fetch = outboundFetch,
): Promise<ProviderModelsFetchResult> {
if (
- spec.authMethod === 'none'
- && (
- !isLoopbackProviderUrl(spec.baseUrl)
- || (!!spec.modelsUrl?.trim() && !isLoopbackProviderUrl(spec.modelsUrl.trim()))
- )
+ spec.authMethod === 'none' &&
+ (!isLoopbackProviderUrl(spec.baseUrl) ||
+ (!!spec.modelsUrl?.trim() && !isLoopbackProviderUrl(spec.modelsUrl.trim())))
) {
return {
ok: false,
@@ -187,12 +189,22 @@ export async function fetchProviderModels(
try {
json = await res.json();
} catch {
- return { ok: false, code: 'UNKNOWN', status: res.status, detail: 'models response is not JSON' };
+ return {
+ ok: false,
+ code: 'UNKNOWN',
+ status: res.status,
+ detail: 'models response is not JSON',
+ };
}
const models = parseModelsListResponse(json);
if (!models || models.length === 0) {
// 端点 200 但响应不是可识别的模型列表(或为空)——按「模型不存在」类引导用户手填。
- return { ok: false, code: 'UNKNOWN', status: res.status, detail: 'no models found in response' };
+ return {
+ ok: false,
+ code: 'UNKNOWN',
+ status: res.status,
+ detail: 'no models found in response',
+ };
}
return { ok: true, models };
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index d2dae40334..cb14290ffb 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1149,8 +1149,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 意识仓库 (shared/ghost.ts)。listSync 走 sendSync:意识面板要与内置
// 面板同帧注册进布局引擎(规则 7 无跳变);目录扫描极小,同步读不卡启动。
ghosts: {
- recommendationsSync: (): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>
- ipcRenderer.sendSync('ghosts:recommendations'),
+ recommendationsSync:
+ (): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>
+ ipcRenderer.sendSync('ghosts:recommendations'),
listSync: (): { ghosts: unknown[] } => ipcRenderer.sendSync('ghosts:list'),
recentUsageSync: (): { ids: string[] } => {
try {
@@ -5601,7 +5602,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
savedProviderId?: string;
}): Promise<{
ok: boolean;
- models?: { id: string; name: string; contextWindow?: number }[];
+ models?: import('@cindy/model-providers').DiscoveredModel[];
code?: import('../shared/providerErrors').ProviderErrorCode;
status?: number;
detail?: string;
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
index cfdab4faff..b612044a24 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
@@ -13,7 +13,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/re
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { ProviderView } from '@cindy/model-providers';
+import { buildUserProvider, BUNDLED_CATALOG, type ProviderView } from '@cindy/model-providers';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }),
@@ -376,7 +376,7 @@ describe('AddProviderWizard — preset 直达', () => {
).toBe(false);
});
- it('官方 API 预设:完成保存 → 模型带目录口径 contextWindow(Codex P1 回归)', async () => {
+ it('官方 API 预设保存引用,解析后继承目录窗口', async () => {
render(
React.createElement(AddProviderWizard, {
providers: [anthropicProvider],
@@ -396,16 +396,15 @@ describe('AddProviderWizard — preset 直达', () => {
await waitFor(() => expect(screen.getByText('Claude Opus 5')).not.toBeNull());
fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
- // 保存产物必须带预设声明的 contextWindow:它是唯一窗口来源,缺省会落
- // 200k 默认导致 1M 模型丢 [1m] 路由(toSdkModelString 按窗口剥后缀)。
+ // 默认资料保持继承;保存引用后仍解析出目录窗口。
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
const config = vi.mocked(createCustomProvider).mock.calls[0][0];
const models = config.runtimes['claude-code']?.models ?? [];
expect(models).toEqual(
expect.arrayContaining([
- expect.objectContaining({ id: 'claude-opus-5', contextWindow: 1_000_000 }),
- expect.objectContaining({ id: 'claude-sonnet-5', contextWindow: 1_000_000 }),
- expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),
+ expect.objectContaining({ id: 'claude-opus-5', discoveredMetadata: {} }),
+ expect.objectContaining({ id: 'claude-sonnet-5', discoveredMetadata: {} }),
+ expect.objectContaining({ id: 'claude-haiku-4-5', discoveredMetadata: {} }),
]),
);
const codex = config.runtimes.codex;
@@ -413,26 +412,41 @@ describe('AddProviderWizard — preset 直达', () => {
expect(codex?.baseUrl).toBe('https://api.anthropic.com');
expect(codex?.models).toEqual(
expect.arrayContaining([
- expect.objectContaining({ id: 'claude-opus-5', contextWindow: 1_000_000 }),
- expect.objectContaining({ id: 'claude-sonnet-5', contextWindow: 1_000_000 }),
- expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),
+ expect.objectContaining({ id: 'claude-opus-5', discoveredMetadata: {} }),
+ expect.objectContaining({ id: 'claude-sonnet-5', discoveredMetadata: {} }),
+ expect.objectContaining({ id: 'claude-haiku-4-5', discoveredMetadata: {} }),
]),
);
const keys = vi.mocked(createCustomProvider).mock.calls[0][1];
expect(keys).toMatchObject({ 'claude-code': 'sk-test', codex: 'sk-test' });
expect(config.runtimes.pi).toEqual({
+ catalogPresetId: 'anthropic-api',
baseUrl: 'https://api.anthropic.com',
wireProtocol: 'anthropic-messages',
models: expect.arrayContaining([
- expect.objectContaining({ id: 'claude-opus-5', contextWindow: 1_000_000 }),
- expect.objectContaining({ id: 'claude-sonnet-5', contextWindow: 1_000_000 }),
- expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),
+ expect.objectContaining({ id: 'claude-opus-5', discoveredMetadata: {} }),
+ expect.objectContaining({ id: 'claude-sonnet-5', discoveredMetadata: {} }),
+ expect.objectContaining({ id: 'claude-haiku-4-5', discoveredMetadata: {} }),
]),
});
expect(keys.pi).toBe('sk-test');
+ const { presets } = await window.electronAPI.maker.listProviderPresets();
+ const projected = buildUserProvider(config, {
+ presets,
+ modelRegistry: BUNDLED_CATALOG.modelRegistry,
+ });
+ expect(projected.models['claude-code']).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'claude-opus-5', contextWindow: 1_000_000 }),
+ expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),
+ ]),
+ );
+ expect(
+ config.runtimes['claude-code']?.models.every((model) => model.contextWindow === undefined),
+ ).toBe(true);
});
- it('Pi 预设保存时保留显式 reasoning 能力与支持档位', async () => {
+ it('Pi 预设通过引用继承 reasoning 能力与支持档位', async () => {
renderWizard('pi-reasoning');
await waitFor(() => expect(screen.getByDisplayValue('Pi Reasoning')).not.toBeNull());
@@ -445,11 +459,16 @@ describe('AddProviderWizard — preset 直达', () => {
expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.pi?.models).toEqual([
expect.objectContaining({
id: 'reasoning-model',
- reasoning: true,
- reasoningEfforts: ['low', 'high'],
- reasoningDefaultEffort: 'high',
+ discoveredMetadata: {},
}),
]);
+ const config = vi.mocked(createCustomProvider).mock.calls[0][0];
+ const { presets } = await window.electronAPI.maker.listProviderPresets();
+ expect(config.runtimes.pi?.catalogPresetId).toBe('pi-reasoning');
+ expect(buildUserProvider(config, { presets }).models.pi?.[0]).toMatchObject({
+ efforts: ['low', 'high'],
+ defaultEffort: 'high',
+ });
});
it('预设已有显式 Pi runtime 时不被 Claude 自动初始化覆盖', async () => {
@@ -464,9 +483,10 @@ describe('AddProviderWizard — preset 直达', () => {
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];
expect(config.runtimes.pi).toEqual({
+ catalogPresetId: 'explicit-pi',
baseUrl: 'https://explicit.example/pi',
wireProtocol: 'openai-chat',
- models: [{ id: 'pi-model', name: 'Pi Model' }],
+ models: [{ id: 'pi-model', name: 'Pi Model', discoveredMetadata: {} }],
});
expect(keys.pi).toBe('sk-test');
});
@@ -484,8 +504,9 @@ describe('AddProviderWizard — preset 直达', () => {
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];
expect(config.runtimes['claude-code']).toEqual({
+ catalogPresetId: 'explicit-pi',
baseUrl: 'https://explicit.example/anthropic',
- models: [{ id: 'claude-model', name: 'Claude Model' }],
+ models: [{ id: 'claude-model', name: 'Claude Model', discoveredMetadata: {} }],
});
expect(config.runtimes.pi).toBeUndefined();
expect(keys.pi).toBeUndefined();
@@ -521,7 +542,7 @@ describe('AddProviderWizard — preset 直达', () => {
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];
expect(config.runtimes['claude-code']?.models).toEqual([
- { id: 'claude-only-model', name: 'Claude Only Model' },
+ { id: 'claude-only-model', name: 'Claude Only Model', discoveredMetadata: {} },
]);
expect(config.runtimes.pi).toBeUndefined();
expect(keys.pi).toBeUndefined();
@@ -602,7 +623,7 @@ describe('AddProviderWizard — preset 直达', () => {
codex: expect.objectContaining({
baseUrl: 'http://localhost:4100/v1',
requestPath: '/tenant/acme/infer',
- models: [{ id: 'local-model', name: 'local-model' }],
+ models: [{ id: 'local-model', name: 'local-model', discoveredMetadata: {} }],
}),
},
}),
@@ -628,7 +649,7 @@ describe('AddProviderWizard — preset 直达', () => {
ok: true,
models: [
{ id: 'minimax-m3', name: 'MiniMax M3' },
- { id: 'glm-5.2', name: 'GLM-5.2' },
+ { id: 'glm-5.2', name: 'GLM-5.2', discoveredMetadata: {} },
],
});
renderWizard('opencode-go');
@@ -666,7 +687,10 @@ describe('AddProviderWizard — preset 直达', () => {
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
const config = vi.mocked(createCustomProvider).mock.calls[0][0];
expect(config.runtimes['claude-code']?.models).toEqual([
- expect.objectContaining({ id: 'deepseek-v4', contextWindow: 262_144 }),
+ expect.objectContaining({
+ id: 'deepseek-v4',
+ discoveredMetadata: expect.objectContaining({ contextWindow: 262_144 }),
+ }),
]);
});
@@ -698,10 +722,16 @@ describe('AddProviderWizard — preset 直达', () => {
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
const config = vi.mocked(createCustomProvider).mock.calls[0][0];
expect(config.runtimes['claude-code']?.models).toEqual([
- expect.objectContaining({ id: 'shared-model', contextWindow: 1_000_000 }),
+ expect.objectContaining({
+ id: 'shared-model',
+ discoveredMetadata: expect.objectContaining({ contextWindow: 1_000_000 }),
+ }),
]);
expect(config.runtimes.codex?.models).toEqual([
- expect.objectContaining({ id: 'shared-model', contextWindow: 272_000 }),
+ expect.objectContaining({
+ id: 'shared-model',
+ discoveredMetadata: expect.objectContaining({ contextWindow: 272_000 }),
+ }),
]);
});
@@ -710,7 +740,7 @@ describe('AddProviderWizard — preset 直达', () => {
async ({ baseUrl }: { baseUrl: string }) =>
baseUrl === 'https://open.bigmodel.cn/api/v1'
? { ok: true, models: [{ id: 'glm-5.3', name: 'GLM-5.3' }] }
- : { ok: true, models: [{ id: 'glm-5.2', name: 'GLM-5.2' }] },
+ : { ok: true, models: [{ id: 'glm-5.2', name: 'GLM-5.2', discoveredMetadata: {} }] },
);
renderWizard('zhipu-coding-plan-cn');
@@ -742,7 +772,7 @@ describe('AddProviderWizard — preset 直达', () => {
baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
wireProtocol: 'openai-chat',
models: [
- { id: 'glm-5.2', name: 'GLM-5.2' },
+ { id: 'glm-5.2', name: 'GLM-5.2', discoveredMetadata: {} },
{
id: 'glm-5.3',
name: 'GLM-5.3',
@@ -763,7 +793,7 @@ describe('AddProviderWizard — preset 直达', () => {
? {
ok: true,
models: [
- { id: 'glm-5.2', name: 'GLM-5.2' },
+ { id: 'glm-5.2', name: 'GLM-5.2', discoveredMetadata: {} },
{ id: 'glm-5.3', name: 'GLM-5.3' },
],
}
@@ -783,7 +813,7 @@ describe('AddProviderWizard — preset 直达', () => {
baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
wireProtocol: 'openai-chat',
});
- expect(runtime?.models).toEqual([{ id: 'glm-5.2', name: 'GLM-5.2' }]);
+ expect(runtime?.models).toEqual([{ id: 'glm-5.2', name: 'GLM-5.2', discoveredMetadata: {} }]);
});
it('可编辑预设改为同源 endpoint 后继续合并 Responses 目录', async () => {
@@ -791,7 +821,10 @@ describe('AddProviderWizard — preset 直达', () => {
async ({ baseUrl }: { baseUrl: string }) =>
baseUrl === 'https://editable.example/api/v1'
? { ok: true, models: [{ id: 'responses-model', name: 'Responses Model' }] }
- : { ok: true, models: [{ id: 'chat-model', name: 'Chat Model' }] },
+ : {
+ ok: true,
+ models: [{ id: 'chat-model', name: 'Chat Model', discoveredMetadata: {} }],
+ },
);
renderWizard('editable-discovery');
@@ -818,8 +851,9 @@ describe('AddProviderWizard — preset 直达', () => {
}),
);
expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex?.models).toEqual([
- { id: 'chat-model', name: 'Chat Model' },
+ { id: 'chat-model', name: 'Chat Model', discoveredMetadata: {} },
{
+ discoveredMetadata: { name: 'Responses Model' },
id: 'responses-model',
name: 'Responses Model',
route: {
@@ -858,7 +892,7 @@ describe('AddProviderWizard — preset 直达', () => {
expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex).toMatchObject({
baseUrl: 'https://self-hosted.example/v4',
models: [
- { id: 'chat-model', name: 'Chat Model' },
+ { id: 'chat-model', name: 'Chat Model', discoveredMetadata: {} },
{ id: 'self-hosted-model', name: 'Self-hosted Model' },
],
});
diff --git a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx
index 1200e1a0a6..104c3393c4 100644
--- a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx
@@ -355,6 +355,8 @@ describe('CustomProviderDialog preset locale ownership', () => {
await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex?.models[0]).toEqual({
+ discoveredMetadata: {},
+ nameExplicit: false,
id: 'local-model',
name: 'Local Model',
route: {
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index 11863acb87..dddf617222 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -401,8 +401,11 @@ export function AddProviderWizard({
recommended: boolean;
agents: AgentKind[];
/** 列模型端点上报的上下文窗口,**按 agent 分槽**(同一 id 双端可不同,如
- * cc=1M / codex=272K);完成创建时按所属 runtime 取值,预设值优先、本值兜底。 */
+ * cc=1M / codex=272K);完成创建时按所属 runtime 取值,作为供应商事实单独保存。 */
contextWindows?: Partial<Record<AgentKind, number>>;
+ discoveredMetadata?: Partial<
+ Record<AgentKind, import('@cindy/model-providers').ModelMetadata>
+ >;
/** 附加目录发现出的模型级路由;主 runtime 目录发现的模型保持缺省路由。 */
routes?: Partial<Record<AgentKind, ProviderModelRouteConfig>>;
}
@@ -546,9 +549,7 @@ export function AddProviderWizard({
);
const recommendsOllama = recommendations.some((item) => item.kind === 'ollama');
const ollamaMatchesQuery =
- !q ||
- t('settings.providers.local.title').toLowerCase().includes(q) ||
- 'ollama'.includes(q);
+ !q || t('settings.providers.local.title').toLowerCase().includes(q) || 'ollama'.includes(q);
const showOllamaInList =
!ollamaAlreadyAdded &&
ollamaMatchesQuery &&
@@ -806,6 +807,9 @@ export function AddProviderWizard({
recommended: boolean;
agents: AgentKind[];
contextWindows?: Partial<Record<AgentKind, number>>;
+ discoveredMetadata?: Partial<
+ Record<AgentKind, import('@cindy/model-providers').ModelMetadata>
+ >;
routes?: Partial<Record<AgentKind, ProviderModelRouteConfig>>;
}
>();
@@ -914,7 +918,7 @@ export function AddProviderWizard({
modelsUrl: source.modelsUrl,
route: source.route,
ok: false,
- models: [] as { id: string; name: string; contextWindow?: number }[],
+ models: [] as import('@cindy/model-providers').DiscoveredModel[],
};
}
});
@@ -952,10 +956,22 @@ export function AddProviderWizard({
!existing.routes?.[agent]
? route
: undefined;
- if (mergedAgents !== existing.agents || backfillWindow || discoveredRoute) {
+ if (
+ mergedAgents !== existing.agents ||
+ backfillWindow ||
+ discoveredRoute ||
+ m.discoveredMetadata
+ ) {
next.set(m.id, {
...existing,
agents: mergedAgents,
+ discoveredMetadata: {
+ ...existing.discoveredMetadata,
+ [agent]: m.discoveredMetadata ?? {
+ name: m.name,
+ ...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
+ },
+ },
...(backfillWindow
? { contextWindows: { ...existing.contextWindows, [agent]: m.contextWindow } }
: {}),
@@ -970,6 +986,12 @@ export function AddProviderWizard({
checked: false,
recommended: false,
agents: [agent],
+ discoveredMetadata: {
+ [agent]: m.discoveredMetadata ?? {
+ name: m.name,
+ ...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
+ },
+ },
...(m.contextWindow !== undefined
? { contextWindows: { [agent]: m.contextWindow } }
: {}),
@@ -1065,6 +1087,7 @@ export function AddProviderWizard({
name: v.name,
agents: v.agents,
contextWindows: v.contextWindows,
+ discoveredMetadata: v.discoveredMetadata,
routes: v.routes,
}));
if (selected.length === 0) {
@@ -1096,31 +1119,21 @@ export function AddProviderWizard({
.filter((m) => m.agents.includes(agent))
.map((m) => {
const presetModel = rt.models.find((candidate) => candidate.id === m.id);
- // 预设策展值优先;拉取新增模型没有预设条目,落**该 runtime 端点**上报的
- // 发现值(按 agent 分槽,双端窗口可不同),不再无窗口入库退回 200K 默认。
- const contextWindow = presetModel?.contextWindow ?? m.contextWindows?.[agent];
+ // Only interface facts belong to discovery. Preset defaults follow a live reference.
+ const discoveredMetadata = m.discoveredMetadata?.[agent] ?? {};
return {
id: m.id,
name: m.name,
+ discoveredMetadata,
...(agent === 'pi' && presetModel?.piApi ? { piApi: presetModel.piApi } : {}),
...((presetModel?.route ?? m.routes?.[agent])
? { route: presetModel?.route ?? m.routes?.[agent] }
: {}),
- ...(contextWindow !== undefined ? { contextWindow } : {}),
- ...(presetModel?.supportsImageInput === true ? { supportsImageInput: true } : {}),
- ...(presetModel?.reasoning === true && presetModel.reasoningEfforts?.length
- ? {
- reasoning: true,
- reasoningEfforts: [...presetModel.reasoningEfforts],
- ...(presetModel.reasoningDefaultEffort
- ? { reasoningDefaultEffort: presetModel.reasoningDefaultEffort }
- : {}),
- }
- : {}),
};
});
if (agentModels.length === 0) continue;
runtimes[agent] = {
+ catalogPresetId: preset.id,
baseUrl: presetRuntimeBaseUrl(preset, agent, presetBaseUrls),
...(rt.wireProtocol ? { wireProtocol: rt.wireProtocol } : {}),
...(rt.requestPath ? { requestPath: rt.requestPath } : {}),
@@ -1537,10 +1550,7 @@ export function AddProviderWizard({
>
{t('settings.providers.local.onboardingTitle')}
</span>
- <LocalOllamaInstall
- canInstall={ollamaCanInstall}
- onReady={() => connectOllama()}
- />
+ <LocalOllamaInstall canInstall={ollamaCanInstall} onReady={() => connectOllama()} />
</div>
)}
{step === 2 && sel?.kind === 'oauth' && (
diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
index 3de9e3c6ba..7f358a2c1f 100644
--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
@@ -209,6 +209,7 @@ interface RuntimeFields extends RuntimeFillDraft {
modelsUrl: string;
/** 隐藏字段:从 Pi 官方目录生成该 runtime;编辑保存必须无损保留。 */
piCatalogProviderId?: string;
+ catalogPresetId?: string;
/** Codex Responses runtime 级原生图片生成能力。 */
supportsImageGeneration: boolean;
}
@@ -283,6 +284,7 @@ function initRuntimes(initial?: CustomProviderConfig): Record<DialogAgentKind, R
: [{ name: '', value: '' }],
modelsUrl: rc.modelsUrl ?? '',
piCatalogProviderId: rc.piCatalogProviderId,
+ catalogPresetId: rc.catalogPresetId,
supportsImageGeneration: a === 'codex' && rc.supportsImageGeneration === true,
headersState: rc.headersState,
});
@@ -309,7 +311,10 @@ function isCommittableWindowText(text: string): boolean {
}
/** Compact context-window label shown inside the existing token-count input. */
-function compactContextWindowLabel(draft: string | undefined, contextWindow?: number): string | null {
+function compactContextWindowLabel(
+ draft: string | undefined,
+ contextWindow?: number,
+): string | null {
if (draft !== undefined) {
if (!isCommittableWindowText(draft) || !draft.trim()) return null;
const value = Number(BigInt(draft.trim().replace(/[,_ ]/g, '')));
@@ -975,13 +980,22 @@ export function CustomProviderDialog({
requestPath: a === 'pi' ? '' : (rc.requestPath ?? ''),
apiKey: prev[a].apiKey, // 已填的 key 保留
wireProtocol: rc.wireProtocol ?? defaultWireFor(a),
- models: rc.models.length ? rc.models.map((m) => ({ ...m })) : [{ id: '', name: '' }],
+ models: rc.models.length
+ ? rc.models.map((m) => ({
+ id: m.id,
+ name: m.name,
+ discoveredMetadata: {},
+ ...(m.piApi ? { piApi: m.piApi } : {}),
+ ...(m.route ? { route: m.route } : {}),
+ }))
+ : [{ id: '', name: '' }],
headers:
rc.headers && Object.keys(rc.headers).length > 0
? Object.entries(rc.headers).map(([n, v]) => ({ name: n, value: v }))
: [{ name: '', value: '' }],
modelsUrl: rc.modelsUrl ?? '',
piCatalogProviderId: rc.piCatalogProviderId,
+ catalogPresetId: p.id,
supportsImageGeneration: a === 'codex' && rc.supportsImageGeneration === true,
};
}
@@ -1478,15 +1492,19 @@ export function CustomProviderDialog({
.map((m) => ({
id: m.id.trim(),
name: m.name.trim(),
+ discoveredMetadata: m.discoveredMetadata,
+ nameExplicit: m.nameExplicit,
...(agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.route ? { route: { ...m.route } } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
- ...(m.reasoning === true && m.reasoningEfforts?.length
+ ...(m.supportsImageInput !== undefined
+ ? { supportsImageInput: m.supportsImageInput }
+ : {}),
+ ...(m.reasoning !== undefined
? {
- reasoning: true,
- reasoningEfforts: [...m.reasoningEfforts],
+ reasoning: m.reasoning,
+ reasoningEfforts: [...(m.reasoningEfforts ?? [])],
...(m.reasoningDefaultEffort
? { reasoningDefaultEffort: m.reasoningDefaultEffort }
: {}),
@@ -1506,19 +1524,23 @@ export function CustomProviderDialog({
// contextWindow:表单已有的行以用户当前值为准——包括「显式清空」
// (cur 存在但无值时不得被发现值回填,review P1);只有表单没见过的
// 新模型才带上端点声明的发现值(否则保存后回落 200K,review P1)。
- const contextWindow = cur ? cur.contextWindow : m.contextWindow;
+ const contextWindow = cur?.contextWindow;
return {
id: m.id,
name: cur?.name || m.name,
+ discoveredMetadata: m.discoveredMetadata ?? { contextWindow: m.contextWindow },
+ nameExplicit: cur ? (cur.nameExplicit ?? !cur.discoveredMetadata) : undefined,
...(agent === 'pi' && cur?.piApi ? { piApi: cur.piApi } : {}),
...(cur?.route ? { route: { ...cur.route } } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(cur?.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(cur?.supportsImageInput === true ? { supportsImageInput: true } : {}),
- ...(cur?.reasoning === true && cur.reasoningEfforts?.length
+ ...(cur?.supportsImageInput !== undefined
+ ? { supportsImageInput: cur.supportsImageInput }
+ : {}),
+ ...(cur?.reasoning !== undefined
? {
- reasoning: true,
- reasoningEfforts: [...cur.reasoningEfforts],
+ reasoning: cur.reasoning,
+ reasoningEfforts: [...(cur.reasoningEfforts ?? [])],
...(cur.reasoningDefaultEffort
? { reasoningDefaultEffort: cur.reasoningDefaultEffort }
: {}),
@@ -1589,15 +1611,17 @@ export function CustomProviderDialog({
return {
id: m.id,
name: latest?.name.trim() ? latest.name.trim() : m.name,
+ discoveredMetadata: m.discoveredMetadata ?? latest?.discoveredMetadata,
+ nameExplicit: latest?.nameExplicit ?? m.nameExplicit,
...(picker.agent === 'pi' && piApi ? { piApi } : {}),
...((latest?.route ?? m.route) ? { route: { ...(latest?.route ?? m.route)! } } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(supportsImageInput === true ? { supportsImageInput: true } : {}),
- ...(reasoning === true && reasoningEfforts?.length
+ ...(supportsImageInput !== undefined ? { supportsImageInput } : {}),
+ ...(reasoning !== undefined
? {
- reasoning: true,
- reasoningEfforts: [...reasoningEfforts],
+ reasoning,
+ reasoningEfforts: [...(reasoningEfforts ?? [])],
...(reasoningDefaultEffort ? { reasoningDefaultEffort } : {}),
}
: {}),
@@ -1609,15 +1633,19 @@ export function CustomProviderDialog({
merged.push({
id,
name: m.name.trim() || id,
+ discoveredMetadata: m.discoveredMetadata,
+ nameExplicit: m.nameExplicit,
...(picker.agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.route ? { route: { ...m.route } } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
- ...(m.reasoning === true && m.reasoningEfforts?.length
+ ...(m.supportsImageInput !== undefined
+ ? { supportsImageInput: m.supportsImageInput }
+ : {}),
+ ...(m.reasoning !== undefined
? {
- reasoning: true,
- reasoningEfforts: [...m.reasoningEfforts],
+ reasoning: m.reasoning,
+ reasoningEfforts: [...(m.reasoningEfforts ?? [])],
...(m.reasoningDefaultEffort
? { reasoningDefaultEffort: m.reasoningDefaultEffort }
: {}),
@@ -1745,15 +1773,19 @@ export function CustomProviderDialog({
.map((m) => ({
id: m.id.trim(),
name: m.name.trim(),
+ discoveredMetadata: m.discoveredMetadata,
+ nameExplicit: m.nameExplicit,
...(a === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.route ? { route: { ...m.route } } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
- ...(m.reasoning === true && m.reasoningEfforts?.length
+ ...(m.supportsImageInput !== undefined
+ ? { supportsImageInput: m.supportsImageInput }
+ : {}),
+ ...(m.reasoning !== undefined
? {
- reasoning: true,
- reasoningEfforts: [...m.reasoningEfforts],
+ reasoning: m.reasoning,
+ reasoningEfforts: [...(m.reasoningEfforts ?? [])],
...(m.reasoningDefaultEffort
? { reasoningDefaultEffort: m.reasoningDefaultEffort }
: {}),
@@ -1787,6 +1819,7 @@ export function CustomProviderDialog({
);
runtimes[a] = {
baseUrl: rf.baseUrl.trim(),
+ ...(rf.catalogPresetId ? { catalogPresetId: rf.catalogPresetId } : {}),
...(requestPath ? { requestPath } : {}),
...(savedWireProtocol ? { wireProtocol: savedWireProtocol } : {}),
...(a === 'codex' && rf.supportsImageGeneration && canRuntimeUseNativeImageGeneration(rf)
@@ -2500,7 +2533,9 @@ export function CustomProviderDialog({
onChange={(v) =>
patch(activeTab, (x) => ({
...x,
- models: x.models.map((y, j) => (j === i ? { ...y, name: v } : y)),
+ models: x.models.map((y, j) =>
+ j === i ? { ...y, name: v, nameExplicit: true } : y,
+ ),
}))
}
placeholder={t('settings.providers.custom.fields.modelNamePlaceholder')}
@@ -2789,7 +2824,9 @@ export function CustomProviderDialog({
onChange={(v) =>
patch(activeTab, (x) => ({
...x,
- headers: x.headers.map((y, j) => (j === i ? { ...y, name: v } : y)),
+ headers: x.headers.map((y, j) =>
+ j === i ? { ...y, name: v, nameExplicit: true } : y,
+ ),
}))
}
placeholder={t('settings.providers.custom.fields.headerNamePlaceholder')}
diff --git a/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx b/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx
index 226ce79ec9..7ae3a44ca0 100644
--- a/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx
+++ b/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx
@@ -53,15 +53,10 @@ function IconAction({
);
}
-function PullMeter({
- pull,
-}: {
- pull: LocalModelPullProgress;
-}) {
+function PullMeter({ pull }: { pull: LocalModelPullProgress }) {
const { t } = useTranslation();
const pullPhase = (pull.phase ?? 'starting') as LocalModelPullPhase;
- const errorKind =
- pull.phase === 'error' ? classifyOllamaPullError(pull.error, pull.name) : null;
+ const errorKind = pull.phase === 'error' ? classifyOllamaPullError(pull.error, pull.name) : null;
return (
<DownloadMeter
progress={{
@@ -117,7 +112,7 @@ function PullActions({
}
export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const [status, setStatus] = useState<LocalRuntimeStatus | null>(null);
const [models, setModels] = useState<LocalInstalledModel[]>([]);
const [catalog, setCatalog] = useState<CuratedOllamaModel[]>([]);
@@ -171,6 +166,9 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
useEffect(() => {
void refresh().catch(() => undefined);
+ const offCatalog = window.electronAPI.maker.onProvidersChanged(() => {
+ void refresh().catch(() => undefined);
+ });
const offStatus = window.electronAPI.maker.onLocalModelStatus((next) => {
setStatus(next as LocalRuntimeStatus);
});
@@ -178,6 +176,7 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
upsertPull(next as LocalModelPullProgress);
});
return () => {
+ offCatalog();
offStatus();
offPull();
};
@@ -328,7 +327,13 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
)}
</div>
<span className="text-12 leading-snug" style={{ color: 'var(--text-secondary)' }}>
- {t(`settings.providers.local.models.${entry.id}.blurb`)}
+ {entry.descriptions?.[
+ (i18n.resolvedLanguage ?? i18n.language) as keyof NonNullable<
+ typeof entry.descriptions
+ >
+ ] ??
+ entry.descriptions?.en ??
+ ''}
</span>
<span className="text-11" style={{ color: 'var(--text-tertiary)' }}>
{t(
@@ -435,7 +440,11 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
: t('settings.providers.local.hostProfileUnknown')}
</span>
<span className="text-12 leading-snug" style={{ color: 'var(--text-secondary)' }}>
- {t(`settings.providers.local.recommendReason.${recommendReason}`)}
+ {t(
+ featured.length > 0
+ ? `settings.providers.local.recommendReason.${recommendReason}`
+ : 'settings.providers.local.noRecommendation',
+ )}
</span>
</>
)}
@@ -453,7 +462,7 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
color: 'var(--settings-section-title)',
}}
/>
- {visibleCatalog.length === 0 && (
+ {searching && visibleCatalog.length === 0 && (
<span className="text-12" style={{ color: 'var(--text-tertiary)' }}>
{t('settings.providers.local.noSearchResults')}
</span>
@@ -513,7 +522,10 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
}}
>
<div className="flex items-start justify-between gap-3">
- <span className="min-w-0 truncate text-14 font-medium" style={{ color: 'var(--settings-section-title)' }}>
+ <span
+ className="min-w-0 truncate text-14 font-medium"
+ style={{ color: 'var(--settings-section-title)' }}
+ >
{t('settings.providers.local.pullingTitle', { name: customPull.name })}
</span>
<PullActions
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 1aeb2301d5..802fe5a596 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -2517,8 +2517,8 @@ export function ProvidersSection() {
toast.error(t('settings.providers.models.refreshFailed'));
return;
}
+ await updateCustomProvider(config, {});
if (added > 0) {
- await updateCustomProvider(config, {});
toast.success(t('settings.providers.models.refreshAdded', { count: added }));
} else {
toast.success(t('settings.providers.models.refreshNoNew'));
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 648cabb596..debdee9e00 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2010,8 +2010,8 @@
"hostProfileApple": "Apple silicon · about {{memory}} GB unified memory",
"hostProfileGeneric": "About {{memory}} GB memory",
"hostProfileUnknown": "This computer’s memory isn’t available yet",
- "bestForYou": "Best for you",
- "alsoCoding": "Also good for coding",
+ "bestForYou": "Capability pick",
+ "alsoCoding": "Speed alternative",
"packaging": {
"mxfp8": "MXFP8",
"mlx": "MLX",
@@ -2028,41 +2028,12 @@
"noSearchResults": "No matching models",
"alreadyInstalled": "Installed",
"searchResults": "Search results",
- "moreModels": "More local models",
- "memoryWarning": "Not enough memory on this computer (needs {{need}} GB, about {{have}} GB available)",
+ "moreModels": "Other candidate models",
+ "memoryWarning": "Below the estimated memory threshold ({{need}} GB; this computer has about {{have}} GB)",
"manualDownload": "Manual download",
"manualDownloadPlaceholder": "Ollama library name or Hugging Face URL",
"invalidLibraryName": "Enter an Ollama library name, or paste a huggingface.co model page URL",
"advancedExactName": "Advanced: exact library name",
- "models": {
- "qwen38-27b": {
- "blurb": "The strongest dense model you can run locally. Best for coding and long tasks."
- },
- "gpt-oss-20b": {
- "blurb": "OpenAI’s open 20B. The usual pick for 16 GB machines."
- },
- "gemma4-e2b": {
- "blurb": "Smallest Gemma 4. Light machines, with vision."
- },
- "gemma4-e4b": {
- "blurb": "Google Gemma 4 small. Light daily use, with vision."
- },
- "gemma4-12b": {
- "blurb": "Gemma 4 mid-size. Steadier chat and multimodal."
- },
- "gemma4-31b": {
- "blurb": "Gemma 4 large. Stronger chat and multimodal, more memory."
- },
- "gemma4-26b": {
- "blurb": "Gemma 4 mid-large MoE. Fewer active parameters, mid-to-high-end machines."
- },
- "ornith15-35b": {
- "blurb": "Ornith 1.5 mid-size MoE. The local coding and agent backup."
- },
- "glm-47-flash": {
- "blurb": "Zhipu’s current coding model. 30B MoE, good for code and agents."
- }
- },
"onboardingTitle": "Install the Ollama runtime",
"onboardingBody": "After you install Ollama, you can download and use local models in Cindy without opening the Ollama app. Ollama is a free, open-source third-party runtime.",
"installInCindy": "Install in Cindy",
@@ -2131,8 +2102,8 @@
"cancelDownload": "Delete Incomplete Download",
"notRecommended": "This Mac doesn’t meet the 32 GB memory bar for Qwen3.8 27B. You can still enter an exact library name.",
"sizeHint": "About {{size}} · needs {{memory}} GB unified memory",
- "sizeHintApple": "About {{size}} · needs {{memory}} GB unified memory",
- "sizeHintGeneric": "About {{size}} · needs {{memory}} GB memory",
+ "sizeHintApple": "Download {{size}} · estimated {{memory}} GB unified memory",
+ "sizeHintGeneric": "Download {{size}} · estimated {{memory}} GB memory",
"deleteFromCindy": "Remove from Cindy",
"deleteConfirmTitle": "Remove Ollama from Cindy?",
"deleteConfirmBody": "This only removes the Cindy connection. Models already downloaded in Ollama stay on disk, and the service keeps running.",
@@ -2141,7 +2112,8 @@
"deleteModelConfirmBody": "This deletes the downloaded model files from this computer and removes them from Cindy. You can download the model again later.",
"deleteModelConfirm": "Delete",
"deleteModelDone": "Deleted {{name}}",
- "deleteModelFailed": "Couldn’t delete the model. Make sure Ollama is running, then try again."
+ "deleteModelFailed": "Couldn’t delete the model. Make sure Ollama is running, then try again.",
+ "noRecommendation": "No recommendation with sufficient evidence fits this computer yet. You can choose a candidate below."
},
"xdSignin": {
"badge": "Recommended",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6deeb414aa..afd11717f0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2009,8 +2009,8 @@
"hostProfileApple": "Apple シリコン · 統合メモリ 約 {{memory}} GB",
"hostProfileGeneric": "メモリ 約 {{memory}} GB",
"hostProfileUnknown": "このコンピュータのメモリをまだ確認できません",
- "bestForYou": "あなたに最適",
- "alsoCoding": "コーディングにも",
+ "bestForYou": "能力で推奨",
+ "alsoCoding": "速度の候補",
"packaging": {
"mxfp8": "MXFP8",
"mlx": "MLX",
@@ -2027,41 +2027,12 @@
"noSearchResults": "一致するモデルがありません",
"alreadyInstalled": "インストール済み",
"searchResults": "検索結果",
- "moreModels": "その他のよく使うモデル",
- "memoryWarning": "このコンピュータのメモリが不足しています({{need}} GB 必要、現在約 {{have}} GB)",
+ "moreModels": "その他の候補モデル",
+ "memoryWarning": "推定メモリ目安未満({{need}} GB、本機は約 {{have}} GB)",
"manualDownload": "手動ダウンロード",
"manualDownloadPlaceholder": "Ollama のライブラリ名、または Hugging Face の URL",
"invalidLibraryName": "Ollama のライブラリ名を入力するか、huggingface.co のモデルページ URL を貼り付けてください",
"advancedExactName": "上級:正確なライブラリ名",
- "models": {
- "qwen38-27b": {
- "blurb": "ローカルで動かせる最強クラスの密モデル。コーディングと長時間タスク向け。"
- },
- "gpt-oss-20b": {
- "blurb": "OpenAI のオープン 20B。16GB 級マシンの定番。"
- },
- "gemma4-e2b": {
- "blurb": "Gemma 4 の最小。軽いマシンでも動く。ビジョン付き。"
- },
- "gemma4-e4b": {
- "blurb": "Google Gemma 4 の小型。日常使いでビジョン付き。"
- },
- "gemma4-12b": {
- "blurb": "Gemma 4 の中型。日常会話とマルチモーダル向け。"
- },
- "gemma4-31b": {
- "blurb": "Gemma 4 の大型。会話とマルチモーダルがより強く、メモリもより食う。"
- },
- "gemma4-26b": {
- "blurb": "Gemma 4 の中大型 MoE。有効パラメータは少なめ。"
- },
- "ornith15-35b": {
- "blurb": "Ornith 1.5 の中型 MoE。ローカルのコーディングと Agent の控え。"
- },
- "glm-47-flash": {
- "blurb": "智譜の新しいコーディングモデル。30B MoE で、コードと Agent 向き。"
- }
- },
"onboardingTitle": "先に Ollama ランタイムをインストール",
"onboardingBody": "Ollama をインストールすれば、Ollama アプリを開かなくても Cindy 内でローカルモデルをダウンロードして使えます。Ollama は無料のオープンソース製サードパーティランタイムです。",
"installInCindy": "Cindy 内でインストール",
@@ -2130,8 +2101,8 @@
"cancelDownload": "未完了のダウンロードを削除",
"notRecommended": "この Mac は Qwen3.8 27B に必要な 32 GB メモリに達していません。正確なライブラリ名を入力して自分でダウンロードできます。",
"sizeHint": "約 {{size}} · 統合メモリ {{memory}} GB が必要",
- "sizeHintApple": "約 {{size}} · 統合メモリ {{memory}} GB が必要",
- "sizeHintGeneric": "約 {{size}} · メモリ {{memory}} GB が必要",
+ "sizeHintApple": "ダウンロード {{size}} · 統合メモリの目安 {{memory}} GB",
+ "sizeHintGeneric": "ダウンロード {{size}} · メモリの目安 {{memory}} GB",
"deleteFromCindy": "Cindy から削除",
"deleteConfirmTitle": "Cindy から Ollama を削除しますか?",
"deleteConfirmBody": "Cindy 側の接続だけを削除します。Ollama にダウンロード済みのモデルはディスクに残り、サービスも停止しません。",
@@ -2140,7 +2111,8 @@
"deleteModelConfirmBody": "このパソコンからダウンロード済みのモデルファイルを削除し、Cindy からも取り除きます。必要ならあとから再ダウンロードできます。",
"deleteModelConfirm": "削除",
"deleteModelDone": "{{name}} を削除しました",
- "deleteModelFailed": "削除できませんでした。Ollama が起動していることを確認して、もう一度お試しください。"
+ "deleteModelFailed": "削除できませんでした。Ollama が起動していることを確認して、もう一度お試しください。",
+ "noRecommendation": "このコンピュータのメモリに適合し、十分な根拠のある推奨モデルはまだありません。下の候補から選べます。"
},
"xdSignin": {
"badge": "おすすめ",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4c7d6d1748..3d23f66f24 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2009,8 +2009,8 @@
"hostProfileApple": "Apple 칩 · 통합 메모리 약 {{memory}}GB",
"hostProfileGeneric": "메모리 약 {{memory}}GB",
"hostProfileUnknown": "이 컴퓨터의 메모리를 아직 확인할 수 없습니다",
- "bestForYou": "가장 잘 맞음",
- "alsoCoding": "코딩에도 좋음",
+ "bestForYou": "성능 추천",
+ "alsoCoding": "속도 대안",
"packaging": {
"mxfp8": "MXFP8",
"mlx": "MLX",
@@ -2027,41 +2027,12 @@
"noSearchResults": "일치하는 모델이 없습니다",
"alreadyInstalled": "설치됨",
"searchResults": "검색 결과",
- "moreModels": "자주 쓰는 모델 더 보기",
- "memoryWarning": "이 컴퓨터의 메모리가 부족합니다({{need}} GB 필요, 현재 약 {{have}} GB)",
+ "moreModels": "다른 후보 모델",
+ "memoryWarning": "추정 메모리 기준 미만({{need}} GB, 이 기기 약 {{have}} GB)",
"manualDownload": "수동 다운로드",
"manualDownloadPlaceholder": "Ollama 라이브러리 이름 또는 Hugging Face URL",
"invalidLibraryName": "Ollama 라이브러리 이름을 입력하거나 huggingface.co 모델 페이지 URL을 붙여넣으세요",
"advancedExactName": "고급: 정확한 라이브러리 이름",
- "models": {
- "qwen38-27b": {
- "blurb": "로컬에서 돌릴 수 있는 가장 강한 밀집 모델. 코딩과 긴 작업에 적합합니다."
- },
- "gpt-oss-20b": {
- "blurb": "OpenAI 오픈 20B. 16GB급 기기에서 가장 무난한 선택."
- },
- "gemma4-e2b": {
- "blurb": "Gemma 4 최소형. 가벼운 기기에서도 돌아가며 비전을 지원합니다."
- },
- "gemma4-e4b": {
- "blurb": "Google Gemma 4 소형. 가벼운 일상용이며 비전을 지원합니다."
- },
- "gemma4-12b": {
- "blurb": "Gemma 4 중형. 일상 대화와 멀티모달에 더 안정적입니다."
- },
- "gemma4-31b": {
- "blurb": "Gemma 4 대형. 대화와 멀티모달이 더 강하고, 메모리도 더 듭니다."
- },
- "gemma4-26b": {
- "blurb": "Gemma 4 중대형 MoE. 활성 파라미터가 적어 중고사양에 맞습니다."
- },
- "ornith15-35b": {
- "blurb": "Ornith 1.5 중형 MoE. 로컬 코딩과 에이전트 대안."
- },
- "glm-47-flash": {
- "blurb": "Zhipu의 최신 코딩 모델. 30B MoE로 코드와 에이전트에 맞음."
- }
- },
"onboardingTitle": "먼저 Ollama 런타임을 설치하세요",
"onboardingBody": "Ollama를 설치하면 Ollama 앱을 열지 않고도 Cindy에서 로컬 모델을 다운로드하고 사용할 수 있습니다. Ollama는 무료 오픈소스 서드파티 런타임입니다.",
"installInCindy": "Cindy에서 설치",
@@ -2130,8 +2101,8 @@
"cancelDownload": "미완료 다운로드 삭제",
"notRecommended": "이 Mac은 Qwen3.8 27B에 필요한 32GB 메모리 기준에 미달합니다. 정확한 라이브러리 이름을 입력해 직접 다운로드할 수 있습니다.",
"sizeHint": "약 {{size}} · 통합 메모리 {{memory}}GB 필요",
- "sizeHintApple": "약 {{size}} · 통합 메모리 {{memory}}GB 필요",
- "sizeHintGeneric": "약 {{size}} · 메모리 {{memory}}GB 필요",
+ "sizeHintApple": "다운로드 {{size}} · 예상 통합 메모리 {{memory}} GB",
+ "sizeHintGeneric": "다운로드 {{size}} · 예상 메모리 {{memory}} GB",
"deleteFromCindy": "Cindy에서 제거",
"deleteConfirmTitle": "Cindy에서 Ollama를 제거할까요?",
"deleteConfirmBody": "Cindy 연결만 제거합니다. Ollama에 이미 받은 모델은 디스크에 남고 서비스도 멈추지 않습니다.",
@@ -2140,7 +2111,8 @@
"deleteModelConfirmBody": "이 컴퓨터에서 받은 모델 파일을 삭제하고 Cindy에서도 제거합니다. 필요하면 나중에 다시 받을 수 있습니다.",
"deleteModelConfirm": "삭제",
"deleteModelDone": "{{name}}을(를) 삭제했습니다",
- "deleteModelFailed": "삭제하지 못했습니다. Ollama가 실행 중인지 확인한 뒤 다시 시도해 주세요."
+ "deleteModelFailed": "삭제하지 못했습니다. Ollama가 실행 중인지 확인한 뒤 다시 시도해 주세요.",
+ "noRecommendation": "아직 이 컴퓨터의 메모리에 맞고 근거가 충분한 추천 모델이 없습니다. 아래에서 후보를 직접 선택할 수 있습니다."
},
"xdSignin": {
"badge": "추천",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index f44affe5b0..fc35b0b9f2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2009,8 +2009,8 @@
"hostProfileApple": "Apple 芯片 · 约 {{memory}} GB 统一内存",
"hostProfileGeneric": "约 {{memory}} GB 内存",
"hostProfileUnknown": "还不能确定这台电脑的内存",
- "bestForYou": "最适合你",
- "alsoCoding": "也适合编程",
+ "bestForYou": "能力推荐",
+ "alsoCoding": "速度备选",
"packaging": {
"mxfp8": "MXFP8",
"mlx": "MLX",
@@ -2027,41 +2027,12 @@
"noSearchResults": "没有匹配的模型",
"alreadyInstalled": "已在本机",
"searchResults": "搜索结果",
- "moreModels": "更多常用模型",
- "memoryWarning": "这台电脑内存不足(需要 {{need}} GB,当前约 {{have}} GB)",
+ "moreModels": "其他候选模型",
+ "memoryWarning": "低于估算内存门槛({{need}} GB,本机约 {{have}} GB)",
"manualDownload": "手动下载",
"manualDownloadPlaceholder": "Ollama 库名或 Hugging Face 链接",
"invalidLibraryName": "请输入 Ollama 库名,或粘贴 huggingface.co 上的模型页链接",
"advancedExactName": "高级:精确库名",
- "models": {
- "qwen38-27b": {
- "blurb": "当前最强可本机跑的稠密模型,适合编程和长任务。"
- },
- "gpt-oss-20b": {
- "blurb": "OpenAI 开源 20B,16GB 级机器上的对话和推理首选。"
- },
- "gemma4-e2b": {
- "blurb": "Gemma 4 最小杯,轻量机器也能跑,带视觉。"
- },
- "gemma4-e4b": {
- "blurb": "Google Gemma 4 小杯,轻量日常,带视觉。"
- },
- "gemma4-12b": {
- "blurb": "Gemma 4 中杯,日常对话和多模态更稳。"
- },
- "gemma4-31b": {
- "blurb": "Gemma 4 大杯,对话和多模态更强,也更吃内存。"
- },
- "gemma4-26b": {
- "blurb": "Gemma 4 的 MoE 中大杯,激活参数更少,适合中高配。"
- },
- "ornith15-35b": {
- "blurb": "Ornith 1.5 中杯 MoE,本机编程和 Agent 备选。"
- },
- "glm-47-flash": {
- "blurb": "智谱新一代编程模型,30B MoE,适合写代码和 Agent。"
- }
- },
"onboardingTitle": "先安装 Ollama 运行环境",
"onboardingBody": "安装 Ollama 后,即可在 Cindy 中下载和使用本机模型,无需打开 Ollama App。Ollama 是免费开源的第三方运行环境。",
"installInCindy": "在 Cindy 里安装",
@@ -2130,8 +2101,8 @@
"cancelDownload": "删除未完成下载",
"notRecommended": "这台电脑未达到 Qwen3.8 27B 所需的 32 GB 内存门槛。你仍可输入精确库名自行下载。",
"sizeHint": "约 {{size}} · 需要 {{memory}} GB 统一内存",
- "sizeHintApple": "约 {{size}} · 需要 {{memory}} GB 统一内存",
- "sizeHintGeneric": "约 {{size}} · 需要 {{memory}} GB 内存",
+ "sizeHintApple": "下载 {{size}} · 估算需要 {{memory}} GB 统一内存",
+ "sizeHintGeneric": "下载 {{size}} · 估算需要 {{memory}} GB 内存",
"deleteFromCindy": "从 Cindy 移除",
"deleteConfirmTitle": "从 Cindy 移除 Ollama?",
"deleteConfirmBody": "只会移除 Cindy 中的连接。Ollama 里已下载的模型仍在磁盘上,服务也不会停止。",
@@ -2140,7 +2111,8 @@
"deleteModelConfirmBody": "会从这台电脑删除已下载的模型文件,Cindy 里也会一并移除。需要时可以重新下载。",
"deleteModelConfirm": "删除",
"deleteModelDone": "已删除 {{name}}",
- "deleteModelFailed": "删除失败,请确认 Ollama 正在运行后重试"
+ "deleteModelFailed": "删除失败,请确认 Ollama 正在运行后重试",
+ "noRecommendation": "这台电脑暂时没有证据充分且内存适配的推荐,可在下方手动选择候选模型。"
},
"xdSignin": {
"badge": "推荐",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9f58a84447..4a7c86caaf 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2009,8 +2009,8 @@
"hostProfileApple": "Apple 晶片 · 約 {{memory}} GB 統一記憶體",
"hostProfileGeneric": "約 {{memory}} GB 記憶體",
"hostProfileUnknown": "還不能確定這台電腦的記憶體",
- "bestForYou": "最適合你",
- "alsoCoding": "也適合程式設計",
+ "bestForYou": "能力推薦",
+ "alsoCoding": "速度備選",
"packaging": {
"mxfp8": "MXFP8",
"mlx": "MLX",
@@ -2027,41 +2027,12 @@
"noSearchResults": "沒有符合的模型",
"alreadyInstalled": "已在本機",
"searchResults": "搜尋結果",
- "moreModels": "更多常用模型",
- "memoryWarning": "這台電腦記憶體不足(需要 {{need}} GB,目前約 {{have}} GB)",
+ "moreModels": "其他候選模型",
+ "memoryWarning": "低於估算記憶體門檻({{need}} GB,本機約 {{have}} GB)",
"manualDownload": "手動下載",
"manualDownloadPlaceholder": "Ollama 庫名或 Hugging Face 連結",
"invalidLibraryName": "請輸入 Ollama 庫名,或貼上 huggingface.co 上的模型頁連結",
"advancedExactName": "進階:精確庫名",
- "models": {
- "qwen38-27b": {
- "blurb": "目前最強可本機跑的稠密模型,適合程式設計與長任務。"
- },
- "gpt-oss-20b": {
- "blurb": "OpenAI 開源 20B,16GB 級機器上的對話與推理首選。"
- },
- "gemma4-e2b": {
- "blurb": "Gemma 4 最小杯,輕量機器也能跑,帶視覺。"
- },
- "gemma4-e4b": {
- "blurb": "Google Gemma 4 小杯,輕量日常,帶視覺。"
- },
- "gemma4-12b": {
- "blurb": "Gemma 4 中杯,日常對話與多模態更穩。"
- },
- "gemma4-31b": {
- "blurb": "Gemma 4 大杯,對話與多模態更強,也更吃記憶體。"
- },
- "gemma4-26b": {
- "blurb": "Gemma 4 的 MoE 中大杯,啟動參數更少,適合中高配。"
- },
- "ornith15-35b": {
- "blurb": "Ornith 1.5 中杯 MoE,本機程式設計與 Agent 備選。"
- },
- "glm-47-flash": {
- "blurb": "智譜新一代程式設計模型,30B MoE,適合寫程式和 Agent。"
- }
- },
"onboardingTitle": "先安裝 Ollama 執行環境",
"onboardingBody": "安裝 Ollama 後,即可在 Cindy 中下載和使用本機模型,無需開啟 Ollama App。Ollama 是免費開源的第三方執行環境。",
"installInCindy": "在 Cindy 裡安裝",
@@ -2130,8 +2101,8 @@
"cancelDownload": "刪除未完成下載",
"notRecommended": "這台電腦未達到 Qwen3.8 27B 所需的 32 GB 記憶體門檻。你仍可輸入精確庫名自行下載。",
"sizeHint": "約 {{size}} · 需要 {{memory}} GB 統一記憶體",
- "sizeHintApple": "約 {{size}} · 需要 {{memory}} GB 統一記憶體",
- "sizeHintGeneric": "約 {{size}} · 需要 {{memory}} GB 記憶體",
+ "sizeHintApple": "下載 {{size}} · 估算需要 {{memory}} GB 統一記憶體",
+ "sizeHintGeneric": "下載 {{size}} · 估算需要 {{memory}} GB 記憶體",
"deleteFromCindy": "從 Cindy 移除",
"deleteConfirmTitle": "從 Cindy 移除 Ollama?",
"deleteConfirmBody": "只會移除 Cindy 中的連線。Ollama 裡已下載的模型仍在磁碟上,服務也不會停止。",
@@ -2140,7 +2111,8 @@
"deleteModelConfirmBody": "會從這台電腦刪除已下載的模型檔案,Cindy 裡也會一併移除。需要時可以重新下載。",
"deleteModelConfirm": "刪除",
"deleteModelDone": "已刪除 {{name}}",
- "deleteModelFailed": "刪除失敗,請確認 Ollama 正在執行後重試"
+ "deleteModelFailed": "刪除失敗,請確認 Ollama 正在執行後重試",
+ "noRecommendation": "這台電腦暫時沒有證據充分且記憶體適配的推薦,可在下方手動選擇候選模型。"
},
"xdSignin": {
"badge": "推薦",
diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
index c9cb026a50..72e6f2125f 100644
--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
@@ -278,15 +278,17 @@ describe('PI custom-provider protocol overrides', () => {
] as const)(
'drops a stale Messages route when switching the model override to %s',
(piApi, expected) => {
- const models: ProviderRuntimeModelConfig[] = [{
- id: 'routed-model',
- name: 'Routed model',
- piApi: 'anthropic-messages',
- route: {
- baseUrl: 'https://provider.example/anthropic',
- wireProtocol: 'anthropic-messages',
+ const models: ProviderRuntimeModelConfig[] = [
+ {
+ id: 'routed-model',
+ name: 'Routed model',
+ piApi: 'anthropic-messages',
+ route: {
+ baseUrl: 'https://provider.example/anthropic',
+ wireProtocol: 'anthropic-messages',
+ },
},
- }];
+ ];
expect(setCustomProviderModelPiApi(models, 0, piApi)[0]).toEqual({
id: 'routed-model',
@@ -348,7 +350,9 @@ describe('Pi custom-provider reasoning controls', () => {
reasoningEfforts: ['minimal', 'low', 'medium', 'high'],
},
]);
- expect(setCustomProviderModelReasoning(enabled, 0, false)).toEqual(models);
+ expect(setCustomProviderModelReasoning(enabled, 0, false)).toEqual(
+ models.map((model) => ({ ...model, reasoning: false })),
+ );
});
it('keeps canonical order and refuses to remove the final supported effort', () => {
@@ -769,8 +773,8 @@ describe('appendDiscoveredCustomProviderModels', () => {
);
expect(result).toEqual({
models: [
- { id: 'kept', name: 'Kept' },
- { id: 'new', name: 'New', defaultEnabled: false },
+ { id: 'kept', name: 'Kept', nameExplicit: true, discoveredMetadata: { name: 'New name' } },
+ { id: 'new', name: 'New', defaultEnabled: false, discoveredMetadata: { name: 'New' } },
],
addedIds: ['new'],
});
@@ -786,10 +790,15 @@ describe('appendDiscoveredCustomProviderModels', () => {
],
);
expect(result.models).toEqual([
- { id: 'big', name: 'Big', contextWindow: 1_000_000, defaultEnabled: false },
- { id: 'plain', name: 'Plain', defaultEnabled: false },
+ {
+ id: 'big',
+ name: 'Big',
+ discoveredMetadata: { name: 'Big', contextWindow: 1_000_000 },
+ defaultEnabled: false,
+ },
+ { id: 'plain', name: 'Plain', discoveredMetadata: { name: 'Plain' }, defaultEnabled: false },
// 非法值不落盘,回落保守默认
- { id: 'bogus', name: 'Bogus', defaultEnabled: false },
+ { id: 'bogus', name: 'Bogus', discoveredMetadata: { name: 'Bogus' }, defaultEnabled: false },
]);
});
});
diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.ts
index 7198c3b367..37491a42ec 100644
--- a/apps/desktop/src/renderer/lib/customProviders.ts
+++ b/apps/desktop/src/renderer/lib/customProviders.ts
@@ -1,3 +1,4 @@
+import { mergeDiscoveredRuntimeModels, type DiscoveredModel } from '@cindy/model-providers';
/**
* customProviders —— 自定义供应商「配置 + per-runtime 密钥」的 renderer 侧写入编排。
*
@@ -90,13 +91,14 @@ export function setCustomProviderModelPiApi(
const next = { ...model };
if (piApi) next.piApi = piApi;
else delete next.piApi;
- const selectedWireProtocol = piApi === 'anthropic-messages'
- ? 'anthropic-messages'
- : piApi === 'openai-completions'
- ? 'openai-chat'
- : piApi === 'openai-responses'
- ? 'openai-responses'
- : undefined;
+ const selectedWireProtocol =
+ piApi === 'anthropic-messages'
+ ? 'anthropic-messages'
+ : piApi === 'openai-completions'
+ ? 'openai-chat'
+ : piApi === 'openai-responses'
+ ? 'openai-responses'
+ : undefined;
// "Inherit default" means inheriting both protocol and endpoint. For an explicit override,
// retain a model endpoint only when it already speaks that protocol; otherwise the provider
// endpoint is the only safe pair (also repairs legacy protocol/route mismatches on save).
@@ -136,7 +138,7 @@ export function setCustomProviderModelReasoning(
if (index !== targetIndex) return model;
if (!reasoning) {
const rest = { ...model };
- delete rest.reasoning;
+ rest.reasoning = false;
delete rest.reasoningEfforts;
delete rest.reasoningDefaultEffort;
return rest;
@@ -188,6 +190,9 @@ export function customProviderModelConfigFromCatalogModel(
| 'name'
| 'contextWindow'
| 'contextWindowExplicit'
+ | 'userModelConfig'
+ | 'discoveredMetadata'
+ | 'nameExplicit'
| 'defaultEnabled'
| 'supportsImageInput'
| 'piApi'
@@ -196,6 +201,7 @@ export function customProviderModelConfigFromCatalogModel(
Partial<Pick<CatalogModel, 'efforts' | 'defaultEffort'>>,
agent?: AgentKind,
): ProviderRuntimeModelConfig {
+ if (model.userModelConfig) return structuredClone(model.userModelConfig);
const reasoningEfforts =
agent === 'pi'
? (model.efforts ?? []).filter((effort): effort is PiReasoningEffort =>
@@ -205,10 +211,14 @@ export function customProviderModelConfigFromCatalogModel(
return {
id: model.id,
name: model.name,
+ discoveredMetadata: model.discoveredMetadata,
+ nameExplicit: model.nameExplicit,
...(agent === 'pi' && model.piApi ? { piApi: model.piApi } : {}),
...(model.route ? { route: { ...model.route } } : {}),
...(model.contextWindowExplicit === true ||
- model.contextWindow !== DEFAULT_CUSTOM_CONTEXT_WINDOW
+ (model.contextWindowExplicit === undefined &&
+ !model.discoveredMetadata &&
+ model.contextWindow !== DEFAULT_CUSTOM_CONTEXT_WINDOW)
? { contextWindow: model.contextWindow }
: {}),
...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),
@@ -230,6 +240,7 @@ export function providerViewToCustomProviderConfig(p: ProviderView): CustomProvi
const models = p.models[agent] ?? [];
runtimes[agent] = {
baseUrl: routing?.upstream ?? '',
+ ...(models[0]?.catalogPresetId ? { catalogPresetId: models[0].catalogPresetId } : {}),
...(routing?.requestPath ? { requestPath: routing.requestPath } : {}),
...(routing?.wireProtocol ? { wireProtocol: routing.wireProtocol } : {}),
...(agent === 'codex' && routing?.supportsImageGeneration === true
@@ -259,27 +270,14 @@ export function providerViewToCustomProviderConfig(p: ProviderView): CustomProvi
/** 刷新时只追加接口新发现的模型,并让新增模型默认隐藏。端点声明的 contextWindow 随发现带入(#386)。 */
export function appendDiscoveredCustomProviderModels(
existing: readonly ProviderRuntimeModelConfig[],
- discovered: readonly Pick<ProviderRuntimeModelConfig, 'id' | 'name' | 'contextWindow'>[],
+ discovered: readonly DiscoveredModel[],
): { models: ProviderRuntimeModelConfig[]; addedIds: string[] } {
- const known = new Set(existing.map((m) => m.id));
- const models = [...existing];
- const addedIds: string[] = [];
- for (const model of discovered) {
- if (!model.id || !model.name || known.has(model.id)) continue;
- models.push({
- id: model.id,
- name: model.name,
- ...(typeof model.contextWindow === 'number' &&
- Number.isFinite(model.contextWindow) &&
- model.contextWindow > 0
- ? { contextWindow: Math.floor(model.contextWindow) }
- : {}),
- defaultEnabled: false,
- });
- known.add(model.id);
- addedIds.push(model.id);
- }
- return { models, addedIds };
+ const models = mergeDiscoveredRuntimeModels(existing, discovered, true);
+ const known = new Set(existing.map((model) => model.id));
+ return {
+ models,
+ addedIds: models.filter((model) => !known.has(model.id)).map((model) => model.id),
+ };
}
/**
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 7085ab4f77..b2dee83984 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1627,9 +1627,7 @@ interface ElectronAPI {
reload: (id: string) => Promise<{ state: string }>;
/** Library(持久作品库)设置面:概览/选位置/绑定/迁移/回默认/解绑/删除。 */
libraryOverview: (id: string) => Promise<import('../shared/ghost').GhostLibraryOverview>;
- libraryPickLocation: (
- id: string,
- ) => Promise<{
+ libraryPickLocation: (id: string) => Promise<{
ok: boolean;
cancelled?: boolean;
candidate?: string;
@@ -5142,7 +5140,7 @@ interface ElectronAPI {
savedProviderId?: string;
}) => Promise<{
ok: boolean;
- models?: { id: string; name: string; contextWindow?: number }[];
+ models?: import('@cindy/model-providers').DiscoveredModel[];
code?: import('../shared/providerErrors').ProviderErrorCode;
status?: number;
detail?: string;
diff --git a/apps/desktop/src/shared/__tests__/localModelRuntime.test.ts b/apps/desktop/src/shared/__tests__/localModelRuntime.test.ts
index af2cf5e459..04c1533555 100644
--- a/apps/desktop/src/shared/__tests__/localModelRuntime.test.ts
+++ b/apps/desktop/src/shared/__tests__/localModelRuntime.test.ts
@@ -1,4 +1,6 @@
import { describe, expect, it } from 'vitest';
+import { BUNDLED_CATALOG } from '@cindy/model-providers';
+const catalogSpec = BUNDLED_CATALOG.modelRegistry!.localModels!;
import {
classifyOllamaPullError,
@@ -17,11 +19,8 @@ import {
OLLAMA_OPENAI_BASE_URL,
pickFeaturedOllamaModels,
recommendForHost,
- recommendQwen38,
resolveCuratedOllamaCatalog,
resolveManagedOllamaAgents,
- QWEN38_MLX,
- QWEN38_MXFP8,
} from '../localModelRuntime.js';
describe('localModelRuntime', () => {
@@ -66,9 +65,12 @@ describe('localModelRuntime', () => {
it('treats an untagged Ollama name as its :latest alias', () => {
expect(ollamaModelRefsEqual('glm-4.7-flash', 'glm-4.7-flash:latest')).toBe(true);
expect(ollamaModelRefsEqual('library/foo', 'library/foo:latest')).toBe(true);
- expect(ollamaModelRefsEqual('hf.co/unsloth/Qwen3.8-27B-GGUF', 'hf.co/unsloth/Qwen3.8-27B-GGUF:latest')).toBe(
- true,
- );
+ expect(
+ ollamaModelRefsEqual(
+ 'hf.co/unsloth/Qwen3.8-27B-GGUF',
+ 'hf.co/unsloth/Qwen3.8-27B-GGUF:latest',
+ ),
+ ).toBe(true);
expect(ollamaModelRefsEqual('gpt-oss:20b', 'gpt-oss:latest')).toBe(false);
expect(ollamaModelRefsEqual('qwen3.8:27b-mxfp8', 'qwen3.8:latest')).toBe(false);
});
@@ -86,74 +88,119 @@ describe('localModelRuntime', () => {
expect(classifyOllamaPullError('connection refused')).toBe('refused');
});
- it('does not recommend 27B below 32GB or off Apple Silicon', () => {
- expect(
- recommendQwen38({ platform: 'darwin', arch: 'x64', totalmemBytes: 128 * 1024 ** 3 }),
- ).toBeNull();
- expect(
- recommendQwen38({ platform: 'darwin', arch: 'arm64', totalmemBytes: 24 * 1024 ** 3 }),
- ).toBeNull();
- expect(
- recommendQwen38({ platform: 'win32', arch: 'arm64', totalmemBytes: 128 * 1024 ** 3 }),
- ).toBeNull();
- });
-
it('picks mlx then mxfp8 by unified memory', () => {
expect(
- recommendQwen38({ platform: 'darwin', arch: 'arm64', totalmemBytes: 36 * 1024 ** 3 }),
- ).toEqual(QWEN38_MLX);
+ recommendForHost({ platform: 'darwin', arch: 'arm64', totalmemBytes: 36 * 1024 ** 3 }).primary
+ ?.libraryName,
+ ).toBe('qwen3.8:27b-mlx');
expect(
- recommendQwen38({ platform: 'darwin', arch: 'arm64', totalmemBytes: 128 * 1024 ** 3 }),
- ).toEqual(QWEN38_MXFP8);
+ recommendForHost({ platform: 'darwin', arch: 'arm64', totalmemBytes: 128 * 1024 ** 3 })
+ .primary?.libraryName,
+ ).toBe('qwen3.8:27b-mxfp8');
});
- it('keeps featured picks tiny and lets search find multilingual aliases', () => {
- const appleMax = {
- platform: 'darwin' as const,
- arch: 'arm64',
- totalmemBytes: 128 * 1024 ** 3,
- };
- const catalog = resolveCuratedOllamaCatalog(appleMax);
- expect(pickFeaturedOllamaModels(appleMax).map((model) => model.id)).toEqual([
- 'qwen38-27b',
- 'ornith15-35b',
- ]);
- expect(catalog.some((model) => model.id === 'gemma4-e4b')).toBe(true);
- expect(catalog.some((model) => model.id === 'gemma4-31b')).toBe(true);
- expect(catalog.some((model) => model.id === 'glm-47-flash')).toBe(true);
- expect(catalog.some((model) => model.id === 'llama3.2-3b')).toBe(false);
- expect(catalog.some((model) => model.id === 'phi4')).toBe(false);
- expect(catalog.some((model) => model.id === 'qwen25-7b')).toBe(false);
- expect(catalog.some((model) => model.id === 'gemma3-12b')).toBe(false);
- expect(
- catalog.find((model) => model.id === 'ornith15-35b')?.libraryName,
- ).toBe('hf.co/ornith-ai/Ornith-1.5-35B-A3B-GGUF:Q4_K_M');
+ it('keeps recommendations separate from searchable candidates', () => {
+ const host = { platform: 'darwin' as const, arch: 'arm64', totalmemBytes: 128 * 1024 ** 3 };
+ const catalog = resolveCuratedOllamaCatalog(host);
+ expect(pickFeaturedOllamaModels(host).map((model) => model.id)).toEqual(['qwen38-27b']);
+ expect(catalog).toHaveLength(7);
expect(filterCuratedOllamaModels(catalog, '通义').map((model) => model.id)).toContain(
'qwen38-27b',
);
expect(filterCuratedOllamaModels(catalog, '宝石').map((model) => model.id)).toEqual([
- 'gemma4-e2b',
- 'gemma4-e4b',
'gemma4-12b',
- 'gemma4-31b',
- 'gemma4-26b',
]);
- expect(filterCuratedOllamaModels(catalog, '编程').map((model) => model.id)).toContain(
- 'ornith15-35b',
- );
- expect(filterCuratedOllamaModels(catalog, '编程').map((model) => model.id)).not.toContain(
- 'gemma4-12b',
- );
- expect(
- pickFeaturedOllamaModels({
- platform: 'darwin',
+ expect(catalog.some((model) => model.id === 'ornith15-35b')).toBe(false);
+ expect(catalog.some((model) => model.id === 'gpt-oss-20b')).toBe(false);
+ });
+
+ it.each([0, 4, 8, 16, 24])(
+ 'leaves recommendations empty at %i GB without promoting candidates',
+ (memory) => {
+ const host = {
+ platform: 'darwin' as const,
arch: 'arm64',
- totalmemBytes: 16 * 1024 ** 3,
- }).map((model) => model.id),
- ).toEqual(['gpt-oss-20b']);
+ totalmemBytes: memory * 1024 ** 3,
+ };
+ expect(recommendForHost(host).primary).toBeNull();
+ expect(pickFeaturedOllamaModels(host)).toEqual([]);
+ expect(resolveCuratedOllamaCatalog(host).some((model) => model.id === 'qwen35-4b')).toBe(
+ true,
+ );
+ },
+ );
+
+ it('honors the recommendation allowlist even when a larger model fits', () => {
+ const host = { platform: 'darwin' as const, arch: 'arm64', totalmemBytes: 256 * 1024 ** 3 };
+ expect(
+ recommendForHost(host, { ...catalogSpec, models: [], featuredIds: [] }).primary,
+ ).toBeNull();
+ expect(recommendForHost(host, { ...catalogSpec, featuredIds: [] }).primary).toBeNull();
+ expect(recommendForHost(host, { ...catalogSpec, featuredIds: ['qwen35-4b'] }).primary?.id).toBe(
+ 'qwen35-4b',
+ );
+ });
+
+ it('uses platform-specific download sizes and excludes Apple-only candidates elsewhere', () => {
+ const host = { platform: 'darwin' as const, arch: 'arm64', totalmemBytes: 256 * 1024 ** 3 };
+ const apple = resolveCuratedOllamaCatalog(host);
+ const windows = resolveCuratedOllamaCatalog({ ...host, platform: 'win32', arch: 'x64' });
+ expect(apple.find((model) => model.id === 'qwen35-9b')).toMatchObject({
+ libraryName: 'qwen3.5:9b-mlx',
+ sizeBytes: 8903014479,
+ appleSiliconOnly: true,
+ });
+ expect(windows.find((model) => model.id === 'qwen35-9b')).toMatchObject({
+ libraryName: 'qwen3.5:9b-q4_K_M',
+ sizeBytes: 6594474236,
+ appleSiliconOnly: false,
+ });
+ expect(windows.some((model) => model.id === 'qwen38-flash-next')).toBe(false);
+ expect(apple.some((model) => model.id === 'qwen38-flash-next')).toBe(true);
+ });
+
+ it('rejects invalid platform metadata and preserves bundled fallback', () => {
+ const host = { platform: 'darwin' as const, arch: 'arm64', totalmemBytes: 128 * 1024 ** 3 };
+ const remote = {
+ ...catalogSpec,
+ models: [{ ...catalogSpec.models[0], variants: [{ libraryName: '../bad', sizeBytes: -1 }] }],
+ };
+ expect(recommendForHost(host, remote).primary?.id).toBe('qwen38-27b');
+ });
+
+ it('uses remotely added models and exact packaging without a bundled name entry', () => {
+ const remote = {
+ version: 1,
+ featuredIds: ['new-model'],
+ models: [
+ {
+ id: 'new-model',
+ name: 'New model',
+ aliases: [],
+ variants: [
+ { libraryName: 'new-model:4b', sizeBytes: 4 * 1024 ** 3, minUnifiedMemoryGb: 8 },
+ ],
+ descriptions: { 'zh-CN': '测试简介' },
+ },
+ ],
+ };
+ const host = { platform: 'darwin' as const, arch: 'arm64', totalmemBytes: 16 * 1024 ** 3 };
+ expect(recommendForHost(host, remote).primary).toMatchObject({
+ id: 'new-model',
+ descriptions: { 'zh-CN': '测试简介' },
+ });
+ expect(curatedOllamaDisplayName('new-model:4b', remote)).toBe('New model');
+ expect(pickFeaturedOllamaModels(host, { version: 1, models: [], featuredIds: [] })).toEqual([]);
+ });
+
+ it('does not label an unknown quantization as a different model size', () => {
+ expect(curatedOllamaDisplayName('qwen3.5:9b-mlx')).toBe('Qwen3.5 9B');
+ expect(curatedOllamaDisplayName('qwen3.5:9b-q8_0')).toBeUndefined();
+ expect(curatedOllamaDisplayName('gemma4:31b-mlx')).toBeUndefined();
+ expect(curatedOllamaDisplayName('qwen3.8:27b-mlx')).toBe('Qwen3.8 27B');
});
- it('picks a machine-specific primary model for every host class', () => {
+ it('picks a fitting recommendation and leaves unsupported tiers empty', () => {
expect(
recommendForHost({
platform: 'darwin',
@@ -181,7 +228,7 @@ describe('localModelRuntime', () => {
arch: 'x64',
totalmemBytes: 16 * 1024 ** 3,
}),
- ).toMatchObject({ reason: 'compact', primary: { id: 'gpt-oss-20b' } });
+ ).toMatchObject({ reason: 'compact', primary: null });
expect(
recommendForHost({
platform: 'linux',
diff --git a/apps/desktop/src/shared/localModelRuntime.ts b/apps/desktop/src/shared/localModelRuntime.ts
index c29c7d2de4..26f1e92666 100644
--- a/apps/desktop/src/shared/localModelRuntime.ts
+++ b/apps/desktop/src/shared/localModelRuntime.ts
@@ -4,12 +4,17 @@
* 安全边界:renderer 只传 runtime / 操作枚举和已校验的模型名;
* URL、路径、shell 一律由 Main 写死。
*
- * 精选目录是纯数据(`ollamaCuratedCatalog.json`)。挑选算法和库名白名单留在本文件,
- * 以后这份 JSON 可以改由 `/api/model-catalog/catalog` 下发;未知根字段现在不能写进
- * Catalog schema,所以本 PR 不改热更协议。
+ * 精选目录来自活动 Registry V4;缺少该字段时使用随包快照。
+ * 筛选与运行操作留在客户端,服务端仅下发经过校验的数据。
*/
-import curatedCatalogJson from './ollamaCuratedCatalog.json' with { type: 'json' };
+import {
+ BUNDLED_CATALOG,
+ parseLocalModelCatalog,
+ type LocalModelCatalog,
+ type LocalCatalogModel,
+ type LocalModelVariant,
+} from '@cindy/model-providers';
export const MANAGED_OLLAMA_PROVIDER_ID = 'cindy-local-ollama';
export const MANAGED_LMSTUDIO_PROVIDER_ID = 'cindy-local-lmstudio';
@@ -128,6 +133,8 @@ export interface RecommendedLocalModel {
export interface CuratedOllamaModel extends RecommendedLocalModel {
aliases: string[];
+ descriptions?: LocalCatalogModel['descriptions'];
+ runtimeProfile?: LocalCatalogModel['runtimeProfile'];
}
export type OllamaPackaging = 'mxfp8' | 'mlx' | 'q4';
@@ -165,12 +172,7 @@ export interface LocalModelPullProgress {
error?: string;
}
-export type OllamaPullErrorKind =
- | 'not-gguf'
- | 'not-found'
- | 'unauthorized'
- | 'refused'
- | 'generic';
+export type OllamaPullErrorKind = 'not-gguf' | 'not-found' | 'unauthorized' | 'refused' | 'generic';
const OLLAMA_PULL_ERROR_KINDS = new Set<OllamaPullErrorKind>([
'not-gguf',
@@ -197,10 +199,7 @@ export function isHfMlxPullName(name: string): boolean {
return /mlx/i.test(repo) && !/gguf/i.test(name);
}
-export function classifyOllamaPullError(
- value: unknown,
- pullName?: string,
-): OllamaPullErrorKind {
+export function classifyOllamaPullError(value: unknown, pullName?: string): OllamaPullErrorKind {
if (typeof value === 'string' && OLLAMA_PULL_ERROR_KINDS.has(value as OllamaPullErrorKind)) {
return value as OllamaPullErrorKind;
}
@@ -255,72 +254,17 @@ export interface LocalModelRecommendInput {
const GIB = 1024 * 1024 * 1024;
-interface CuratedTagSpec {
- libraryName: string;
- sizeBytes: number;
- minUnifiedMemoryGb: number;
- appleSiliconOnly?: boolean;
-}
-
-interface CuratedModelSpec {
- id: string;
- name: string;
- libraryName: string;
- appleLibraryName?: string;
- aliases: string[];
- sizeBytes: number;
- minUnifiedMemoryGb: number;
-}
-
-interface CuratedCatalogSpec {
- version: number;
- qwen38: {
- id: string;
- name: string;
- aliases: string[];
- mxfp8: CuratedTagSpec;
- mlx: CuratedTagSpec;
- generic: CuratedTagSpec;
- };
- featuredIds: string[];
- featuredCoderId?: string;
- models: CuratedModelSpec[];
-}
+const BUNDLED_CURATED_CATALOG = BUNDLED_CATALOG.modelRegistry!.localModels!;
function recommendedFromTag(
id: string,
name: string,
- spec: CuratedTagSpec,
+ spec: LocalModelVariant,
): RecommendedLocalModel {
- return {
- id,
- name,
- libraryName: spec.libraryName,
- sizeBytes: spec.sizeBytes,
- minUnifiedMemoryGb: spec.minUnifiedMemoryGb,
- appleSiliconOnly: spec.appleSiliconOnly === true,
- };
+ return { id, name, ...spec, appleSiliconOnly: spec.appleSiliconOnly === true };
}
-
-const BUNDLED_CURATED_CATALOG = curatedCatalogJson as CuratedCatalogSpec;
-
-export const QWEN38_MXFP8: RecommendedLocalModel = recommendedFromTag(
- BUNDLED_CURATED_CATALOG.qwen38.mxfp8.libraryName,
- BUNDLED_CURATED_CATALOG.qwen38.name,
- BUNDLED_CURATED_CATALOG.qwen38.mxfp8,
-);
-
-export const QWEN38_MLX: RecommendedLocalModel = recommendedFromTag(
- BUNDLED_CURATED_CATALOG.qwen38.mlx.libraryName,
- BUNDLED_CURATED_CATALOG.qwen38.name,
- BUNDLED_CURATED_CATALOG.qwen38.mlx,
-);
-
-export const QWEN38_CURATED_TAGS = new Set<string>([
- QWEN38_MXFP8.libraryName,
- QWEN38_MLX.libraryName,
- BUNDLED_CURATED_CATALOG.qwen38.generic.libraryName,
-]);
+// Runtime support is client-owned and survives withdrawal from the catalog.
+export const QWEN38_CURATED_TAGS = new Set(['qwen3.8:27b', 'qwen3.8:27b-mlx', 'qwen3.8:27b-mxfp8']);
export function isOllamaModelName(value: unknown): value is string {
return typeof value === 'string' && OLLAMA_MODEL_NAME_RE.test(value);
@@ -366,7 +310,9 @@ export function normalizeOllamaPullName(value: string): string | null {
}
let quant: string | undefined;
- const blobIndex = parts.findIndex((part) => part === 'blob' || part === 'tree' || part === 'resolve');
+ const blobIndex = parts.findIndex(
+ (part) => part === 'blob' || part === 'tree' || part === 'resolve',
+ );
if (blobIndex >= 0 && parts[blobIndex + 2]) {
const file = parts[blobIndex + 2] ?? '';
const match = file.match(/[-_.]([Qq]\d[\w.-]*|UD-[\w.-]+|iq\d[\w.-]*)\.gguf$/i);
@@ -446,228 +392,66 @@ export function unifiedMemoryGb(totalmemBytes: number): number {
return Math.floor(totalmemBytes / GIB);
}
-/** 低于 32GB 统一内存不推荐 27B;MLX 仅 Apple Silicon。算法留在客户端,门槛来自策展数据。 */
-export function recommendQwen38(
- input: LocalModelRecommendInput,
- remote?: unknown,
-): RecommendedLocalModel | null {
- if (!isAppleSilicon(input)) return null;
- const spec = resolveCuratedCatalogSpec(remote);
- const gb = unifiedMemoryGb(input.totalmemBytes);
- if (gb >= spec.qwen38.mxfp8.minUnifiedMemoryGb) {
- return recommendedFromTag(spec.qwen38.mxfp8.libraryName, spec.qwen38.name, spec.qwen38.mxfp8);
- }
- if (gb >= spec.qwen38.mlx.minUnifiedMemoryGb) {
- return recommendedFromTag(spec.qwen38.mlx.libraryName, spec.qwen38.name, spec.qwen38.mlx);
- }
- return null;
-}
-
export function isCuratedQwen38Tag(name: string): boolean {
return QWEN38_CURATED_TAGS.has(name);
}
-export function curatedOllamaDisplayName(libraryName: string): string | undefined {
- const catalogs = [
- resolveCuratedOllamaCatalog({
- platform: 'darwin',
- arch: 'arm64',
- totalmemBytes: 128 * GIB,
- }),
- resolveCuratedOllamaCatalog({
- platform: 'linux',
- arch: 'x64',
- totalmemBytes: 128 * GIB,
- }),
- ];
- for (const catalog of catalogs) {
- const exact = catalog.find((entry) => entry.libraryName === libraryName);
- if (exact) return exact.name;
- }
- const family = libraryName.split(':')[0] ?? libraryName;
- for (const catalog of catalogs) {
- const hit = catalog.find((entry) => (entry.libraryName.split(':')[0] ?? '') === family);
- if (hit) return hit.name;
- }
- return undefined;
-}
-
-function isSafeId(value: unknown): value is string {
- return typeof value === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(value);
+export function resolveCuratedCatalogSpec(remote?: unknown): LocalModelCatalog {
+ return parseLocalModelCatalog(remote) ?? BUNDLED_CURATED_CATALOG;
}
-function isSafeName(value: unknown): value is string {
- return typeof value === 'string' && value.trim().length > 0 && value.length <= 80;
-}
-
-function isSafeAlias(value: unknown): value is string {
- return typeof value === 'string' && value.trim().length > 0 && value.length <= 40;
-}
-
-function isSafeSize(value: unknown): value is number {
- return typeof value === 'number' && Number.isFinite(value) && value >= GIB && value <= 256 * GIB;
-}
-
-function isSafeMemoryGb(value: unknown): value is number {
- return typeof value === 'number' && Number.isInteger(value) && value >= 4 && value <= 512;
-}
-
-function sanitizeTagSpec(raw: unknown): CuratedTagSpec | null {
- if (!raw || typeof raw !== 'object') return null;
- const spec = raw as CuratedTagSpec;
- if (!isCuratedOllamaLibraryName(spec.libraryName)) return null;
- if (!isSafeSize(spec.sizeBytes) || !isSafeMemoryGb(spec.minUnifiedMemoryGb)) return null;
- return {
- libraryName: spec.libraryName,
- sizeBytes: spec.sizeBytes,
- minUnifiedMemoryGb: spec.minUnifiedMemoryGb,
- ...(spec.appleSiliconOnly === true ? { appleSiliconOnly: true } : {}),
- };
-}
-
-function sanitizeModelSpec(raw: unknown): CuratedModelSpec | null {
- if (!raw || typeof raw !== 'object') return null;
- const spec = raw as CuratedModelSpec;
- if (!isSafeId(spec.id) || !isSafeName(spec.name)) return null;
- if (!isCuratedOllamaLibraryName(spec.libraryName)) return null;
- if (spec.appleLibraryName !== undefined && !isCuratedOllamaLibraryName(spec.appleLibraryName)) {
- return null;
- }
- if (!Array.isArray(spec.aliases) || spec.aliases.length > 16 || !spec.aliases.every(isSafeAlias)) {
- return null;
- }
- if (!isSafeSize(spec.sizeBytes) || !isSafeMemoryGb(spec.minUnifiedMemoryGb)) return null;
- return {
- id: spec.id,
- name: spec.name.trim(),
- libraryName: spec.libraryName,
- ...(spec.appleLibraryName ? { appleLibraryName: spec.appleLibraryName } : {}),
- aliases: spec.aliases.map((alias) => alias.trim()),
- sizeBytes: spec.sizeBytes,
- minUnifiedMemoryGb: spec.minUnifiedMemoryGb,
- };
-}
-
-function sanitizeCatalogSpec(raw: unknown): CuratedCatalogSpec | null {
- if (!raw || typeof raw !== 'object') return null;
- const spec = raw as CuratedCatalogSpec;
- if (spec.version !== 1) return null;
- if (!spec.qwen38 || !isSafeId(spec.qwen38.id) || !isSafeName(spec.qwen38.name)) return null;
- if (
- !Array.isArray(spec.qwen38.aliases) ||
- spec.qwen38.aliases.length > 16 ||
- !spec.qwen38.aliases.every(isSafeAlias)
- ) {
- return null;
- }
- const mxfp8 = sanitizeTagSpec(spec.qwen38.mxfp8);
- const mlx = sanitizeTagSpec(spec.qwen38.mlx);
- const generic = sanitizeTagSpec(spec.qwen38.generic);
- if (!mxfp8 || !mlx || !generic) return null;
- if (!Array.isArray(spec.featuredIds) || spec.featuredIds.length === 0 || spec.featuredIds.length > 8) {
- return null;
- }
- if (!spec.featuredIds.every(isSafeId)) return null;
- if (spec.featuredCoderId !== undefined && !isSafeId(spec.featuredCoderId)) return null;
- if (!Array.isArray(spec.models) || spec.models.length > MAX_CURATED_OLLAMA_MODELS) return null;
- const models: CuratedModelSpec[] = [];
- const seen = new Set<string>([spec.qwen38.id]);
- for (const entry of spec.models) {
- const model = sanitizeModelSpec(entry);
- if (!model || seen.has(model.id)) continue;
- seen.add(model.id);
- models.push(model);
- }
- return {
- version: 1,
- qwen38: {
- id: spec.qwen38.id,
- name: spec.qwen38.name.trim(),
- aliases: spec.qwen38.aliases.map((alias) => alias.trim()),
- mxfp8,
- mlx,
- generic,
- },
- featuredIds: spec.featuredIds,
- ...(spec.featuredCoderId ? { featuredCoderId: spec.featuredCoderId } : {}),
- models,
- };
-}
-
-function modelFromSpec(
- spec: CuratedModelSpec,
- apple: boolean,
-): CuratedOllamaModel {
- const libraryName = apple && spec.appleLibraryName ? spec.appleLibraryName : spec.libraryName;
- return {
- id: spec.id,
- name: spec.name,
- libraryName,
- aliases: spec.aliases,
- sizeBytes: spec.sizeBytes,
- minUnifiedMemoryGb: spec.minUnifiedMemoryGb,
- appleSiliconOnly: apple && Boolean(spec.appleLibraryName),
- };
+export function findCuratedOllamaModel(
+ name: string,
+ remote?: unknown,
+): LocalCatalogModel | undefined {
+ return resolveCuratedCatalogSpec(remote).models.find((m) =>
+ m.variants.some((v) => ollamaModelRefsEqual(v.libraryName, name)),
+ );
}
-/**
- * 策展数据入口。现在只读 bundled JSON;以后可把 remote 换成 catalog section。
- * 远端/覆盖数据不合法时整表回落 bundled,挑选算法仍在客户端。
- */
-export function resolveCuratedCatalogSpec(remote?: unknown): CuratedCatalogSpec {
- return sanitizeCatalogSpec(remote) ?? sanitizeCatalogSpec(BUNDLED_CURATED_CATALOG)!;
+export function curatedOllamaDisplayName(name: string, remote?: unknown): string | undefined {
+ return findCuratedOllamaModel(name, remote)?.name;
}
-/** 可搜索目录:比推荐区更大,默认不展示。 */
+/** Ordered variants express packaging preference; hardware fit is always checked locally. */
export function resolveCuratedOllamaCatalog(
input: LocalModelRecommendInput,
remote?: unknown,
): CuratedOllamaModel[] {
- const spec = resolveCuratedCatalogSpec(remote);
const apple = isAppleSilicon(input);
- const qwen38 =
- recommendQwen38(input, spec) ??
- recommendedFromTag(
- spec.qwen38.id,
- spec.qwen38.name,
- apple ? spec.qwen38.mlx : spec.qwen38.generic,
- );
-
- return [
- {
- ...qwen38,
- id: spec.qwen38.id,
- name: spec.qwen38.name,
- aliases: spec.qwen38.aliases,
- },
- ...spec.models.map((entry) => modelFromSpec(entry, apple)),
- ];
+ const memory = unifiedMemoryGb(input.totalmemBytes);
+ return resolveCuratedCatalogSpec(remote).models.flatMap((model) => {
+ const variants = model.variants.filter((v) => apple || !v.appleSiliconOnly);
+ const variant =
+ variants.find((v) => memory >= v.minUnifiedMemoryGb) ??
+ [...variants].sort((a, b) => a.minUnifiedMemoryGb - b.minUnifiedMemoryGb)[0];
+ if (!variant) return [];
+ return [
+ {
+ ...recommendedFromTag(model.id, model.name, variant),
+ aliases: model.aliases,
+ descriptions: model.descriptions,
+ runtimeProfile: model.runtimeProfile,
+ },
+ ];
+ });
}
-
function fits(model: CuratedOllamaModel, memoryGb: number): boolean {
return memoryGb >= model.minUnifiedMemoryGb;
}
export type LocalRecommendReason =
- | 'apple-mxfp8'
- | 'apple-mlx'
- | 'generic-27b'
- | 'compact'
- | 'unknown';
+ 'apple-mxfp8' | 'apple-mlx' | 'generic-27b' | 'compact' | 'unknown';
export interface HostModelRecommendation {
- primary: CuratedOllamaModel;
+ primary: CuratedOllamaModel | null;
secondary: CuratedOllamaModel | null;
reason: LocalRecommendReason;
appleSilicon: boolean;
memoryGb: number;
}
-function smallestByMemory(models: readonly CuratedOllamaModel[]): CuratedOllamaModel | undefined {
- return [...models].sort((left, right) => left.minUnifiedMemoryGb - right.minUnifiedMemoryGb)[0];
-}
-
-/** 每个用户一条主推:按芯片和内存选官方封装,绝不把跑不动的 27B 硬塞给小机器。 */
+/** 只从有证据的推荐名单中按内存选择;候选目录不能自动补位。 */
export function recommendForHost(
input: LocalModelRecommendInput,
remote?: unknown,
@@ -677,46 +461,27 @@ export function recommendForHost(
const memoryGb = unifiedMemoryGb(input.totalmemBytes);
const appleSilicon = isAppleSilicon(input);
const byId = (id: string) => catalog.find((entry) => entry.id === id);
- const qwen = byId(spec.qwen38.id);
-
- let primary: CuratedOllamaModel | undefined;
- let reason: LocalRecommendReason = 'compact';
-
- if (memoryGb <= 0) {
- primary =
- [...spec.featuredIds].reverse().map(byId).find(Boolean) ?? smallestByMemory(catalog);
- reason = 'unknown';
- } else if (appleSilicon && qwen && memoryGb >= spec.qwen38.mxfp8.minUnifiedMemoryGb) {
- primary = qwen;
- reason = 'apple-mxfp8';
- } else if (appleSilicon && qwen && memoryGb >= spec.qwen38.mlx.minUnifiedMemoryGb) {
- primary = qwen;
- reason = 'apple-mlx';
- } else if (!appleSilicon && qwen && memoryGb >= spec.qwen38.generic.minUnifiedMemoryGb) {
- primary = qwen;
- reason = 'generic-27b';
- } else {
- primary =
- spec.featuredIds.map(byId).find((entry) => entry && fits(entry, memoryGb)) ??
- [...catalog]
- .filter((entry) => fits(entry, memoryGb))
- .sort((left, right) => right.minUnifiedMemoryGb - left.minUnifiedMemoryGb)[0] ??
- smallestByMemory(catalog);
- reason = 'compact';
+ const primary =
+ memoryGb > 0
+ ? (spec.featuredIds.map(byId).find((entry) => entry && fits(entry, memoryGb)) ?? null)
+ : null;
+ let reason: LocalRecommendReason = memoryGb > 0 ? 'compact' : 'unknown';
+ if (primary?.id === 'qwen38-27b') {
+ reason = !appleSilicon
+ ? 'generic-27b'
+ : primary.libraryName === 'qwen3.8:27b-mxfp8'
+ ? 'apple-mxfp8'
+ : 'apple-mlx';
}
-
- const fallback = primary ?? catalog[0];
- if (!fallback) {
- throw new Error('curated ollama catalog is empty');
- }
- const coder = spec.featuredCoderId ? byId(spec.featuredCoderId) : undefined;
+ const coder = spec.featuredIds
+ .map(byId)
+ .find((entry) => entry && entry.id !== primary?.id && fits(entry, memoryGb));
const secondary =
- coder && coder.id !== fallback.id && (memoryGb <= 0 || fits(coder, memoryGb)) ? coder : null;
-
- return { primary: fallback, secondary, reason, appleSilicon, memoryGb };
+ primary && coder && coder.id !== primary.id && fits(coder, memoryGb) ? coder : null;
+ return { primary, secondary, reason, appleSilicon, memoryGb };
}
-/** 外面只露 1–2 条:主推 + 内存够时的编程备选。 */
+/** 推荐区只展示有依据且内存适配的选择,允许为空。 */
export function pickFeaturedOllamaModels(
input: LocalModelRecommendInput,
remote?: unknown,
diff --git a/apps/desktop/src/shared/ollamaCuratedCatalog.json b/apps/desktop/src/shared/ollamaCuratedCatalog.json
deleted file mode 100644
index 419d68b81c..0000000000
--- a/apps/desktop/src/shared/ollamaCuratedCatalog.json
+++ /dev/null
@@ -1,99 +0,0 @@
-{
- "version": 1,
- "qwen38": {
- "id": "qwen38-27b",
- "name": "Qwen3.8 27B",
- "aliases": ["qwen", "qwen3.8", "qwen3", "tongyi", "qwq", "通义", "通義", "千问", "千問"],
- "mxfp8": {
- "libraryName": "qwen3.8:27b-mxfp8",
- "sizeBytes": 34359738368,
- "minUnifiedMemoryGb": 64,
- "appleSiliconOnly": true
- },
- "mlx": {
- "libraryName": "qwen3.8:27b-mlx",
- "sizeBytes": 19327352832,
- "minUnifiedMemoryGb": 32,
- "appleSiliconOnly": true
- },
- "generic": {
- "libraryName": "qwen3.8:27b",
- "sizeBytes": 19327352832,
- "minUnifiedMemoryGb": 32,
- "appleSiliconOnly": false
- }
- },
- "featuredIds": ["qwen38-27b", "gpt-oss-20b"],
- "featuredCoderId": "ornith15-35b",
- "models": [
- {
- "id": "gpt-oss-20b",
- "name": "gpt-oss 20B",
- "libraryName": "gpt-oss:20b",
- "aliases": ["gpt", "openai", "oss", "gpt-oss"],
- "sizeBytes": 15032385536,
- "minUnifiedMemoryGb": 16
- },
- {
- "id": "gemma4-e2b",
- "name": "Gemma 4 E2B",
- "libraryName": "gemma4:e2b",
- "appleLibraryName": "gemma4:e2b-mlx",
- "aliases": ["gemma", "gemma4", "google", "宝石", "寶石"],
- "sizeBytes": 6657199309,
- "minUnifiedMemoryGb": 8
- },
- {
- "id": "gemma4-e4b",
- "name": "Gemma 4 E4B",
- "libraryName": "gemma4:e4b",
- "appleLibraryName": "gemma4:e4b-mlx",
- "aliases": ["gemma", "gemma4", "google", "宝石", "寶石"],
- "sizeBytes": 7730941132,
- "minUnifiedMemoryGb": 12
- },
- {
- "id": "gemma4-12b",
- "name": "Gemma 4 12B",
- "libraryName": "gemma4:12b",
- "appleLibraryName": "gemma4:12b-mlx",
- "aliases": ["gemma", "gemma4", "google", "宝石", "寶石"],
- "sizeBytes": 9126805504,
- "minUnifiedMemoryGb": 16
- },
- {
- "id": "gemma4-31b",
- "name": "Gemma 4 31B",
- "libraryName": "gemma4:31b",
- "appleLibraryName": "gemma4:31b-mlx",
- "aliases": ["gemma", "gemma4", "google", "宝石", "寶石"],
- "sizeBytes": 21474836480,
- "minUnifiedMemoryGb": 32
- },
- {
- "id": "gemma4-26b",
- "name": "Gemma 4 26B",
- "libraryName": "gemma4:26b",
- "appleLibraryName": "gemma4:26b-mlx",
- "aliases": ["gemma", "gemma4", "google", "宝石", "寶石"],
- "sizeBytes": 19327352832,
- "minUnifiedMemoryGb": 32
- },
- {
- "id": "ornith15-35b",
- "name": "Ornith 1.5 35B",
- "libraryName": "hf.co/ornith-ai/Ornith-1.5-35B-A3B-GGUF:Q4_K_M",
- "aliases": ["ornith", "coder", "code", "coding", "agent", "编程", "程式", "コード"],
- "sizeBytes": 23301691187,
- "minUnifiedMemoryGb": 32
- },
- {
- "id": "glm-47-flash",
- "name": "GLM-4.7 Flash",
- "libraryName": "glm-4.7-flash",
- "aliases": ["glm", "flash", "coder", "code", "coding", "zhipu", "智谱", "智譜", "编程", "程式", "コード"],
- "sizeBytes": 20401094656,
- "minUnifiedMemoryGb": 32
- }
- ]
-}
diff --git a/docs/dev-rules/configuration-and-overrides.md b/docs/dev-rules/configuration-and-overrides.md
index 8f2afd16e8..c993ae16a8 100644
--- a/docs/dev-rules/configuration-and-overrides.md
+++ b/docs/dev-rules/configuration-and-overrides.md
@@ -31,6 +31,9 @@ token)与 [`engineering-conventions.md`](engineering-conventions.md)(i18n)
自定义标记,**不把完整默认配置复制进用户配置**。
- 未自定义的用户随版本获得新默认值,已自定义的用户保留自己的选择。
+模型资料的系统层再区分公共默认、供应商默认、供应商实报与服务端明确修正;用户覆盖始终最高。
+发现快照和用户字段分开持久化,详见 [模型资料优先级](../product-rules/model-metadata-precedence.md)。
+
## 3. 默认值演进与迁移
- 默认值变化时,分别说明新用户、未自定义老用户、已自定义老用户的行为。
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
index 62bc2706cb..c385373894 100644
--- a/docs/dev-rules/model-catalog-maintenance.md
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -9,20 +9,24 @@
## 1. 先找数据归属
-| 内容 | 应维护的位置 | 客户端职责 |
-| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
-| 统一模型目录中的名称、窗口、最大输出、推理档位、参考价及默认标记 | `cindy-server` 的 `model-access-server/catalog/providers.json`;若部署配置了 `MODEL_CATALOG_URL`,还需核对那份远程完整快照 | 同步 `packages/model-providers/catalog/model-registry.json` 作为内置兜底,正确消费实际下发值 |
-| Gateway 的实际可用性、路由能力与实价 | Gateway/Server 对应控制面 | 保留实际路由与价格来源,不用 registry 参考价覆盖 Gateway 实价 |
-| 请求协议、SDK 字段兼容、能力透传与 token 计量 | 本仓对应 harness/bridge/host | 根据具体通道能力适配,测试最终请求与用量 |
-| 模型原生协议与兼容判定基准 | Cindy Registry V3 的 `nativeApi` / `nativeApiRules`,客户端内置补全 | 与 Pi 执行配置、Gateway 路由提示分开维护;结合 Harness 请求协议和实际出站协议判定本地桥接与供应商兼容 |
-| Pi 原生模型元数据 | Pi 上游与本仓 `tools/pi/sync-model-catalog.mjs`、`catalog/pi-model-catalog.json` | 保留上游原生字段,区分公共 API 与订阅协议,遵守 `pi-harness.md` |
-| 旧任务的上下文占比 | 客户端历史读取与展示路径 | 正确区分历史快照、当前目录与运行数据;不能用显示特判掩盖源目录错误 |
+| 内容 | 应维护的位置 | 客户端职责 |
+| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
+| 统一模型目录中的名称、窗口、最大输出、推理档位、参考价及默认标记 | `cindy-server` 的 `model-access-server/catalog/providers.json`;若部署配置了 `MODEL_CATALOG_URL`,还需核对那份远程完整快照 | 同步 `packages/model-providers/catalog/model-registry.json` 作为内置兜底,正确消费实际下发值 |
+| Gateway 的实际可用性、路由能力与实价 | Gateway/Server 对应控制面 | 保留实际路由与价格来源,不用 registry 参考价覆盖 Gateway 实价 |
+| 请求协议、SDK 字段兼容、能力透传与 token 计量 | 本仓对应 harness/bridge/host | 根据具体通道能力适配,测试最终请求与用量 |
+| 模型原生协议与兼容判定基准 | Cindy Registry V3 的 `nativeApi` / `nativeApiRules`,客户端内置补全 | 与 Pi 执行配置、Gateway 路由提示分开维护;结合 Harness 请求协议和实际出站协议判定本地桥接与供应商兼容 |
+| Pi 原生模型元数据 | Pi 上游与本仓 `tools/pi/sync-model-catalog.mjs`、`catalog/pi-model-catalog.json` | 保留上游原生字段,区分公共 API 与订阅协议,遵守 `pi-harness.md` |
+| 旧任务的上下文占比 | 客户端历史读取与展示路径 | 正确区分历史快照、当前目录与运行数据;不能用显示特判掩盖源目录错误 |
同一模型在公共 API、订阅、Gateway,以及不同 Agent 下的能力可能不同。先列出实际
`provider + agent + model` 路由,再判断哪些字段共用、哪些需要 `perAgent` 或独立条目。
公共 API 总窗口、Codex 默认工作窗口、可选最大窗口、有效窗口和压缩阈值不是同一个值。
参考价也不等于订阅实际扣费;标准/Fast、缓存读/写、长输入分档需分别核实。
+公共资料维护在 `baseModels[].defaults`;原接入条目以 `modelRef` 引用公共型号,
+`routes[].defaults` 保存供应商默认差异,只有显式 `forceOverrides` 才能纠正供应商实报。
+同一 ID/alias 必须唯一;公共模型不继承供应商价格、地址、凭证或成员资格。
+
## 2. 核对真实发布链路
客户端入口是 `packages/model-providers/src/source.ts` 的 `loadCatalog`,Desktop 由
@@ -43,14 +47,10 @@
### 默认思考深度的归属
-模型的默认深度由当前已接受的 Cindy Registry 条目的 `defaultEffort` 统一决定;
-XD 按精确 provider/model 路由读取同一值,Registry 未声明时按实际支持档位优先选中档,不继承 Gateway 的默认深度。
-维护表内支持中档的型号统一默认中;没有中档时按 high、low、xhigh、max、minimal、ultra 顺序选真实支持档,不新增能力。新任务入口也消费此值,不单独写死 high。`perAgent` 可以收窄可用档位、窗口和 Fast 能力,
-不再决定另一份默认深度;旧文件若缺少模型层默认且 `perAgent.defaultEffort` 的声明
-完全一致,则将该值提升为模型共同默认;声明冲突时统一采用其中最低的深度,避免旧模型
-消失或静默提升开销。模型层显式值始终优先。目标引擎不支持该档时,
-复用共享档位适配规则,不改变模型的默认意图。
-订阅 Registry 已声明可用路由和有效能力时,缺少默认深度不应阻止新模型实体化;从已声明档位补默认,不伪造窗口、路由或思考能力。
+Registry V4 按字段采用「公共默认 → 供应商/运行时默认 → 供应商实报 → 明确 forceOverrides → 用户覆盖」。
+`perAgent` 可声明运行时默认;上游明示的默认优先,缺项才继承。`null` 与空档位保留明确语义;
+实际不支持的默认档按共享规则适配,不增加能力。旧 V1–V3 继续保留历史消费语义。
+完整契约、JSON 示例和用户文件见 [模型资料优先级](../product-rules/model-metadata-precedence.md)。
用户显式保存的选择和正在运行的任务不随目录刷新被覆盖。
Pi 的 `thinkingLevelMap` 是稀疏映射:标准档位省略时仍支持,`null` 才表示不支持;
@@ -96,8 +96,8 @@ JS
服务端明确声明的协议、`null`(待核实)及 retired 则优先。补全不改窗口、价格、档位或成员资格,
也不从 Gateway 的 `wireProtocol` 或 Pi 的 `piApi` 反推原生协议。
-从旧 schema 同步内置基线时,先保存并恢复经核实的 `nativeApi` / `nativeApiRules`,
-按 route 身份对齐;以 V3 格式生成新的递增 revision。此时两份 Registry 不再逐字相等,
+历史 V1–V3 迁移时,先保存并恢复经核实的 `nativeApi` / `nativeApiRules`,
+按 route 身份对齐;当时以 V3 格式生成新的递增 revision。此时两份 Registry 不再逐字相等,
应分别核对业务参数与协议补全差异,不能沿用同 revision 却修改内容。服务端以后可在原文件
补写这些字段,无需再维护第二份配置文件。
@@ -182,7 +182,6 @@ Doubao Seed 2.1 Pro、Qwen3.8 Max、DS4 Flash Vision Exp、HY4 Preview。只设
Kimi 的 XD 默认与公共直连路由分开维护。发布时将这份递增 revision 的 Registry 同步到
Server 目录;不改 Gateway 的价格、成员、上下文与可用性。
-
### 模型名称本地化
中文界面使用经核实的官方中文厂商/系列名;版本号与变体后缀保留原样。
@@ -197,7 +196,6 @@ Server 目录;不改 Gateway 的价格、成员、上下文与可用性。
[月之暗面](https://www.moonshot.cn/)、[深度求索](https://www.deepseek.com/)、
[字节跳动 Seed](https://seed.bytedance.com/zh/seed2)、[豆包](https://www.doubao.com/)。不根据这些页面改变运行协议或能力。
-
### 模型简介本地化
Desktop 模型选择器(含收藏)、旧入口的配置浮层及设置详情统一使用
@@ -224,6 +222,13 @@ Registry 的全部模型及其 routes,防止只翻译当前默认启用的几
但按 2026-09-07 用户更正,界面恢复「兼容模式」、默认关闭,允许用户手动开启。
不新增「支持」协议分类;用户显式开关保持优先。GPT 窗口默认与自动压缩修复不回退。
+### 本地模型目录
+
+本地模型筛选与更新遵循 [`local-model-selection.md`](../product-rules/local-model-selection.md)。
+Server 维护 Registry V4 的 `localModels`,本仓 `model-registry.json` 仅作离线副本;
+不得重新增加独立的硬编码推荐名单。更新时协调完整 Registry revision 和服务端覆盖源,
+保持旧客户端的版本投影与显式空推荐语义。
+
### 原生缓存与简略列表的字段完整性(2026-09-07)
diff --git a/docs/product-rules/local-model-selection.md b/docs/product-rules/local-model-selection.md
new file mode 100644
index 0000000000..28f53a5ee3
--- /dev/null
+++ b/docs/product-rules/local-model-selection.md
@@ -0,0 +1,130 @@
+# 本地模型筛选标准
+
+适用于内置本地模型目录、推荐顺序、内存门槛与推荐文案。2026-09-05 确认:
+只在**能力、速度、实际运行内存**三个维度之间选取有明确优势的模型。
+
+## 长期筛选规则
+
+1. **按可用内存划档,不按品牌凑名单。** 参数量用于描述架构,不能替代内存;
+ MoE 激活参数少也不代表全部权重占用小。新发布、知名品牌、视觉或编程标签本身
+ 都不构成增加推荐位的理由。
+2. **只保留有优势的取舍。** 同一内存档最多保留一个能力选择和一个速度选择;
+ 若同一个模型兼得,则只留一个。若另一个模型能力不差、速度不慢、内存不多,
+ 且至少一项有可复现的实质优势,移除被全面超过的推荐。差异落在测量噪声内时
+ 不宣布胜出,不通过任意加权分数制造冠军。
+3. **能力优先采用独立、公开方法的评测。** 记录榜单版本、原始页面、评测日期、
+ 推理档位及测试设置。厂商自报或榜单 estimated 值单独标明,仅用于候选筛选;
+ 不与实测值混为同等证据。不混用不同版本的综合指数,不平均无关榜单分数。
+4. **比较单位是具体配置。** 模型版本、权重/量化、思考设置、上下文、推理引擎和
+ 版本缺一不可。原模型/API 的成绩不能直接贴到本地 4-bit 包装上;高思考档的
+ 能力分数不能与关闭思考的速度拼成一条“实测最佳”。
+5. **速度必须来自对应硬件实测。** 同机器、同运行时、同输入/输出长度与思考预算,
+ 报告首字延迟、预填充速度、输出速度及完成整个请求的时间;区分冷启动和热运行,
+ 重复测量并报告中位数、波动和 swap 情况。API tokens/s 不代表 Mac tokens/s。
+6. **内存使用运行峰值。** 区分下载大小、加载峰值、稳定运行峰值;记录上下文长度、
+ KV cache 精度、并发数及测量口径。仅进程 RSS 或 MLX allocator 数值不能冒充
+ 系统总占用。门槛须为操作系统和 Cindy 留空间;不能把“偶尔装得下”写成“适合”。
+7. **证据不足允许空位。** 候选可以在小规模候选目录中供手动选择,但不自动进入
+ 推荐区,不因 RAM 足够、没有其他推荐或内存未知而晋升。正式增加推荐前应补齐
+ 对应配置的能力依据和本机速度/内存比较。当前保留推荐的证据缺口也要公开记录。
+8. **每次更新同时写入取舍记录。** 新模型应替换它胜出的旧位置,而非不断追加。
+ 研究中的候选只保留有希望填补空位或替换现有模型的少数项;确认无优势后退出目录。
+
+## 当前配置与证据边界(2026-09-05)
+
+本轮由 9 个内置条目收敛到 7 个逻辑模型。正式推荐保留 Qwen3.8 27B;其他
+6 个只是待比较候选。5 个选择位置中,低内存中档和速度档各保留两名候选等待比较。
+“保留推荐”是当前证据下的产品选择,不表示已完成所有量化与硬件组合的 Pareto 证明。
+
+| 位置 | 模型 | 当前处理 | 仍需补齐的证据 |
+| -------- | -------------------------------------------- | --------------------- | --------------------------------------------------------- |
+| 更低内存 | Qwen3.5 4B | 候选 | 同条件能力、速度、峰值内存 |
+| 低内存 | Qwen3.5 9B / Gemma 4 12B | 两名候选,未决出胜者 | 同硬件、同量化条件的三维比较 |
+| 能力 | Qwen3.8 27B | 保留能力推荐 | 本地量化对能力的影响、长上下文峰值;不宣称所有 Mac 上最优 |
+| 速度 | Qwen3.6 35B A3B / Nemotron 3.5 Lightning 30B | 两名候选,未决出胜者 | 同一台 Mac 上的完整比较 |
+| 大内存 | Qwen3.8 Flash-Next | 仅 Apple Silicon 候选 | Ollama 对应标签的加载/运行峰值及能力损失 |
+
+移出内置目录:GPT-OSS 20B、Gemma 4 E2B/E4B/26B/31B、Ornith 1.5 35B、
+GLM-4.7-Flash。本轮未证明它们相对上述候选有独立的三维优势,不为这些条目另设推荐位;
+这不等于已经用完整同机实验证明它们都被支配。Laguna XS 2.1、Muse Glimmer 30B
+也不因新品或厂商宣传进入目录。
+
+### 证据快照
+
+- [Artificial Analysis Qwen3.8 27B xhigh](https://artificialanalysis.ai/models/qwen3-8-27b):
+ Intelligence Index **v4.2 = 42**,是保留能力推荐的独立依据。该配置是 xhigh,
+ 不是本地 MLX/MXFP8 已复现的成绩。
+- [Qwen3.8 Flash-Next](https://artificialanalysis.ai/models/qwen3-8-flash-next) 的 v4.2
+ **46**、[Qwen3.6 35B A3B](https://artificialanalysis.ai/models/qwen3-6-35b-a3b) 的
+ **26**在本轮查询中标为 estimated;仅用于候选判断,不据此宣称已实测击败 27B。
+- [M4 Air 32GB 对比原始项目](https://github.com/jordanilchev/local-qwen):Ollama 0.32.14,
+ 关闭思考、短输入、最多 200 输出 tokens;Qwen3.6 Q4_K_M 为 29.9 tokens/s,
+ Qwen3.8 27B NVFP4 为 17.2 tokens/s。量化不同且未提供完整内存峰值,
+ 只能支持速度候选资格。
+- [Nemotron 长上下文测试](https://omarshabab.com/local-llm-256k-leaderboard/) 使用
+ M3 Ultra 512GB 和 MLX;不能与上述 M4 Air 数字直接排出快慢。
+- [Flash-Next 4-bit 测试](https://huggingface.co/rapid-mlx/Qwen3.8-Flash-Next-4bit)
+ 使用 M3 Ultra 256GB、Rapid,报告加载峰值约 148.1GB;不能推断 Ollama 在 128GB
+ 上适合日用。本目录的 192GB 是保守候选提示,尚未由对应 Ollama 标签验证。
+
+### 包装与内存提示
+
+标签和下载字节于 2026-09-05 从 Ollama 官方 registry 的 manifest 核对,下载大小
+为 `layers[].size` 之和。目录中各 `variants[].sizeBytes` 按具体包装分别记录,不能混用。
+标签可变;后续更新应重新读取 manifest 并记录摘要。大小仅用于下载提示。
+
+| 模型 | 通用标签 | Apple Silicon 标签 | 内存提示 GB |
+| ---------------------- | ---------------------------- | --------------------------------------- | ------------- |
+| Qwen3.5 4B | `qwen3.5:4b-q4_K_M` | `qwen3.5:4b-mlx` | 8 |
+| Qwen3.5 9B | `qwen3.5:9b-q4_K_M` | `qwen3.5:9b-mlx` | 16 |
+| Gemma 4 12B | `gemma4:12b-it-q4_K_M` | `gemma4:12b-mlx` | 16 |
+| Qwen3.8 27B | `qwen3.8:27b` | `qwen3.8:27b-mlx` / `qwen3.8:27b-mxfp8` | 32 / MXFP8 64 |
+| Qwen3.6 35B A3B | `qwen3.6:35b-a3b-q4_K_M` | `qwen3.6:35b-mlx` | 32 |
+| Nemotron 3.5 Lightning | `nemotron-3.5-lightning:30b` | `nemotron-3.5-lightning:30b-mlx` | 48 |
+| Qwen3.8 Flash-Next | 未纳入通用包装 | `qwen3.8-flash-next:125b-mlx` | 192 |
+
+查询入口为 `https://registry.ollama.ai/v2/library/<模型家族>/manifests/<标签>`。
+以上内存提示全部是当前配置的估算门槛,不是测得的最低运行内存,不保证任意上下文可用。
+Qwen27 的 32GB MLX、64GB MXFP8 选择沿用现有行为,不把更大包装描述成已经证实更优。
+非 Apple 主机的普通 RAM 也不等于 GPU 显存;内存适配不是 GPU 性能认证。
+
+## 实现边界与以后更新
+
+- 数据正本:Server 的 `model-access-server/catalog/providers.json` 中
+ `modelRegistry.localModels`;客户端离线副本位于
+ `packages/model-providers/catalog/model-registry.json` 的 `localModels`。
+ 算法入口仍为 `apps/desktop/src/shared/localModelRuntime.ts`。
+ `featuredIds` 按能力、速度顺序列推荐;`models` 中的候选不会自动补位。
+- 当前 Apple Silicon 32GB 起保留 Qwen27 推荐,64GB 起沿用 MXFP8;低于门槛或
+ 内存未知返回空推荐。Flash-Next 仅出现在 Apple Silicon 候选目录。
+- 新用户看到更新后的目录;未修改默认值的老用户也看到新目录,但不自动安装或切换模型。
+ 已手动配置的用户保留选择;目录淘汰不卸载模型、不删除供应商、不改变任务使用的模型。
+ 用户仍可通过手动标签拉取目录外模型。
+- 修改条目时附上:日期、精确模型/量化/思考设置、榜单及版本、是否 estimated、
+ 硬件和引擎版本、上下文和缓存设置、速度/延迟/完整耗时、加载与运行峰值、原始日志链接、
+ 被替换条目和三维取舍理由。缺项写“未验证”,不能补猜测数字。
+- 配套验证须覆盖:低内存/未知内存空推荐、推荐名单不得被目录兜底绕过、平台包装过滤、
+ 推荐变化不影响手动拉取或已安装模型。文案避免“最强”“最适合你”等超出证据的结论。
+
+## 服务端下发与发布(2026-09-08)
+
+- 复用现有匿名目录接口,客户端请求 `registrySchemaVersion=4`,本地域为
+ `modelRegistry.localModels = { version: 1, models, featuredIds }`。共享 Registry
+ 的 `updatedAt`、校验、缓存与刷新事件,不另建请求或持久化层。
+- 服务端下发名称、搜索别名、具体包装、内存提示、五语简介、证据链接及推荐顺序。
+ 客户端继续负责平台/内存适配、用户选择、下载与执行。未知内存不自动推荐。
+ 普通包装可通过目录新增;新推理协议仍需客户端实现。`qwen-xhigh` 只允许当前已支持
+ 的三个 Qwen3.8 27B 标签,远程数据不能提供命令、路径或任意下载 URL。
+- 明确的空 `models` / `featuredIds` 分别撤下目录 / 推荐;字段缺失表示旧服务端,
+ 使用随包本地域。网络失败、非法数据和 revision 冲突沿用已有合法快照。
+- 发布顺序为服务端先行、客户端随后。旧客户端默认收到 Registry V2;显式请求
+ V1/V2/V3 时剥离新字段。各响应版本有独立内容 ETag,不能跨版本误命中 304。
+- 每次先在 Server 正本更新取舍记录和本地域,增加整个 Registry 的 `updatedAt`,
+ 再把完整 Registry(含 `baseModels` 与 `modelRef`)同步到客户端离线副本,核对同 revision、同内容。
+ 本次将客户端已维护的型号、协议资料和 medium 优先的默认思考策略同步到 Server,两个随包 Registry 完全一致;这不改写用户显式档位或供应商实报默认档。
+ 后续服务端 revision 必须高于已发布版本,禁止只复制本地域或使用相同 revision 发布不同内容。
+- 本地与云端接入可用 `modelRef` 引用同一公共型号;量化包装、内存与推荐证据独立留在本地域。
+ 用户文件可覆盖推荐及单项资料,优先级见 [模型资料优先级](model-metadata-precedence.md)。
+- 若生产配置了 `MODEL_CATALOG_URL`,还须同步该覆盖源;只修改制品内置目录不能证明
+ 线上生效。部署后核对 V4 响应、旧版响应与新客户端刷新;离线首次启动核对随包兜底。
+- 目录撤下或调整顺序不卸载、切换用户模型,也不修改已有供应商和执行中的配置。
diff --git a/docs/product-rules/model-metadata-precedence.md b/docs/product-rules/model-metadata-precedence.md
new file mode 100644
index 0000000000..950bb3e193
--- /dev/null
+++ b/docs/product-rules/model-metadata-precedence.md
@@ -0,0 +1,93 @@
+# 模型公共资料、供应商资料与用户覆盖
+
+裁决日期:2026-09-08。模型资料按字段合并,最终采用以下优先级(低到高):
+
+1. `modelRegistry.baseModels[].defaults`:模型公共资料。
+2. 接入条目及 `routes[].defaults`,再叠加该条目的 `perAgent`:供应商、运行时默认资料。
+3. 供应商接口明确返回的资料。没返回的字段继续继承默认;不能把客户端合成值当成供应商事实。
+4. 匹配路由的 `forceOverrides`:经核实必须纠正的字段,必须填写 `overrideReason`,可填写 `overrideVerifiedAt`(日期)。普通默认值不能暗中强制覆盖供应商。
+5. 用户显式配置:自定义供应商表单中的字段,以及本机 `model-catalog-overrides.json`。文件中的公共型号补丁先应用,具体供应商/运行时补丁最后应用。
+
+字段缺失表示继承;`false` 表示明确关闭;数组整体替换,`efforts: []` 表示无可调思考档;`defaultEffort: null` 表示无指定默认档。最终默认档必须适配实际支持的档位,不能凭默认值增加能力。
+
+## 数据结构
+
+```json
+{
+ "schemaVersion": 4,
+ "updatedAt": "2026-09-08T07:00:00.000Z",
+ "baseModels": [
+ {
+ "id": "maker/model",
+ "aliases": ["model"],
+ "defaults": { "name": "Model", "contextWindow": 128000 }
+ }
+ ],
+ "models": [
+ {
+ "id": "existing-entry-id",
+ "name": "Model",
+ "modelRef": "maker/model",
+ "routes": [
+ {
+ "providerId": "supplier",
+ "modelId": "model",
+ "agents": ["codex"],
+ "defaults": { "contextWindow": 64000 },
+ "forceOverrides": { "maxOutputTokens": 8000 },
+ "overrideReason": "已核实供应商错误报告输出上限",
+ "overrideVerifiedAt": "2026-09-08"
+ }
+ ]
+ }
+ ]
+}
+```
+
+公共字段范围是名称、说明、分组、上下文、最大输出、思考档位、默认档、Fast 与图片输入能力。Fast 通常是供应商能力,应放在路由默认值中。价格、余额、账号可用性、模型成员、协议、地址和凭证不通过公共模型继承。参考价格继续绑定原来的供应商路由,实价仍来自计费控制面。
+
+`modelRef` 只引用明确的公共型号;aliases 必须在整表唯一。新供应商没有专属条目时,仅在精确公共 ID 或明确 alias 匹配后继承公共资料。不剥任意前缀、不用模糊名称猜型号,也不继承另一供应商的强制修正。订阅桥接已有的 ID 归一规则继续适用。
+
+保留现有 entry、provider、上游 model ID 和 `[1m]` 变体。一个模型可以同时有本地包装与云端接入,共用 `modelRef`;本地量化标签、包装体积、运行内存、平台限制、推荐证据仍留在 `localModels`。不同权重或不同版本不能仅因名字相似而共用型号。
+
+## 用户文件与恢复默认
+
+文件位于当前账号的用户数据目录,沿用已有 `model-catalog-overrides.json`,不上传到服务器。以下示例只保存用户修改的字段:
+
+```json
+{
+ "version": 1,
+ "baseModels": { "maker/model": { "name": "我的显示名" } },
+ "patches": {
+ "supplier:model": {
+ "base": { "contextWindow": 32000, "supportsImageInput": false },
+ "perAgent": { "pi": { "defaultEffort": null } }
+ }
+ },
+ "localModels": {
+ "featuredIds": [],
+ "patches": { "qwen38-27b": { "name": "我的本地模型" } }
+ }
+}
+```
+
+`baseModels` 是按公共 ID 的稀疏补丁;`patches` 支持已有订阅、Cindy AI、自定义供应商模型及 Pi。补丁不能凭空增加账号可用模型,尚未出现的条目静置。原有 `additions` 仍只适用于允许实体化的订阅根,不开放 Gateway 伪造。退役条目仍需完整合法 addition 才能复活。
+
+键中的供应商段使用 `encodeURIComponent` 编码,模型段保持原文。例如旧自定义 xAI 的运行时 ID 是 `custom:xai`,对应键为 `custom%3Axai:grok-model`;`xai:grok-model` 仍指内置 xAI,`custom:xai:grok-model` 仍指供应商 `custom` 的模型 `xai:grok-model`,三者不混用。
+
+`localModels` 支持 `patches`、完整 `additions`、`removedIds`、`featuredIds`;空推荐数组明确不推荐任何模型。名称和包装仍需通过本地域校验,不能下发命令、路径或下载 URL。删除补丁或对应字段就是恢复继承,远端刷新不会写回或删除这些用户字段。
+
+自定义供应商的接口结果单独保存在 `discoveredMetadata`;表单只持久化用户显式设置。旧数据缺少来源标记时保守保留旧名称和窗口,不猜测用户意图。刷新供应商信息会更新发现快照,不把发现值转成用户 override。
+从预设新建时只保存 `catalogPresetId` 引用;模型默认资料读取当前目录,接口结果仍单独记录。
+预设地址与协议仍按创建时配置保存,只有它们与当前预设一致时才继承该供应商的默认资料;用户换端点后停止继承。
+旧连接已有的显式快照不自动转为继承。官方 API 入口没有同名服务端预设时,仍通过精确型号匹配读取公共资料;不把入口中的提示值保存成用户覆盖。
+
+## 发布、兼容与验证
+
+Server `catalog/providers.json` 是数据正本;客户端 `catalog/model-registry.json` 是同 revision、同内容的离线副本。`baseModels`、模型引用和本地域必须随整个 Registry 一起校验、发布和同步,禁止只复制子域造成悬空引用。坏快照、网络失败、回退 revision 和同 revision 冲突沿用上一份合法快照。
+
+复用当前目录接口与 Registry V4 协商,不增加请求或数据库表。旧 V1/V2/V3 客户端收到展开后的旧字段;不同资料的多条路由在兼容响应中拆成独立条目,保留上游 ID,额外条目使用派生目录 ID。旧协议不支持的公共引用、覆盖指令与图片字段被移除,空默认以缺省表达。
+
+供应商总容量与客户端工作预算分开:既有 GPT 272K 工作预算继续保留,实际容量放在 `contextWindowMax`;用户显式窗口覆盖仍优先。协议和实际执行能力门禁继续由运行时负责,元数据不能解锁未实现协议或伪造可售性。
+
+验收至少覆盖缺字段继承、供应商优先、force 修正、用户最高、显式 false/null/空数组、未知供应商公共识别、刷新与保存、旧版解析、离线与坏快照回退。模型推荐标准另见 [本地模型筛选](local-model-selection.md),仍只按能力、速度和实际运行内存筛选。
diff --git a/packages/model-providers/catalog/model-registry.json b/packages/model-providers/catalog/model-registry.json
index 74589b28ba..5fe4c7d73d 100644
--- a/packages/model-providers/catalog/model-registry.json
+++ b/packages/model-providers/catalog/model-registry.json
@@ -1,35 +1,15 @@
{
- "schemaVersion": 3,
- "updatedAt": "2026-09-07T08:34:10.338Z",
+ "schemaVersion": 4,
+ "updatedAt": "2026-09-08T07:58:08.918Z",
"models": [
{
"id": "openai/gpt-5.6-sol",
"name": "GPT-5.6-Sol",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.6-Sol for coding tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 18,
- "supportsFastMode": true,
"perAgent": {
"codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ],
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"],
"contextWindow": 272000
},
"claude-code": {
@@ -40,10 +20,7 @@
{
"providerId": "openai",
"modelId": "gpt-5.6-sol",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -107,35 +84,29 @@
"verifiedAt": "2026-08-28"
}
}
- ]
+ ],
+ "defaults": {
+ "description": "GPT-5.6-Sol for coding tasks",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-sol"
},
{
"id": "openai/gpt-5.6-sol[1m]",
"name": "GPT-5.6-Sol (1M · Higher usage)",
"status": "deprecated",
- "group": "gpt",
- "description": "Explicit 1M context opt-in; inputs above 272K use higher long-context rates for the entire request",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 18,
- "supportsFastMode": true,
"routes": [
{
"providerId": "openai",
"modelId": "gpt-5.6-sol",
- "agents": [
- "claude-code"
- ],
+ "agents": ["claude-code"],
"referencePrices": [
{
"currency": "USD",
@@ -199,86 +170,60 @@
"verifiedAt": "2026-08-28"
}
}
- ]
+ ],
+ "defaults": {
+ "name": "GPT-5.6-Sol (1M · Higher usage)",
+ "description": "Explicit 1M context opt-in; inputs above 272K use higher long-context rates for the entire request",
+ "group": "gpt",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "supportsFastMode": true
+ }
}
],
"nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-sol",
"defaultEnabled": false
},
{
"id": "xd/gpt-5.6-sol",
"name": "GPT-5.6-Sol",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.6-Sol for coding tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 18,
- "supportsFastMode": true,
"perAgent": {
"claude-code": {
"supportsFastMode": false
},
"codex": {
"contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
}
},
"routes": [
{
"providerId": "xd",
"modelId": "gpt-5.6-sol",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.6-Sol for coding tasks",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-sol"
},
{
"id": "openai/gpt-5.6-terra",
"name": "GPT-5.6-Terra",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.6-Terra for coding tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 19,
- "supportsFastMode": true,
"perAgent": {
"codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ],
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"],
"contextWindow": 272000
},
"claude-code": {
@@ -289,10 +234,7 @@
{
"providerId": "openai",
"modelId": "gpt-5.6-terra",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -356,81 +298,56 @@
"verifiedAt": "2026-08-07"
}
}
- ]
+ ],
+ "defaults": {
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-terra"
},
{
"id": "xd/gpt-5.6-terra",
"name": "GPT-5.6-Terra",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.6-Terra for coding tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 19,
- "supportsFastMode": true,
"perAgent": {
"claude-code": {
"supportsFastMode": false
},
"codex": {
"contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
}
},
"routes": [
{
"providerId": "xd",
"modelId": "gpt-5.6-terra",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-terra"
},
{
"id": "openai/gpt-5.6-luna",
"name": "GPT-5.6-Luna",
"status": "active",
- "group": "gpt",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 17,
"routes": [
{
"providerId": "openai",
"modelId": "gpt-5.6-luna",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -494,10 +411,18 @@
"verifiedAt": "2026-08-07"
}
}
- ]
+ ],
+ "defaults": {
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
}
],
"nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-luna",
"perAgent": {
"codex": {
"contextWindow": 272000
@@ -511,17 +436,6 @@
"id": "xd/gpt-5.6-luna",
"name": "GPT-5.6-Luna",
"status": "active",
- "group": "gpt",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 17,
"perAgent": {
"codex": {
@@ -532,31 +446,24 @@
{
"providerId": "xd",
"modelId": "gpt-5.6-luna",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-luna"
},
{
"id": "openai/gpt-5.5",
"name": "GPT-5.5",
"status": "active",
- "group": "gpt",
- "description": "OpenAI Codex (GPT-5.5) for coding tasks",
- "contextWindow": 272000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 20,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"codex": {
@@ -567,10 +474,7 @@
{
"providerId": "openai",
"modelId": "gpt-5.5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -600,28 +504,23 @@
"verifiedAt": "2026-08-01"
}
}
- ]
+ ],
+ "defaults": {
+ "description": "OpenAI Codex (GPT-5.5) for coding tasks",
+ "group": "gpt",
+ "contextWindow": 272000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.5"
},
{
"id": "xd/gpt-5.5",
"name": "GPT-5.5",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.5 for coding tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 20,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"claude-code": {
@@ -635,30 +534,23 @@
{
"providerId": "xd",
"modelId": "gpt-5.5",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.5 for coding tasks",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.5"
},
{
"id": "openai/gpt-5.4",
"name": "GPT-5.4",
"status": "active",
- "group": "gpt",
- "description": "OpenAI Codex (GPT-5.4) for coding tasks",
- "contextWindow": 272000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
"sortOrder": 21,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"codex": {
@@ -669,10 +561,7 @@
{
"providerId": "openai",
"modelId": "gpt-5.4",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -702,28 +591,23 @@
"verifiedAt": "2026-08-01"
}
}
- ]
+ ],
+ "defaults": {
+ "description": "OpenAI Codex (GPT-5.4) for coding tasks",
+ "group": "gpt",
+ "contextWindow": 272000,
+ "supportsFastMode": true
+ }
}
],
"nativeApi": "openai-responses",
- "defaultEffort": "medium"
+ "modelRef": "openai/gpt-5.4"
},
{
"id": "xd/gpt-5.4",
"name": "GPT-5.4",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.4 for coding tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
"sortOrder": 21,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"claude-code": {
@@ -737,31 +621,23 @@
{
"providerId": "xd",
"modelId": "gpt-5.4",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.4 for coding tasks",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "supportsFastMode": true
+ }
}
],
"nativeApi": "openai-responses",
- "defaultEffort": "medium"
+ "modelRef": "openai/gpt-5.4"
},
{
"id": "openai/gpt-5.4-mini",
"name": "GPT-5.4-Mini",
"status": "active",
- "group": "gpt",
- "description": "Faster, lighter Codex variant — speed-optimized for quick edits",
- "contextWindow": 272000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
"sortOrder": 22,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"claude-code": {
@@ -775,10 +651,7 @@
{
"providerId": "openai",
"modelId": "gpt-5.4-mini",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -793,28 +666,23 @@
"verifiedAt": "2026-08-01"
}
}
- ]
+ ],
+ "defaults": {
+ "description": "Faster, lighter Codex variant — speed-optimized for quick edits",
+ "group": "gpt",
+ "contextWindow": 272000,
+ "supportsFastMode": true
+ }
}
],
"nativeApi": "openai-responses",
- "defaultEffort": "medium"
+ "modelRef": "openai/gpt-5.4-mini"
},
{
"id": "xd/gpt-5.4-mini",
"name": "GPT-5.4-Mini",
"status": "active",
- "group": "gpt",
- "description": "GPT-5.4-Mini for coding tasks",
- "contextWindow": 400000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
"sortOrder": 22,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"claude-code": {
@@ -828,107 +696,73 @@
{
"providerId": "xd",
"modelId": "gpt-5.4-mini",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.4-Mini for coding tasks",
+ "group": "gpt",
+ "contextWindow": 400000,
+ "supportsFastMode": true
+ }
}
],
"nativeApi": "openai-responses",
- "defaultEffort": "medium"
+ "modelRef": "openai/gpt-5.4-mini"
},
{
"id": "openai/gpt-5.4-pro",
"name": "GPT-5.4 Pro",
"status": "active",
- "group": "gpt",
- "description": "OpenAI GPT-5.4 Pro for demanding reasoning tasks",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
"sortOrder": 23,
"defaultEnabled": false,
"routes": [
{
"providerId": "openai",
"modelId": "gpt-5.4-pro",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.4-pro"
},
{
"id": "openai/gpt-5.5-pro",
"name": "GPT-5.5 Pro",
"status": "active",
- "group": "gpt",
- "description": "OpenAI GPT-5.5 Pro for precise, high-quality reasoning",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
"sortOrder": 24,
"defaultEnabled": false,
"routes": [
{
"providerId": "openai",
"modelId": "gpt-5.5-pro",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.5-pro"
},
{
"id": "openai/gpt-5.6-cyber",
"name": "GPT-5.6 Cyber",
"status": "active",
- "group": "gpt",
- "description": "OpenAI cyber security reasoning model; access requires approval",
- "contextWindow": 400000,
- "maxOutputTokens": 128000,
"sortOrder": 25,
"defaultEnabled": false,
"routes": [
{
"providerId": "openai",
"modelId": "gpt-5.6-cyber",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-cyber"
},
{
"id": "openai/gpt-6-astra",
"name": "GPT-6 Astra",
"status": "active",
- "group": "gpt",
- "description": "OpenAI GPT-6 Astra for complex reasoning, coding, computer use, research, and document creation",
- "contextWindow": 1050000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"perAgent": {
"codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ],
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"],
"contextWindow": 272000
},
"claude-code": {
@@ -939,10 +773,7 @@
{
"providerId": "openai",
"modelId": "gpt-6-astra",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1036,66 +867,39 @@
},
"minInputTokens": 272001
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": true
+ }
}
],
- "supportsFastMode": true,
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-6-astra"
},
{
"id": "anthropic/claude-fable-5-1",
"name": "Fable 5.1",
"status": "active",
- "group": "anthropic",
- "description": "Claude Fable 5.1 for long-running agentic coding and research",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-fable-5-1",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-fable-5-1"
},
{
"id": "anthropic/claude-fable-5",
"name": "Fable 5",
"status": "active",
- "group": "anthropic",
- "description": "Most capable, supports xhigh effort",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 1,
- "supportsFastMode": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-fable-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1112,41 +916,32 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-fable-5",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-fable-5"
},
{
"id": "anthropic/claude-mythos-5",
"name": "Mythos 5",
"status": "active",
- "group": "anthropic",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-mythos-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1166,34 +961,19 @@
]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-mythos-5"
},
{
"id": "anthropic/claude-opus-5",
"name": "Opus 5",
"status": "active",
- "group": "anthropic",
- "description": "Latest Opus for ambitious work",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 0,
- "supportsFastMode": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-opus-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1225,44 +1005,33 @@
"verifiedAt": "2026-08-02"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-opus-5",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-opus-5"
},
{
"id": "anthropic/claude-opus-4-8",
"name": "Opus 4.8",
"status": "active",
- "group": "anthropic",
- "description": "Most capable, supports xhigh effort",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 2,
- "supportsFastMode": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-opus-4-8",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1294,45 +1063,34 @@
"verifiedAt": "2026-08-02"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-opus-4-8",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-opus-4-8"
},
{
"id": "anthropic/claude-opus-4-7",
"name": "Opus 4.7",
"status": "active",
- "group": "anthropic",
- "description": "Most capable, supports xhigh effort",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 3,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-opus-4-7",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1349,44 +1107,34 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-opus-4-7",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-opus-4-7"
},
{
"id": "anthropic/claude-opus-4-6",
"name": "Opus 4.6",
"status": "active",
- "group": "anthropic",
- "description": "Most capable for ambitious work",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 4,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-opus-4-6",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1403,43 +1151,34 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-opus-4-6",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-opus-4-6"
},
{
"id": "anthropic/claude-opus-4-5",
"name": "Opus 4.5",
"status": "active",
- "group": "anthropic",
- "description": "Earlier Opus generation",
- "contextWindow": 200000,
- "maxOutputTokens": 64000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 5,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-opus-4-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1456,44 +1195,33 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-opus-4-5",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-opus-4-5"
},
{
"id": "anthropic/claude-sonnet-5",
"name": "Sonnet 5",
"status": "active",
- "group": "anthropic",
- "description": "Latest Sonnet — fast and highly capable",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 6,
- "supportsFastMode": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-sonnet-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1510,44 +1238,34 @@
"verifiedAt": "2026-08-12"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-sonnet-5",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-sonnet-5"
},
{
"id": "anthropic/claude-sonnet-4-6",
"name": "Sonnet 4.6",
"status": "active",
- "group": "anthropic",
- "description": "Most efficient for everyday tasks",
- "contextWindow": 1000000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 7,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-sonnet-4-6",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1564,38 +1282,34 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-sonnet-4-6",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-sonnet-4-6"
},
{
"id": "anthropic/claude-sonnet-4-5",
"name": "Sonnet 4.5",
"status": "active",
- "group": "anthropic",
- "description": "Earlier Sonnet generation",
- "contextWindow": 200000,
- "maxOutputTokens": 64000,
- "efforts": [],
"sortOrder": 8,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-sonnet-4-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1612,38 +1326,34 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-sonnet-4-5",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-sonnet-4-5"
},
{
"id": "anthropic/claude-haiku-4-5",
"name": "Haiku 4.5",
"status": "active",
- "group": "anthropic",
- "description": "Fastest for quick answers",
- "contextWindow": 200000,
- "maxOutputTokens": 64000,
- "efforts": [],
"sortOrder": 9,
- "supportsFastMode": false,
"defaultEnabled": true,
"routes": [
{
"providerId": "anthropic",
"modelId": "claude-haiku-4-5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1660,41 +1370,33 @@
"verifiedAt": "2026-07-31"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "claude-haiku-4-5",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "anthropic/claude-haiku-4-5"
},
{
"id": "xai/grok-4.6",
"name": "Grok 4.6",
"status": "active",
- "group": "grok",
- "description": "xAI Grok 4.6 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)",
- "contextWindow": 500000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 48,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.6",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1727,30 +1429,19 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.6"
},
{
"id": "xai/grok-4.5",
"name": "Grok 4.5",
"status": "active",
- "group": "grok",
- "description": "xAI Grok 4.5 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)",
- "contextWindow": 500000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 49,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.5",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1783,39 +1474,24 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.5"
},
{
"id": "xai/grok-4.3",
"name": "Grok 4.3",
"status": "active",
- "group": "grok",
- "description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 51,
"perAgent": {
"codex": {
- "efforts": [
- "low",
- "medium",
- "high"
- ]
+ "efforts": ["low", "medium", "high"]
}
},
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.3",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1848,26 +1524,20 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.3"
},
{
"id": "xai/grok-build-0.1",
"name": "Grok Build 0.1",
"status": "active",
- "group": "grok",
- "description": "xAI agentic coding model,256k 上下文(SuperGrok 订阅直连)",
- "contextWindow": 256000,
- "efforts": [],
"sortOrder": 50,
"defaultEnabled": false,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-build-0.1",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1900,32 +1570,20 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-build-0.1"
},
{
"id": "xai/grok-4.20-multi-agent-0309",
"name": "Grok 4.20 Multi-Agent",
"status": "active",
- "group": "grok",
- "description": "xAI Grok 4.20 multi-agent model,1M 上下文(SuperGrok 订阅直连)",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 52,
"defaultEnabled": false,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.20-multi-agent-0309",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -1958,26 +1616,20 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.20-multi-agent-0309"
},
{
"id": "xai/grok-4.20-0309-reasoning",
"name": "Grok 4.20 Reasoning",
"status": "active",
- "group": "grok",
- "description": "xAI Grok 4.20 reasoning model,1M 上下文(SuperGrok 订阅直连)",
- "contextWindow": 1000000,
- "efforts": [],
"sortOrder": 53,
"defaultEnabled": false,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.20-0309-reasoning",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -2010,26 +1662,20 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.20-0309-reasoning"
},
{
"id": "xai/grok-4.20-0309-non-reasoning",
"name": "Grok 4.20 Non-Reasoning",
"status": "active",
- "group": "grok",
- "description": "xAI Grok 4.20 non-reasoning model,1M 上下文(SuperGrok 订阅直连)",
- "contextWindow": 1000000,
- "efforts": [],
"sortOrder": 54,
"defaultEnabled": false,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.20-0309-non-reasoning",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -2062,32 +1708,20 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.20-0309-non-reasoning"
},
{
"id": "xai/grok-4.20",
"name": "Grok 4.20 Legacy Alias",
"status": "deprecated",
- "group": "grok",
- "description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 98,
"defaultEnabled": false,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-4.20",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -2120,26 +1754,20 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.20"
},
{
"id": "xai/grok-code-fast",
"name": "Grok Code Fast (Deprecated)",
"status": "deprecated",
- "group": "grok",
- "description": "旧版兼容 alias;新会话请使用 grok-build-0.1",
- "contextWindow": 256000,
- "efforts": [],
"sortOrder": 99,
"defaultEnabled": false,
"routes": [
{
"providerId": "xai",
"modelId": "xai/grok-code-fast",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -2172,131 +1800,88 @@
]
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-code-fast"
},
{
"id": "xd/codex-gpt-5.6-luna",
"name": "GPT-5.6-Luna",
- "group": "gpt-budget",
"sortOrder": 7,
"routes": [
{
"providerId": "xd",
"modelId": "codex/gpt-5.6-luna",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "group": "gpt-budget"
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-luna"
},
{
"id": "xd/codex-gpt-5.6-sol",
"name": "GPT-5.6-Sol",
- "group": "gpt-budget",
- "description": "GPT-5.6-Sol for coding tasks",
- "contextWindow": 372000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 8,
- "supportsFastMode": true,
"perAgent": {
"claude-code": {
"supportsFastMode": false
},
"codex": {
"contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
}
},
"routes": [
{
"providerId": "xd",
"modelId": "codex/gpt-5.6-sol",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.6-Sol for coding tasks",
+ "group": "gpt-budget",
+ "contextWindow": 372000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-sol"
},
{
"id": "xd/codex-gpt-5.6-terra",
"name": "GPT-5.6-Terra",
- "group": "gpt-budget",
- "description": "GPT-5.6-Terra for coding tasks",
- "contextWindow": 372000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "medium",
"sortOrder": 9,
- "supportsFastMode": true,
"perAgent": {
"claude-code": {
"supportsFastMode": false
},
"codex": {
"contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
}
},
"routes": [
{
"providerId": "xd",
"modelId": "codex/gpt-5.6-terra",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "group": "gpt-budget",
+ "contextWindow": 372000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.6-terra"
},
{
"id": "xd/codex-gpt-5.5",
"name": "GPT-5.5",
- "group": "gpt-budget",
- "description": "GPT-5.5 for coding tasks",
- "contextWindow": 272000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 10,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"claude-code": {
@@ -2307,30 +1892,22 @@
{
"providerId": "xd",
"modelId": "codex/gpt-5.5",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.5 for coding tasks",
+ "group": "gpt-budget",
+ "contextWindow": 272000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.5"
},
{
"id": "xd/codex-gpt-5.4",
"name": "GPT-5.4",
- "group": "gpt-budget",
- "description": "GPT-5.4 for coding tasks",
- "contextWindow": 272000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 11,
- "supportsFastMode": true,
"defaultEnabled": false,
"perAgent": {
"claude-code": {
@@ -2341,37 +1918,28 @@
{
"providerId": "xd",
"modelId": "codex/gpt-5.4",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "description": "GPT-5.4 for coding tasks",
+ "group": "gpt-budget",
+ "contextWindow": 272000,
+ "supportsFastMode": true
+ }
}
],
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.4"
},
{
"id": "google/gemini-3.7-flash",
"name": "Gemini 3.7 Flash",
"status": "active",
- "group": "google",
- "description": "Google Gemini 3.7 Flash — agentic workflows and multimodal reasoning",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 28,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3.7-flash",
- "agents": [
- "claude-code"
- ],
+ "agents": ["claude-code"],
"referencePrices": [
{
"currency": "USD",
@@ -2402,35 +1970,25 @@
"verifiedAt": "2026-08-13"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3.7-flash"
},
{
"id": "google/gemini-3.6-flash",
"name": "Gemini 3.6 Flash",
"status": "active",
- "group": "google",
- "description": "Google Gemini 3.6 Flash — frontier intelligence optimized for speed and cost",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
- "efforts": [
- "minimal",
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 29,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3.6-flash",
- "agents": [
- "claude-code"
- ],
+ "agents": ["claude-code"],
"referencePrices": [
{
"currency": "USD",
@@ -2461,488 +2019,335 @@
"verifiedAt": "2026-08-13"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3.6-flash"
},
{
"id": "google/gemini-3.5-flash",
"name": "Gemini 3.5 Flash",
- "group": "google",
- "description": "Google Gemini 3.5 Flash — upgraded Flash with stronger reasoning",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
- "efforts": [
- "minimal",
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 30,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3.5-flash",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3.5-flash"
},
{
"id": "google/gemini-3.1-pro-preview",
"name": "Gemini 3.1 Pro",
- "group": "google",
- "description": "Google Gemini 3.1 Pro Preview — deepest reasoning, multimodal",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 31,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3.1-pro-preview",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3.1-pro-preview"
},
{
"id": "google/gemini-3-flash-preview",
"name": "Gemini 3 Flash",
- "group": "google",
- "description": "Google Gemini 3 Flash Preview — fast multimodal reasoning",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
- "efforts": [
- "minimal",
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 32,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3-flash-preview",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3-flash-preview"
},
{
"id": "google/gemini-3.5-flash-lite",
"name": "Gemini 3.5 Flash-Lite",
"status": "active",
- "group": "google",
- "description": "Google Gemini 3.5 Flash-Lite — cost-efficient multimodal model for high-volume workloads",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
- "efforts": [
- "minimal",
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"sortOrder": 33,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3.5-flash-lite",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3.5-flash-lite"
},
{
"id": "google/gemini-3.1-flash-lite",
"name": "Gemini 3.1 Flash-Lite",
"status": "active",
- "group": "google",
- "description": "Google Gemini 3.1 Flash-Lite — efficient multimodal model for large-scale tasks",
- "contextWindow": 1000000,
- "maxOutputTokens": 65536,
"sortOrder": 34,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "gemini-3.1-flash-lite",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "google-generative-ai"
+ "nativeApi": "google-generative-ai",
+ "modelRef": "google/gemini-3.1-flash-lite"
},
{
"id": "bytedance-seed/seed-2.1-pro",
"name": "Seed 2.1 Pro",
- "group": "china",
- "contextWindow": 256000,
- "maxOutputTokens": 256000,
- "efforts": [
- "minimal",
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
- "supportsFastMode": false,
"perAgent": {
"claude-code": {
- "efforts": [
- "low",
- "medium",
- "high"
- ]
+ "efforts": ["low", "medium", "high"]
}
},
"routes": [
{
"providerId": "xd",
"modelId": "bytedance-seed/seed-2.1-pro",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "bytedance-seed/seed-2.1-pro"
},
{
"id": "qwen/qwen3.8-max",
"name": "Qwen 3.8 Max",
- "group": "china",
- "contextWindow": 983616,
- "maxOutputTokens": 131072,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "qwen/qwen3.8-max",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.8-max"
},
{
"id": "qwen/qwen3.8-max-preview",
"name": "Qwen 3.8 Max Preview",
"status": "retired",
- "group": "china",
- "contextWindow": 983616,
- "efforts": [
- "low",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "qwen/qwen3.8-max-preview",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.8-max-preview"
},
{
"id": "qwen/qwen3.7-max",
"name": "Qwen 3.7 Max",
- "group": "china",
- "description": "Qwen 3.7 Max agentic coding model; thinking is provider-managed",
- "contextWindow": 992000,
- "maxOutputTokens": 65536,
- "efforts": [],
"sortOrder": 40,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "qwen/qwen3.7-max",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.7-max"
},
{
"id": "moonshotai/kimi-k2.7-code",
"name": "Kimi K2.7 Code",
"status": "active",
- "group": "china",
- "description": "Moonshot Kimi K2.7 Code agentic coding model",
- "contextWindow": 262144,
- "efforts": [],
"sortOrder": 107,
"defaultEnabled": false,
"routes": [
{
"providerId": "moonshot-kimi-cn",
"modelId": "kimi-k2.7-code",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "moonshot-kimi-global",
"modelId": "kimi-k2.7-code",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "moonshotai/kimi-k2.7-code"
},
{
"id": "moonshotai/kimi-k2.7-code-highspeed",
"name": "Kimi K2.7 Code Highspeed",
"status": "active",
- "group": "china",
- "description": "Moonshot Kimi K2.7 Code high-speed API variant",
- "contextWindow": 262144,
- "efforts": [],
"sortOrder": 108,
"defaultEnabled": false,
"routes": [
{
"providerId": "moonshot-kimi-cn",
"modelId": "kimi-k2.7-code-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "moonshot-kimi-global",
"modelId": "kimi-k2.7-code-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "moonshotai/kimi-k2.7-code-highspeed"
},
{
"id": "moonshotai/kimi-k2.6",
"name": "Kimi K2.6",
- "group": "china",
- "description": "Moonshot Kimi K2.6 agentic coding model; thinking is provider-managed",
- "contextWindow": 262144,
- "efforts": [],
"sortOrder": 106,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "moonshotai/kimi-k2.6",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "moonshotai/kimi-k2.6"
},
{
"id": "z-ai/glm-5.1",
"name": "GLM-5.1",
- "group": "china",
- "description": "Zhipu GLM-5.1 agentic coding model; thinking is provider-managed",
- "contextWindow": 200000,
- "maxOutputTokens": 131072,
- "efforts": [],
"sortOrder": 42,
- "supportsFastMode": false,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "z-ai/glm-5.1",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "z-ai/glm-5.1"
},
{
"id": "z-ai/glm-5.2",
"name": "GLM-5.2",
- "group": "china",
- "description": "Zhipu GLM-5.2 agentic coding model; 1M context",
- "contextWindow": 1000000,
- "maxOutputTokens": 131072,
- "efforts": [
- "minimal",
- "high",
- "max"
- ],
- "defaultEffort": "high",
"sortOrder": 43,
- "supportsFastMode": false,
"perAgent": {
"claude-code": {
- "efforts": [
- "high",
- "max"
- ]
+ "efforts": ["high", "max"]
}
},
"routes": [
{
"providerId": "xd",
"modelId": "z-ai/glm-5.2",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "z-ai/glm-5.2"
},
{
"id": "z-ai/glm-5.3",
"name": "GLM-5.3",
"status": "active",
- "group": "china",
- "description": "Zhipu GLM-5.3 agentic coding model; 1M context",
- "contextWindow": 1000000,
- "maxOutputTokens": 131072,
- "efforts": [
- "low",
- "high",
- "max"
- ],
- "defaultEffort": "high",
"sortOrder": 44,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "z-ai/glm-5.3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "z-ai/glm-5.3"
},
{
"id": "z-ai/glm-5.3-flash",
"name": "GLM-5.3-Flash",
"status": "active",
- "group": "china",
- "description": "Zhipu GLM-5.3-Flash native multimodal coding model; 1M context",
- "contextWindow": 1000000,
- "maxOutputTokens": 131072,
"routes": [
{
"providerId": "zhipu-glm-cn",
"modelId": "glm-5.3-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "zhipu-glm-global",
"modelId": "glm-5.3-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "z-ai/glm-5.3-flash"
},
{
"id": "xd/z-ai-glm-5.3-flash",
"name": "GLM-5.3-Flash",
"status": "active",
- "group": "china",
- "description": "Zhipu GLM-5.3-Flash native multimodal coding model; 1M context",
- "contextWindow": 1000000,
- "maxOutputTokens": 131072,
"routes": [
{
"providerId": "xd",
"modelId": "z-ai/glm-5.3-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
"nativeApi": "openai-completions",
- "defaultEffort": "medium"
+ "modelRef": "xd/z-ai-glm-5.3-flash"
},
{
"id": "deepseek/deepseek-v4-pro",
"name": "DeepSeek V4 Pro",
- "group": "china",
- "description": "DeepSeek V4 Pro reasoning model",
- "contextWindow": 1048576,
- "maxOutputTokens": 384000,
- "efforts": [
- "low",
- "high",
- "max"
- ],
- "defaultEffort": "high",
"sortOrder": 45,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "deepseek/deepseek-v4-pro",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -2957,15 +2362,15 @@
"verifiedAt": "2026-08-16"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "deepseek",
"modelId": "deepseek-v4-pro",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -2994,34 +2399,24 @@
"verifiedAt": "2026-08-16"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "deepseek/deepseek-v4-pro"
},
{
"id": "deepseek/deepseek-v4-flash",
"name": "DeepSeek V4 Flash",
- "group": "china",
- "description": "DeepSeek V4 Flash efficiency-optimized MoE; supports low/high/max effort",
- "contextWindow": 1048576,
- "maxOutputTokens": 384000,
- "efforts": [
- "low",
- "high",
- "max"
- ],
- "defaultEffort": "high",
"sortOrder": 46,
- "supportsFastMode": false,
"routes": [
{
"providerId": "xd",
"modelId": "deepseek/deepseek-v4-flash",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -3036,15 +2431,15 @@
"verifiedAt": "2026-08-16"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "deepseek",
"modelId": "deepseek-v4-flash",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -3073,35 +2468,26 @@
"verifiedAt": "2026-08-16"
}
}
- ]
+ ],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "deepseek/deepseek-v4-flash"
},
{
"id": "openai/gpt-5.4-nano",
"name": "GPT-5.4-Nano",
"status": "active",
- "group": "gpt",
- "description": "OpenAI GPT-5.4 nano for simple, high-volume tasks",
- "contextWindow": 400000,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
"sortOrder": 101,
"defaultEnabled": false,
"routes": [
{
"providerId": "openai",
"modelId": "gpt-5.4-nano",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"referencePrices": [
{
"currency": "USD",
@@ -3121,539 +2507,384 @@
{
"providerId": "xd",
"modelId": "gpt-5.4-nano",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
"nativeApi": "openai-responses",
- "defaultEffort": "medium"
+ "modelRef": "openai/gpt-5.4-nano"
},
{
"id": "xd/codex-gpt-5.4-mini",
"name": "GPT-5.4-Mini",
- "group": "gpt-budget",
- "contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"sortOrder": 103,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "codex/gpt-5.4-mini",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "group": "gpt-budget",
+ "contextWindow": 272000
+ }
}
],
- "maxOutputTokens": 128000,
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.4-mini"
},
{
"id": "minimax/minimax-m3",
"name": "MiniMax M3",
"status": "active",
- "group": "china",
- "contextWindow": 1000000,
"sortOrder": 114,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m3"
},
{
"id": "minimax/minimax-m2.7",
"name": "MiniMax M2.7",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 111,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2.7",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2.7",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2.7"
},
{
"id": "minimax/minimax-m2.7-highspeed",
"name": "MiniMax M2.7 Highspeed",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 112,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2.7-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2.7-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2.7-highspeed"
},
{
"id": "minimax/minimax-m2.5",
"name": "MiniMax M2.5",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 116,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2.5",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2.5",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2.5"
},
{
"id": "minimax/minimax-m2.5-highspeed",
"name": "MiniMax M2.5 Highspeed",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 117,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2.5-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2.5-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2.5-highspeed"
},
{
"id": "minimax/minimax-m2.1",
"name": "MiniMax M2.1",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 118,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2.1",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2.1",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2.1"
},
{
"id": "minimax/minimax-m2.1-highspeed",
"name": "MiniMax M2.1 Highspeed",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 119,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2.1-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2.1-highspeed",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2.1-highspeed"
},
{
"id": "minimax/minimax-m2",
"name": "MiniMax M2",
"status": "active",
- "group": "china",
- "contextWindow": 204800,
"sortOrder": 120,
"defaultEnabled": false,
"routes": [
{
"providerId": "minimax-cn",
"modelId": "MiniMax-M2",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "minimax-global",
"modelId": "MiniMax-M2",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "anthropic-messages"
+ "nativeApi": "anthropic-messages",
+ "modelRef": "minimax/minimax-m2"
},
{
"id": "moonshotai/kimi-k3",
"name": "Kimi K3",
- "group": "china",
- "contextWindow": 1048576,
- "maxOutputTokens": 1048576,
- "efforts": [
- "low",
- "high",
- "max"
- ],
- "defaultEffort": "high",
"sortOrder": 41,
- "supportsFastMode": false,
"routes": [
{
"providerId": "moonshot-kimi-cn",
"modelId": "kimi-k3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "moonshot-kimi-global",
"modelId": "kimi-k3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "moonshotai/kimi-k3"
},
{
"id": "qwen/qwen3.6-plus",
"name": "Qwen 3.6 Plus",
- "group": "china",
- "description": "Qwen 3.6 Plus with provider-managed thinking",
- "contextWindow": 1048576,
- "maxOutputTokens": 65536,
- "efforts": [],
"sortOrder": 105,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "qwen/qwen3.6-plus",
- "agents": [
- "claude-code"
- ]
+ "agents": ["claude-code"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.6-plus"
},
{
"id": "qwen/qwen3.6-plus-api",
"name": "Qwen 3.6 Plus API",
"status": "active",
- "group": "china",
- "contextWindow": 991808,
- "maxOutputTokens": 65536,
"sortOrder": 113,
"defaultEnabled": false,
"routes": [
{
"providerId": "aliyun-model-studio-cn",
"modelId": "qwen3.6-plus",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "aliyun-model-studio-global",
"modelId": "qwen3.6-plus",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.6-plus-api"
},
{
"id": "qwen/qwen3.7-flash",
"name": "Qwen 3.7 Flash",
"status": "active",
- "group": "china",
- "description": "Alibaba Qwen 3.7 Flash text model with provider-managed thinking",
- "contextWindow": 991808,
- "maxOutputTokens": 65536,
- "efforts": [],
"sortOrder": 115,
"defaultEnabled": false,
"routes": [
{
"providerId": "aliyun-model-studio-cn",
"modelId": "qwen3.7-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "aliyun-model-studio-global",
"modelId": "qwen3.7-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.7-flash"
},
{
"id": "qwen/qwen3.8-flash",
"name": "Qwen 3.8 Flash",
"status": "active",
- "group": "china",
- "description": "Alibaba Qwen 3.8 Flash multimodal model with provider-managed thinking",
- "contextWindow": 991808,
- "maxOutputTokens": 131072,
- "efforts": [],
"sortOrder": 121,
"defaultEnabled": false,
"routes": [
{
"providerId": "aliyun-model-studio-cn",
"modelId": "qwen3.8-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "aliyun-model-studio-global",
"modelId": "qwen3.8-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.8-flash"
},
{
"id": "qwen/qwen3.7-plus",
"name": "Qwen 3.7 Plus",
"status": "active",
- "group": "china",
- "description": "Alibaba Qwen 3.7 Plus text model with provider-managed thinking",
- "contextWindow": 991808,
- "maxOutputTokens": 65536,
- "efforts": [],
"sortOrder": 109,
"defaultEnabled": false,
"routes": [
{
"providerId": "aliyun-model-studio-cn",
"modelId": "qwen3.7-plus",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "aliyun-model-studio-global",
"modelId": "qwen3.7-plus",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.7-plus"
},
{
"id": "qwen/qwen3.6-flash",
"name": "Qwen 3.6 Flash",
"status": "active",
- "group": "china",
- "description": "Alibaba Qwen 3.6 Flash text model with provider-managed thinking",
- "contextWindow": 991808,
- "maxOutputTokens": 65536,
- "efforts": [],
"sortOrder": 110,
"defaultEnabled": false,
"routes": [
{
"providerId": "aliyun-model-studio-cn",
"modelId": "qwen3.6-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
},
{
"providerId": "aliyun-model-studio-global",
"modelId": "qwen3.6-flash",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.6-flash"
},
{
"id": "xd/codex-gpt-5.5-auto",
"name": "GPT-5.5-Auto",
- "group": "gpt-budget",
"sortOrder": 12,
"defaultEnabled": false,
"routes": [
{
"providerId": "xd",
"modelId": "codex/gpt-5.5:auto",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "maxOutputTokens": 128000,
- "nativeApi": "openai-responses"
+ "nativeApi": "openai-responses",
+ "modelRef": "openai/gpt-5.5-auto"
},
{
"id": "qwen/qwen3.8-27b",
"name": "Qwen3.8 27B",
- "contextWindow": 991808,
- "maxOutputTokens": 131072,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "medium",
"routes": [
{
"providerId": "xd",
"modelId": "qwen/qwen3.8-27b",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "qwen/qwen3.8-27b"
},
{
"id": "tencent/hy3",
"name": "Hy3",
- "contextWindow": 262144,
- "maxOutputTokens": 128000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "medium",
"routes": [
{
"providerId": "xd",
"modelId": "tencent/hy3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "tencent/hy3"
},
{
"id": "meta/muse-spark-1.2",
@@ -3663,79 +2894,61 @@
{
"providerId": "xd",
"modelId": "meta/muse-spark-1.2",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
- ]
+ ],
+ "modelRef": "meta/muse-spark-1.2"
},
{
"id": "xd/moonshotai-kimi-k3",
"name": "Kimi K3",
- "defaultEffort": "medium",
"routes": [
{
"providerId": "xd",
"modelId": "moonshot/kimi-k3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
},
{
"providerId": "xd",
"modelId": "moonshotai/kimi-k3",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"],
+ "defaults": {
+ "supportsFastMode": false
+ }
}
],
"nativeApi": "openai-completions",
- "group": "china",
- "contextWindow": 1048576,
- "maxOutputTokens": 1048576,
- "efforts": [
- "low",
- "medium",
- "high",
- "max"
- ],
"sortOrder": 41,
- "supportsFastMode": false
+ "modelRef": "xd/moonshotai-kimi-k3"
},
{
"id": "xd/deepseek-deepseek-v4-flash-vision-exp",
"name": "DeepSeek V4 Flash Vision Exp",
- "defaultEffort": "medium",
"routes": [
{
"providerId": "xd",
"modelId": "deepseek/deepseek-v4-flash-vision-exp",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "xd/deepseek-deepseek-v4-flash-vision-exp"
},
{
"id": "xd/tencent-hy4-preview",
"name": "Hy4 preview",
- "defaultEffort": "medium",
"routes": [
{
"providerId": "xd",
"modelId": "tencent/hy4-preview",
- "agents": [
- "claude-code",
- "codex"
- ]
+ "agents": ["claude-code", "codex"]
}
],
- "nativeApi": "openai-completions"
+ "nativeApi": "openai-completions",
+ "modelRef": "xd/tencent-hy4-preview"
}
],
"nativeApiRules": [
@@ -3859,5 +3072,1169 @@
"modelIdPrefix": "xai/grok-",
"nativeApi": "openai-responses"
}
+ ],
+ "localModels": {
+ "version": 1,
+ "featuredIds": ["qwen38-27b"],
+ "models": [
+ {
+ "id": "qwen38-27b",
+ "name": "Qwen3.8 27B",
+ "aliases": [
+ "qwen",
+ "qwen3.8",
+ "qwen3",
+ "tongyi",
+ "qwq",
+ "通义",
+ "通義",
+ "千问",
+ "千問"
+ ],
+ "variants": [
+ {
+ "libraryName": "qwen3.8:27b-mxfp8",
+ "sizeBytes": 31655335990,
+ "minUnifiedMemoryGb": 64,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "qwen3.8:27b-mlx",
+ "sizeBytes": 18174721596,
+ "minUnifiedMemoryGb": 32,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "qwen3.8:27b",
+ "sizeBytes": 17741871939,
+ "minUnifiedMemoryGb": 32,
+ "appleSiliconOnly": false
+ }
+ ],
+ "runtimeProfile": "qwen-xhigh",
+ "descriptions": {
+ "en": "Capability pick based on independent benchmarks; local quantization can affect results.",
+ "zh-CN": "依据独立跑分保留的能力推荐,本地量化效果仍可能有差异。",
+ "zh-TW": "依據獨立跑分保留的能力推薦,本機量化效果仍可能有差異。",
+ "ja": "独立評価に基づく能力重視の推奨。ローカルの量子化で結果は変わり得ます。",
+ "ko": "독립 벤치마크에 따른 성능 추천입니다. 로컬 양자화에 따라 결과가 달라질 수 있습니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/qwen3-8-27b",
+ "verifiedAt": "2026-09-05",
+ "status": "measured"
+ }
+ ],
+ "modelRef": "qwen/qwen3.8-27b"
+ },
+ {
+ "id": "qwen35-4b",
+ "name": "Qwen3.5 4B",
+ "aliases": ["qwen", "qwen3.5", "通义", "通義", "千问", "千問"],
+ "variants": [
+ {
+ "libraryName": "qwen3.5:4b-mlx",
+ "sizeBytes": 3973304734,
+ "minUnifiedMemoryGb": 8,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "qwen3.5:4b-q4_K_M",
+ "sizeBytes": 3389983260,
+ "minUnifiedMemoryGb": 8
+ }
+ ],
+ "descriptions": {
+ "en": "Low-memory candidate; comparable speed and memory tests are pending.",
+ "zh-CN": "低内存候选,待补齐同条件速度与内存实测。",
+ "zh-TW": "低記憶體候選,待補齊相同條件的速度與記憶體實測。",
+ "ja": "省メモリ候補。同条件での速度とメモリの実測待ち。",
+ "ko": "저메모리 후보. 동일 조건의 속도와 메모리 실측이 필요합니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/qwen3-5-4b",
+ "verifiedAt": "2026-09-05",
+ "status": "estimated"
+ }
+ ],
+ "modelRef": "qwen/qwen3.5-4b"
+ },
+ {
+ "id": "qwen35-9b",
+ "name": "Qwen3.5 9B",
+ "aliases": ["qwen", "qwen3.5", "通义", "通義", "千问", "千問"],
+ "variants": [
+ {
+ "libraryName": "qwen3.5:9b-mlx",
+ "sizeBytes": 8903014479,
+ "minUnifiedMemoryGb": 16,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "qwen3.5:9b-q4_K_M",
+ "sizeBytes": 6594474236,
+ "minUnifiedMemoryGb": 16
+ }
+ ],
+ "descriptions": {
+ "en": "Low-memory candidate to compare with Gemma 4 12B.",
+ "zh-CN": "低内存候选,待与 Gemma 4 12B 比较。",
+ "zh-TW": "低記憶體候選,待與 Gemma 4 12B 比較。",
+ "ja": "省メモリ候補。Gemma 4 12B との比較待ち。",
+ "ko": "저메모리 후보. Gemma 4 12B와 비교가 필요합니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/qwen3-5-9b",
+ "verifiedAt": "2026-09-05",
+ "status": "estimated"
+ }
+ ],
+ "modelRef": "qwen/qwen3.5-9b"
+ },
+ {
+ "id": "gemma4-12b",
+ "name": "Gemma 4 12B",
+ "aliases": ["gemma", "gemma4", "google", "宝石", "寶石"],
+ "variants": [
+ {
+ "libraryName": "gemma4:12b-mlx",
+ "sizeBytes": 7714091072,
+ "minUnifiedMemoryGb": 16,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "gemma4:12b-it-q4_K_M",
+ "sizeBytes": 7556507848,
+ "minUnifiedMemoryGb": 16
+ }
+ ],
+ "descriptions": {
+ "en": "Low-memory candidate to compare with Qwen3.5 9B.",
+ "zh-CN": "低内存候选,待与 Qwen3.5 9B 比较。",
+ "zh-TW": "低記憶體候選,待與 Qwen3.5 9B 比較。",
+ "ja": "省メモリ候補。Qwen3.5 9B との比較待ち。",
+ "ko": "저메모리 후보. Qwen3.5 9B와 비교가 필요합니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/gemma-4-12b",
+ "verifiedAt": "2026-09-05",
+ "status": "estimated"
+ }
+ ],
+ "modelRef": "google/gemma-4-12b"
+ },
+ {
+ "id": "qwen36-35b",
+ "name": "Qwen3.6 35B A3B",
+ "aliases": ["qwen", "qwen3.6", "通义", "通義", "moe"],
+ "variants": [
+ {
+ "libraryName": "qwen3.6:35b-mlx",
+ "sizeBytes": 23598465441,
+ "minUnifiedMemoryGb": 32,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "qwen3.6:35b-a3b-q4_K_M",
+ "sizeBytes": 23938333115,
+ "minUnifiedMemoryGb": 32
+ }
+ ],
+ "descriptions": {
+ "en": "Speed candidate; a comparison with Nemotron is pending.",
+ "zh-CN": "速度候选,待与 Nemotron 做同条件比较。",
+ "zh-TW": "速度候選,待與 Nemotron 做相同條件比較。",
+ "ja": "速度重視の候補。Nemotron との同条件比較待ち。",
+ "ko": "속도 후보. Nemotron과 동일 조건 비교가 필요합니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/qwen3-6-35b-a3b",
+ "verifiedAt": "2026-09-05",
+ "status": "estimated"
+ }
+ ],
+ "modelRef": "qwen/qwen36-35b"
+ },
+ {
+ "id": "nemotron35-30b",
+ "name": "Nemotron 3.5 Lightning 30B",
+ "aliases": ["nemotron", "nvidia", "lightning", "moe"],
+ "variants": [
+ {
+ "libraryName": "nemotron-3.5-lightning:30b-mlx",
+ "sizeBytes": 22666641292,
+ "minUnifiedMemoryGb": 48,
+ "appleSiliconOnly": true
+ },
+ {
+ "libraryName": "nemotron-3.5-lightning:30b",
+ "sizeBytes": 25430749137,
+ "minUnifiedMemoryGb": 48
+ }
+ ],
+ "descriptions": {
+ "en": "Speed candidate; a comparison with Qwen3.6 is pending.",
+ "zh-CN": "速度候选,待与 Qwen3.6 做同条件比较。",
+ "zh-TW": "速度候選,待與 Qwen3.6 做相同條件比較。",
+ "ja": "速度重視の候補。Qwen3.6 との同条件比較待ち。",
+ "ko": "속도 후보. Qwen3.6과 동일 조건 비교가 필요합니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/nemotron-3-5-lightning",
+ "verifiedAt": "2026-09-05",
+ "status": "estimated"
+ }
+ ],
+ "modelRef": "nvidia/nemotron-3.5-lightning"
+ },
+ {
+ "id": "qwen38-flash-next",
+ "name": "Qwen3.8 Flash-Next",
+ "aliases": ["qwen", "flash-next", "通义", "通義", "moe"],
+ "variants": [
+ {
+ "libraryName": "qwen3.8-flash-next:125b-mlx",
+ "sizeBytes": 104852025885,
+ "minUnifiedMemoryGb": 192,
+ "appleSiliconOnly": true
+ }
+ ],
+ "descriptions": {
+ "en": "High-memory candidate; local peak memory and performance still need validation.",
+ "zh-CN": "大内存候选,仍需验证本机峰值内存与性能。",
+ "zh-TW": "大記憶體候選,仍需驗證本機峰值記憶體與效能。",
+ "ja": "大容量メモリ向け候補。本機でのピークメモリと性能は未検証。",
+ "ko": "대용량 메모리 후보. 로컬 최대 메모리와 성능 검증이 필요합니다."
+ },
+ "evidence": [
+ {
+ "url": "https://artificialanalysis.ai/models/qwen3-8-flash-next",
+ "verifiedAt": "2026-09-05",
+ "status": "estimated"
+ }
+ ],
+ "modelRef": "qwen/qwen3.8-flash-next"
+ }
+ ]
+ },
+ "baseModels": [
+ {
+ "id": "openai/gpt-5.6-sol",
+ "aliases": [
+ "gpt-5.6-sol",
+ "openai/gpt-5.6-sol[1m]",
+ "xd/gpt-5.6-sol",
+ "xd/codex-gpt-5.6-sol",
+ "codex/gpt-5.6-sol"
+ ],
+ "defaults": {
+ "maxOutputTokens": 128000,
+ "defaultEffort": "medium",
+ "name": "GPT-5.6-Sol"
+ }
+ },
+ {
+ "id": "openai/gpt-5.6-terra",
+ "aliases": [
+ "gpt-5.6-terra",
+ "xd/gpt-5.6-terra",
+ "xd/codex-gpt-5.6-terra",
+ "codex/gpt-5.6-terra"
+ ],
+ "defaults": {
+ "name": "GPT-5.6-Terra",
+ "description": "GPT-5.6-Terra for coding tasks",
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "openai/gpt-5.6-luna",
+ "aliases": [
+ "gpt-5.6-luna",
+ "xd/gpt-5.6-luna",
+ "xd/codex-gpt-5.6-luna",
+ "codex/gpt-5.6-luna"
+ ],
+ "defaults": {
+ "name": "GPT-5.6-Luna"
+ }
+ },
+ {
+ "id": "openai/gpt-5.5",
+ "aliases": ["gpt-5.5", "xd/gpt-5.5", "xd/codex-gpt-5.5", "codex/gpt-5.5"],
+ "defaults": {
+ "name": "GPT-5.5",
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "openai/gpt-5.4",
+ "aliases": ["gpt-5.4", "xd/gpt-5.4", "xd/codex-gpt-5.4", "codex/gpt-5.4"],
+ "defaults": {
+ "name": "GPT-5.4",
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "openai/gpt-5.4-mini",
+ "aliases": [
+ "gpt-5.4-mini",
+ "xd/gpt-5.4-mini",
+ "xd/codex-gpt-5.4-mini",
+ "codex/gpt-5.4-mini"
+ ],
+ "defaults": {
+ "name": "GPT-5.4-Mini",
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "openai/gpt-5.4-pro",
+ "aliases": ["gpt-5.4-pro"],
+ "defaults": {
+ "name": "GPT-5.4 Pro",
+ "description": "OpenAI GPT-5.4 Pro for demanding reasoning tasks",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000
+ }
+ },
+ {
+ "id": "openai/gpt-5.5-pro",
+ "aliases": ["gpt-5.5-pro"],
+ "defaults": {
+ "name": "GPT-5.5 Pro",
+ "description": "OpenAI GPT-5.5 Pro for precise, high-quality reasoning",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000
+ }
+ },
+ {
+ "id": "openai/gpt-5.6-cyber",
+ "aliases": ["gpt-5.6-cyber"],
+ "defaults": {
+ "name": "GPT-5.6 Cyber",
+ "description": "OpenAI cyber security reasoning model; access requires approval",
+ "group": "gpt",
+ "contextWindow": 400000,
+ "maxOutputTokens": 128000
+ }
+ },
+ {
+ "id": "openai/gpt-6-astra",
+ "aliases": ["gpt-6-astra"],
+ "defaults": {
+ "name": "GPT-6 Astra",
+ "description": "OpenAI GPT-6 Astra for complex reasoning, coding, computer use, research, and document creation",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-fable-5-1",
+ "aliases": ["claude-fable-5-1"],
+ "defaults": {
+ "name": "Fable 5.1",
+ "description": "Claude Fable 5.1 for long-running agentic coding and research",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-fable-5",
+ "aliases": ["claude-fable-5"],
+ "defaults": {
+ "name": "Fable 5",
+ "description": "Most capable, supports xhigh effort",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-mythos-5",
+ "aliases": ["claude-mythos-5"],
+ "defaults": {
+ "name": "Mythos 5",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-opus-5",
+ "aliases": ["claude-opus-5"],
+ "defaults": {
+ "name": "Opus 5",
+ "description": "Latest Opus for ambitious work",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-opus-4-8",
+ "aliases": ["claude-opus-4-8"],
+ "defaults": {
+ "name": "Opus 4.8",
+ "description": "Most capable, supports xhigh effort",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-opus-4-7",
+ "aliases": ["claude-opus-4-7"],
+ "defaults": {
+ "name": "Opus 4.7",
+ "description": "Most capable, supports xhigh effort",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-opus-4-6",
+ "aliases": ["claude-opus-4-6"],
+ "defaults": {
+ "name": "Opus 4.6",
+ "description": "Most capable for ambitious work",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-opus-4-5",
+ "aliases": ["claude-opus-4-5"],
+ "defaults": {
+ "name": "Opus 4.5",
+ "description": "Earlier Opus generation",
+ "group": "anthropic",
+ "contextWindow": 200000,
+ "maxOutputTokens": 64000,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-sonnet-5",
+ "aliases": ["claude-sonnet-5"],
+ "defaults": {
+ "name": "Sonnet 5",
+ "description": "Latest Sonnet — fast and highly capable",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-sonnet-4-6",
+ "aliases": ["claude-sonnet-4-6"],
+ "defaults": {
+ "name": "Sonnet 4.6",
+ "description": "Most efficient for everyday tasks",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "anthropic/claude-sonnet-4-5",
+ "aliases": ["claude-sonnet-4-5"],
+ "defaults": {
+ "name": "Sonnet 4.5",
+ "description": "Earlier Sonnet generation",
+ "group": "anthropic",
+ "contextWindow": 200000,
+ "maxOutputTokens": 64000,
+ "efforts": []
+ }
+ },
+ {
+ "id": "anthropic/claude-haiku-4-5",
+ "aliases": ["claude-haiku-4-5"],
+ "defaults": {
+ "name": "Haiku 4.5",
+ "description": "Fastest for quick answers",
+ "group": "anthropic",
+ "contextWindow": 200000,
+ "maxOutputTokens": 64000,
+ "efforts": []
+ }
+ },
+ {
+ "id": "xai/grok-4.6",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.6",
+ "description": "xAI Grok 4.6 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 500000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xai/grok-4.5",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.5",
+ "description": "xAI Grok 4.5 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 500000,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xai/grok-4.3",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.3",
+ "description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xai/grok-build-0.1",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok Build 0.1",
+ "description": "xAI agentic coding model,256k 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 256000,
+ "efforts": []
+ }
+ },
+ {
+ "id": "xai/grok-4.20-multi-agent-0309",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.20 Multi-Agent",
+ "description": "xAI Grok 4.20 multi-agent model,1M 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xai/grok-4.20-0309-reasoning",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.20 Reasoning",
+ "description": "xAI Grok 4.20 reasoning model,1M 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 1000000,
+ "efforts": []
+ }
+ },
+ {
+ "id": "xai/grok-4.20-0309-non-reasoning",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.20 Non-Reasoning",
+ "description": "xAI Grok 4.20 non-reasoning model,1M 上下文(SuperGrok 订阅直连)",
+ "group": "grok",
+ "contextWindow": 1000000,
+ "efforts": []
+ }
+ },
+ {
+ "id": "xai/grok-4.20",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.20 Legacy Alias",
+ "description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
+ "group": "grok",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xai/grok-code-fast",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok Code Fast (Deprecated)",
+ "description": "旧版兼容 alias;新会话请使用 grok-build-0.1",
+ "group": "grok",
+ "contextWindow": 256000,
+ "efforts": []
+ }
+ },
+ {
+ "id": "google/gemini-3.7-flash",
+ "aliases": ["gemini-3.7-flash"],
+ "defaults": {
+ "name": "Gemini 3.7 Flash",
+ "description": "Google Gemini 3.7 Flash — agentic workflows and multimodal reasoning",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "google/gemini-3.6-flash",
+ "aliases": ["gemini-3.6-flash"],
+ "defaults": {
+ "name": "Gemini 3.6 Flash",
+ "description": "Google Gemini 3.6 Flash — frontier intelligence optimized for speed and cost",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536,
+ "efforts": ["minimal", "low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "google/gemini-3.5-flash",
+ "aliases": ["gemini-3.5-flash"],
+ "defaults": {
+ "name": "Gemini 3.5 Flash",
+ "description": "Google Gemini 3.5 Flash — upgraded Flash with stronger reasoning",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536,
+ "efforts": ["minimal", "low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "google/gemini-3.1-pro-preview",
+ "aliases": ["gemini-3.1-pro-preview"],
+ "defaults": {
+ "name": "Gemini 3.1 Pro",
+ "description": "Google Gemini 3.1 Pro Preview — deepest reasoning, multimodal",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "google/gemini-3-flash-preview",
+ "aliases": ["gemini-3-flash-preview"],
+ "defaults": {
+ "name": "Gemini 3 Flash",
+ "description": "Google Gemini 3 Flash Preview — fast multimodal reasoning",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536,
+ "efforts": ["minimal", "low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "google/gemini-3.5-flash-lite",
+ "aliases": ["gemini-3.5-flash-lite"],
+ "defaults": {
+ "name": "Gemini 3.5 Flash-Lite",
+ "description": "Google Gemini 3.5 Flash-Lite — cost-efficient multimodal model for high-volume workloads",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536,
+ "efforts": ["minimal", "low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "google/gemini-3.1-flash-lite",
+ "aliases": ["gemini-3.1-flash-lite"],
+ "defaults": {
+ "name": "Gemini 3.1 Flash-Lite",
+ "description": "Google Gemini 3.1 Flash-Lite — efficient multimodal model for large-scale tasks",
+ "group": "google",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 65536
+ }
+ },
+ {
+ "id": "bytedance-seed/seed-2.1-pro",
+ "aliases": [],
+ "defaults": {
+ "name": "Seed 2.1 Pro",
+ "group": "china",
+ "contextWindow": 256000,
+ "maxOutputTokens": 256000,
+ "efforts": ["minimal", "low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "qwen/qwen3.8-max",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen 3.8 Max",
+ "group": "china",
+ "contextWindow": 983616,
+ "maxOutputTokens": 131072,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "qwen/qwen3.8-max-preview",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen 3.8 Max Preview",
+ "group": "china",
+ "contextWindow": 983616,
+ "efforts": ["low", "high", "xhigh"],
+ "defaultEffort": "high"
+ }
+ },
+ {
+ "id": "qwen/qwen3.7-max",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen 3.7 Max",
+ "description": "Qwen 3.7 Max agentic coding model; thinking is provider-managed",
+ "group": "china",
+ "contextWindow": 992000,
+ "maxOutputTokens": 65536,
+ "efforts": []
+ }
+ },
+ {
+ "id": "moonshotai/kimi-k2.7-code",
+ "aliases": ["kimi-k2.7-code"],
+ "defaults": {
+ "name": "Kimi K2.7 Code",
+ "description": "Moonshot Kimi K2.7 Code agentic coding model",
+ "group": "china",
+ "contextWindow": 262144,
+ "efforts": []
+ }
+ },
+ {
+ "id": "moonshotai/kimi-k2.7-code-highspeed",
+ "aliases": ["kimi-k2.7-code-highspeed"],
+ "defaults": {
+ "name": "Kimi K2.7 Code Highspeed",
+ "description": "Moonshot Kimi K2.7 Code high-speed API variant",
+ "group": "china",
+ "contextWindow": 262144,
+ "efforts": []
+ }
+ },
+ {
+ "id": "moonshotai/kimi-k2.6",
+ "aliases": [],
+ "defaults": {
+ "name": "Kimi K2.6",
+ "description": "Moonshot Kimi K2.6 agentic coding model; thinking is provider-managed",
+ "group": "china",
+ "contextWindow": 262144,
+ "efforts": []
+ }
+ },
+ {
+ "id": "z-ai/glm-5.1",
+ "aliases": [],
+ "defaults": {
+ "name": "GLM-5.1",
+ "description": "Zhipu GLM-5.1 agentic coding model; thinking is provider-managed",
+ "group": "china",
+ "contextWindow": 200000,
+ "maxOutputTokens": 131072,
+ "efforts": []
+ }
+ },
+ {
+ "id": "z-ai/glm-5.2",
+ "aliases": [],
+ "defaults": {
+ "name": "GLM-5.2",
+ "description": "Zhipu GLM-5.2 agentic coding model; 1M context",
+ "group": "china",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 131072,
+ "efforts": ["minimal", "high", "max"],
+ "defaultEffort": "high"
+ }
+ },
+ {
+ "id": "z-ai/glm-5.3",
+ "aliases": [],
+ "defaults": {
+ "name": "GLM-5.3",
+ "description": "Zhipu GLM-5.3 agentic coding model; 1M context",
+ "group": "china",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 131072,
+ "efforts": ["low", "high", "max"],
+ "defaultEffort": "high"
+ }
+ },
+ {
+ "id": "z-ai/glm-5.3-flash",
+ "aliases": ["glm-5.3-flash"],
+ "defaults": {
+ "name": "GLM-5.3-Flash",
+ "description": "Zhipu GLM-5.3-Flash native multimodal coding model; 1M context",
+ "group": "china",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 131072
+ }
+ },
+ {
+ "id": "xd/z-ai-glm-5.3-flash",
+ "aliases": [],
+ "defaults": {
+ "name": "GLM-5.3-Flash",
+ "description": "Zhipu GLM-5.3-Flash native multimodal coding model; 1M context",
+ "group": "china",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 131072,
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "deepseek/deepseek-v4-pro",
+ "aliases": ["deepseek-v4-pro"],
+ "defaults": {
+ "name": "DeepSeek V4 Pro",
+ "description": "DeepSeek V4 Pro reasoning model",
+ "group": "china",
+ "contextWindow": 1048576,
+ "maxOutputTokens": 384000,
+ "efforts": ["low", "high", "max"],
+ "defaultEffort": "high"
+ }
+ },
+ {
+ "id": "deepseek/deepseek-v4-flash",
+ "aliases": ["deepseek-v4-flash"],
+ "defaults": {
+ "name": "DeepSeek V4 Flash",
+ "description": "DeepSeek V4 Flash efficiency-optimized MoE; supports low/high/max effort",
+ "group": "china",
+ "contextWindow": 1048576,
+ "maxOutputTokens": 384000,
+ "efforts": ["low", "high", "max"],
+ "defaultEffort": "high"
+ }
+ },
+ {
+ "id": "openai/gpt-5.4-nano",
+ "aliases": ["gpt-5.4-nano"],
+ "defaults": {
+ "name": "GPT-5.4-Nano",
+ "description": "OpenAI GPT-5.4 nano for simple, high-volume tasks",
+ "group": "gpt",
+ "contextWindow": 400000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "minimax/minimax-m3",
+ "aliases": ["MiniMax-M3"],
+ "defaults": {
+ "name": "MiniMax M3",
+ "group": "china",
+ "contextWindow": 1000000
+ }
+ },
+ {
+ "id": "minimax/minimax-m2.7",
+ "aliases": ["MiniMax-M2.7"],
+ "defaults": {
+ "name": "MiniMax M2.7",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "minimax/minimax-m2.7-highspeed",
+ "aliases": ["MiniMax-M2.7-highspeed"],
+ "defaults": {
+ "name": "MiniMax M2.7 Highspeed",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "minimax/minimax-m2.5",
+ "aliases": ["MiniMax-M2.5"],
+ "defaults": {
+ "name": "MiniMax M2.5",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "minimax/minimax-m2.5-highspeed",
+ "aliases": ["MiniMax-M2.5-highspeed"],
+ "defaults": {
+ "name": "MiniMax M2.5 Highspeed",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "minimax/minimax-m2.1",
+ "aliases": ["MiniMax-M2.1"],
+ "defaults": {
+ "name": "MiniMax M2.1",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "minimax/minimax-m2.1-highspeed",
+ "aliases": ["MiniMax-M2.1-highspeed"],
+ "defaults": {
+ "name": "MiniMax M2.1 Highspeed",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "minimax/minimax-m2",
+ "aliases": ["MiniMax-M2"],
+ "defaults": {
+ "name": "MiniMax M2",
+ "group": "china",
+ "contextWindow": 204800
+ }
+ },
+ {
+ "id": "moonshotai/kimi-k3",
+ "aliases": ["kimi-k3"],
+ "defaults": {
+ "name": "Kimi K3",
+ "group": "china",
+ "contextWindow": 1048576,
+ "maxOutputTokens": 1048576,
+ "efforts": ["low", "high", "max"],
+ "defaultEffort": "high"
+ }
+ },
+ {
+ "id": "qwen/qwen3.6-plus",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen 3.6 Plus",
+ "description": "Qwen 3.6 Plus with provider-managed thinking",
+ "group": "china",
+ "contextWindow": 1048576,
+ "maxOutputTokens": 65536,
+ "efforts": []
+ }
+ },
+ {
+ "id": "qwen/qwen3.6-plus-api",
+ "aliases": ["qwen3.6-plus"],
+ "defaults": {
+ "name": "Qwen 3.6 Plus API",
+ "group": "china",
+ "contextWindow": 991808,
+ "maxOutputTokens": 65536
+ }
+ },
+ {
+ "id": "qwen/qwen3.7-flash",
+ "aliases": ["qwen3.7-flash"],
+ "defaults": {
+ "name": "Qwen 3.7 Flash",
+ "description": "Alibaba Qwen 3.7 Flash text model with provider-managed thinking",
+ "group": "china",
+ "contextWindow": 991808,
+ "maxOutputTokens": 65536,
+ "efforts": []
+ }
+ },
+ {
+ "id": "qwen/qwen3.8-flash",
+ "aliases": ["qwen3.8-flash"],
+ "defaults": {
+ "name": "Qwen 3.8 Flash",
+ "description": "Alibaba Qwen 3.8 Flash multimodal model with provider-managed thinking",
+ "group": "china",
+ "contextWindow": 991808,
+ "maxOutputTokens": 131072,
+ "efforts": []
+ }
+ },
+ {
+ "id": "qwen/qwen3.7-plus",
+ "aliases": ["qwen3.7-plus"],
+ "defaults": {
+ "name": "Qwen 3.7 Plus",
+ "description": "Alibaba Qwen 3.7 Plus text model with provider-managed thinking",
+ "group": "china",
+ "contextWindow": 991808,
+ "maxOutputTokens": 65536,
+ "efforts": []
+ }
+ },
+ {
+ "id": "qwen/qwen3.6-flash",
+ "aliases": ["qwen3.6-flash"],
+ "defaults": {
+ "name": "Qwen 3.6 Flash",
+ "description": "Alibaba Qwen 3.6 Flash text model with provider-managed thinking",
+ "group": "china",
+ "contextWindow": 991808,
+ "maxOutputTokens": 65536,
+ "efforts": []
+ }
+ },
+ {
+ "id": "openai/gpt-5.5-auto",
+ "aliases": ["xd/codex-gpt-5.5-auto", "codex/gpt-5.5:auto"],
+ "defaults": {
+ "name": "GPT-5.5-Auto",
+ "group": "gpt-budget",
+ "maxOutputTokens": 128000
+ }
+ },
+ {
+ "id": "qwen/qwen3.8-27b",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen3.8 27B",
+ "contextWindow": 991808,
+ "maxOutputTokens": 131072,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "tencent/hy3",
+ "aliases": [],
+ "defaults": {
+ "name": "Hy3",
+ "contextWindow": 262144,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "meta/muse-spark-1.2",
+ "aliases": [],
+ "defaults": {
+ "name": "Muse Spark 1.2"
+ }
+ },
+ {
+ "id": "xd/moonshotai-kimi-k3",
+ "aliases": ["moonshot/kimi-k3"],
+ "defaults": {
+ "name": "Kimi K3",
+ "group": "china",
+ "contextWindow": 1048576,
+ "maxOutputTokens": 1048576,
+ "efforts": ["low", "medium", "high", "max"],
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xd/deepseek-deepseek-v4-flash-vision-exp",
+ "aliases": ["deepseek/deepseek-v4-flash-vision-exp"],
+ "defaults": {
+ "name": "DeepSeek V4 Flash Vision Exp",
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "xd/tencent-hy4-preview",
+ "aliases": ["tencent/hy4-preview"],
+ "defaults": {
+ "name": "Hy4 preview",
+ "defaultEffort": "medium"
+ }
+ },
+ {
+ "id": "qwen/qwen3.5-4b",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen3.5 4B"
+ }
+ },
+ {
+ "id": "qwen/qwen3.5-9b",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen3.5 9B"
+ }
+ },
+ {
+ "id": "google/gemma-4-12b",
+ "aliases": [],
+ "defaults": {
+ "name": "Gemma 4 12B"
+ }
+ },
+ {
+ "id": "qwen/qwen36-35b",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen3.6 35B A3B"
+ }
+ },
+ {
+ "id": "nvidia/nemotron-3.5-lightning",
+ "aliases": [],
+ "defaults": {
+ "name": "Nemotron 3.5 Lightning 30B"
+ }
+ },
+ {
+ "id": "qwen/qwen3.8-flash-next",
+ "aliases": [],
+ "defaults": {
+ "name": "Qwen3.8 Flash-Next"
+ }
+ }
]
}
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index 68a0e3c2f7..4f780fd234 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -1,3 +1,4 @@
+import { expandedRegistryEntries } from "../modelMetadataLayers.js";
/**
* 目录校验 + 内置供应商契约(2026-07-19 模型列表统一重构后的新契约)。
*
@@ -12,33 +13,38 @@
* 「运行时注入后的目录」上行为正确(用注入 fixture 模拟生产形态)。
*/
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect } from "vitest";
-import { BUNDLED_CATALOG, parseCatalog } from '../catalog.js';
+import { BUNDLED_CATALOG, parseCatalog } from "../catalog.js";
import {
buildRegistry,
sourcesForModel,
modelSupportsFastMode,
sessionModelSupportsFastMode,
-} from '../registry.js';
-import type { AgentKind, Catalog, CatalogModel } from '../types.js';
+} from "../registry.js";
+import type { AgentKind, Catalog, CatalogModel } from "../types.js";
/** Claude/Codex 动态清单供应商;Anthropic/OpenAI 的 Pi 目录是独立静态快照。 */
-const DYNAMIC_PROVIDER_IDS = ['anthropic', 'openai', 'xd'] as const;
+const DYNAMIC_PROVIDER_IDS = ["anthropic", "openai", "xd"] as const;
/** xAI 随包 fallback 元数据清单。 */
const EXPECTED_XAI_IDS = [
- 'xai/grok-4.6',
- 'xai/grok-4.5',
- 'xai/grok-4.3',
- 'xai/grok-build-0.1',
- 'xai/grok-4.20-multi-agent-0309',
- 'xai/grok-4.20-0309-reasoning',
- 'xai/grok-4.20-0309-non-reasoning',
- 'xai/grok-4.20',
- 'xai/grok-code-fast',
+ "xai/grok-4.6",
+ "xai/grok-4.5",
+ "xai/grok-4.3",
+ "xai/grok-build-0.1",
+ "xai/grok-4.20-multi-agent-0309",
+ "xai/grok-4.20-0309-reasoning",
+ "xai/grok-4.20-0309-non-reasoning",
+ "xai/grok-4.20",
+ "xai/grok-code-fast",
+];
+const EXPECTED_XAI_PI_IDS = [
+ "grok-4.3",
+ "grok-4.5",
+ "grok-4.6",
+ "grok-build-0.1",
];
-const EXPECTED_XAI_PI_IDS = ['grok-4.3', 'grok-4.5', 'grok-4.6', 'grok-build-0.1'];
function provider(id: string) {
const p = BUNDLED_CATALOG.providers.find((x) => x.id === id);
@@ -48,13 +54,14 @@ function provider(id: string) {
function registryEntryForRoute(providerId: string, modelId: string) {
const registry = BUNDLED_CATALOG.modelRegistry;
- if (!registry) throw new Error('missing bundled modelRegistry');
- const entry = registry.models.find((candidate) =>
+ if (!registry) throw new Error("missing bundled modelRegistry");
+ const entry = expandedRegistryEntries(registry).find((candidate) =>
candidate.routes.some(
(route) => route.providerId === providerId && route.modelId === modelId,
),
);
- if (!entry) throw new Error(`missing registry route ${providerId}/${modelId}`);
+ if (!entry)
+ throw new Error(`missing registry route ${providerId}/${modelId}`);
return entry;
}
@@ -74,133 +81,178 @@ function model(id: string, extra: Partial<CatalogModel> = {}): CatalogModel {
function runtimeCatalog(): Catalog {
const clone = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
for (const p of clone.providers) {
- if (p.id === 'anthropic') {
+ if (p.id === "anthropic") {
const anthropic = [
- model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000, supportsFastMode: true }),
- model('claude-sonnet-4-6', { name: 'Sonnet 4.6', contextWindow: 1_000_000 }),
+ model("claude-opus-4-8", {
+ name: "Opus 4.8",
+ contextWindow: 1_000_000,
+ supportsFastMode: true,
+ }),
+ model("claude-sonnet-4-6", {
+ name: "Sonnet 4.6",
+ contextWindow: 1_000_000,
+ }),
];
- p.models['claude-code'] = anthropic;
+ p.models["claude-code"] = anthropic;
p.models.codex = anthropic;
}
- if (p.id === 'openai') {
- p.models.codex = [model('gpt-5.5', { name: 'GPT-5.5', supportsFastMode: true })];
- p.models['claude-code'] = [model('chatgpt/gpt-5.5', { name: 'GPT-5.5', supportsFastMode: true })];
+ if (p.id === "openai") {
+ p.models.codex = [
+ model("gpt-5.5", { name: "GPT-5.5", supportsFastMode: true }),
+ ];
+ p.models["claude-code"] = [
+ model("chatgpt/gpt-5.5", { name: "GPT-5.5", supportsFastMode: true }),
+ ];
}
- if (p.id === 'xd') {
- p.models['claude-code'] = [
- model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000, supportsFastMode: false }),
- model('gpt-5.5', { name: 'GPT-5.5', supportsFastMode: true }),
+ if (p.id === "xd") {
+ p.models["claude-code"] = [
+ model("claude-opus-4-8", {
+ name: "Opus 4.8",
+ contextWindow: 1_000_000,
+ supportsFastMode: false,
+ }),
+ model("gpt-5.5", { name: "GPT-5.5", supportsFastMode: true }),
+ ];
+ p.models.codex = [
+ model("gpt-5.5", { name: "GPT-5.5", supportsFastMode: true }),
];
- p.models.codex = [model('gpt-5.5', { name: 'GPT-5.5', supportsFastMode: true })];
}
}
return clone;
}
-describe('bundled catalog validity (dynamic-first contract)', () => {
- it('parses & passes schema validation', () => {
+describe("bundled catalog validity (dynamic-first contract)", () => {
+ it("parses & passes schema validation", () => {
expect(() => parseCatalog(BUNDLED_CATALOG)).not.toThrow();
});
- it('keeps selectable registry efforts self-consistent with defaultEffort', () => {
+ it("keeps selectable registry efforts self-consistent with defaultEffort", () => {
const registry = BUNDLED_CATALOG.modelRegistry;
expect(registry).toBeDefined();
- for (const entry of registry!.models) {
- for (const agent of new Set(entry.routes.flatMap((route) => route.agents))) {
+ for (const entry of expandedRegistryEntries(registry!)) {
+ for (const agent of new Set(
+ entry.routes.flatMap((route) => route.agents),
+ )) {
const override = entry.perAgent?.[agent];
const efforts = override?.efforts ?? entry.efforts ?? [];
const defaultEffort = override?.defaultEffort ?? entry.defaultEffort;
if (efforts.length === 0) continue;
// Disabled legacy entries may rely on discovery for a default, but must
// never declare a default that the target engine does not support.
- if (entry.defaultEnabled === false && defaultEffort === undefined) continue;
+ if (entry.defaultEnabled === false && defaultEffort === undefined)
+ continue;
expect(defaultEffort, `${entry.id}/${agent}`).toBeTruthy();
expect(efforts, `${entry.id}/${agent}`).toContain(defaultEffort);
}
}
- expect(registryEntryForRoute('openai', 'gpt-5.6-luna')).toMatchObject({
- efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
- defaultEffort: 'medium',
+ expect(registryEntryForRoute("openai", "gpt-5.6-luna")).toMatchObject({
+ efforts: ["low", "medium", "high", "xhigh", "max"],
+ defaultEffort: "medium",
});
- expect(registryEntryForRoute('openai', 'gpt-5.4-nano')).toMatchObject({
- efforts: ['low', 'medium', 'high', 'xhigh'],
+ expect(registryEntryForRoute("openai", "gpt-5.4-nano")).toMatchObject({
+ efforts: ["low", "medium", "high", "xhigh"],
defaultEnabled: false,
});
// Corrections must forward-fix: same updatedAt + different content is a
// conflict, so cached clients would keep the entries without defaultEffort.
- expect(Date.parse(registry!.updatedAt)).toBeGreaterThan(Date.parse('2026-08-05T00:00:00.000Z'));
+ expect(Date.parse(registry!.updatedAt)).toBeGreaterThan(
+ Date.parse("2026-08-05T00:00:00.000Z"),
+ );
});
- it('has exactly the built-in providers in stable order', () => {
+ it("has exactly the built-in providers in stable order", () => {
// 顺序契约:决定选择器分段顺序与 deriveAvailableModels first-wins 优先级。
- expect(BUNDLED_CATALOG.providers.map((p) => p.id)).toEqual(['anthropic', 'openai', 'xai', 'xd', 'gemini']);
- expect(BUNDLED_CATALOG.providers.every((p) => p.source === 'builtin')).toBe(true);
+ expect(BUNDLED_CATALOG.providers.map((p) => p.id)).toEqual([
+ "anthropic",
+ "openai",
+ "xai",
+ "xd",
+ "gemini",
+ ]);
+ expect(BUNDLED_CATALOG.providers.every((p) => p.source === "builtin")).toBe(
+ true,
+ );
});
- it('dynamic providers keep Claude/Codex empty while Pi ships its independent native baseline', () => {
+ it("dynamic providers keep Claude/Codex empty while Pi ships its independent native baseline", () => {
for (const id of DYNAMIC_PROVIDER_IDS) {
const p = provider(id);
for (const agent of p.agents) {
- if (agent === 'pi' && (id === 'anthropic' || id === 'openai')) {
- expect(p.models.pi?.length, `${id} must ship Pi native models`).toBeGreaterThan(0);
+ if (agent === "pi" && (id === "anthropic" || id === "openai")) {
+ expect(
+ p.models.pi?.length,
+ `${id} must ship Pi native models`,
+ ).toBeGreaterThan(0);
} else {
- expect(p.models[agent], `${id} models[${agent}] must exist (empty array)`).toEqual([]);
+ expect(
+ p.models[agent],
+ `${id} models[${agent}] must exist (empty array)`,
+ ).toEqual([]);
}
}
}
});
- it('ships Pi-native subscription models plus explicit Astra support, independent of Registry', () => {
- expect(provider('openai').models.pi?.map((model) => model.id)).toEqual([
- 'chatgpt/gpt-5.3-codex-spark',
- 'chatgpt/gpt-5.4',
- 'chatgpt/gpt-5.4-mini',
- 'chatgpt/gpt-5.5',
- 'chatgpt/gpt-5.6-luna',
- 'chatgpt/gpt-5.6-sol',
- 'chatgpt/gpt-5.6-terra',
- 'chatgpt/gpt-6-astra',
+ it("ships Pi-native subscription models plus explicit Astra support, independent of Registry", () => {
+ expect(provider("openai").models.pi?.map((model) => model.id)).toEqual([
+ "chatgpt/gpt-5.3-codex-spark",
+ "chatgpt/gpt-5.4",
+ "chatgpt/gpt-5.4-mini",
+ "chatgpt/gpt-5.5",
+ "chatgpt/gpt-5.6-luna",
+ "chatgpt/gpt-5.6-sol",
+ "chatgpt/gpt-5.6-terra",
+ "chatgpt/gpt-6-astra",
]);
expect(
- provider('openai').models.pi?.some((model) => model.id === 'chatgpt/gpt-6'),
+ provider("openai").models.pi?.some(
+ (model) => model.id === "chatgpt/gpt-6",
+ ),
).toBe(false);
- expect(provider('anthropic').models.pi).toHaveLength(14);
+ expect(provider("anthropic").models.pi).toHaveLength(14);
});
- it('xai ships a static fallback list and Pi official metadata', () => {
- const xai = provider('xai');
- expect((xai.models['claude-code'] ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_IDS);
+ it("xai ships a static fallback list and Pi official metadata", () => {
+ const xai = provider("xai");
+ expect((xai.models["claude-code"] ?? []).map((m) => m.id)).toEqual(
+ EXPECTED_XAI_IDS,
+ );
expect((xai.models.codex ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_IDS);
expect((xai.models.pi ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_PI_IDS);
- expect(xai.models.pi?.find((m) => m.id === 'grok-4.6')).toMatchObject({
- piApi: 'openai-responses',
+ expect(xai.models.pi?.find((m) => m.id === "grok-4.6")).toMatchObject({
+ piApi: "openai-responses",
contextWindow: 500_000,
maxOutput: 500_000,
supportsImageInput: true,
- efforts: ['low', 'medium', 'high', 'xhigh'],
- defaultEffort: 'high',
+ efforts: ["low", "medium", "high", "xhigh"],
+ defaultEffort: "high",
});
- expect(xai.models['claude-code']?.find((m) => m.id === 'xai/grok-4.6')).toMatchObject({
+ expect(
+ xai.models["claude-code"]?.find((m) => m.id === "xai/grok-4.6"),
+ ).toMatchObject({
contextWindow: 500_000,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'high',
+ efforts: ["low", "medium", "high"],
+ defaultEffort: "high",
});
});
- it('xai ships both Grok Imagine subscription image models', () => {
- expect(provider('xai').imageModels).toEqual([
- { id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' },
- { id: 'xai/grok-imagine-image-quality', name: 'Grok Imagine Image (Quality)' },
+ it("xai ships both Grok Imagine subscription image models", () => {
+ expect(provider("xai").imageModels).toEqual([
+ { id: "xai/grok-imagine-image", name: "Grok Imagine Image" },
+ {
+ id: "xai/grok-imagine-image-quality",
+ name: "Grok Imagine Image (Quality)",
+ },
]);
});
- it('xai ships the Grok Imagine subscription video model', () => {
- expect(provider('xai').videoModels).toEqual([
- { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ it("xai ships the Grok Imagine subscription video model", () => {
+ expect(provider("xai").videoModels).toEqual([
+ { id: "xai/grok-imagine-video", name: "Grok Imagine Video" },
]);
});
- it('provides routing + a models[agent] array for every agent the provider declares', () => {
+ it("provides routing + a models[agent] array for every agent the provider declares", () => {
for (const p of BUNDLED_CATALOG.providers) {
for (const a of p.agents) {
expect(p.routing[a], `${p.id} routing[${a}]`).toBeTruthy();
@@ -209,102 +261,131 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
}
});
- it('declares native Responses custom-tool support on each built-in Codex Responses route', () => {
- expect(provider('openai').routing.codex?.supportsResponsesCustomTools).toBe(true);
- expect(provider('xd').routing.codex?.supportsResponsesCustomTools).toBe(false);
- expect(provider('xai').routing.codex?.supportsResponsesCustomTools).toBe(false);
+ it("declares native Responses custom-tool support on each built-in Codex Responses route", () => {
+ expect(provider("openai").routing.codex?.supportsResponsesCustomTools).toBe(
+ true,
+ );
+ expect(provider("xd").routing.codex?.supportsResponsesCustomTools).toBe(
+ false,
+ );
+ expect(provider("xai").routing.codex?.supportsResponsesCustomTools).toBe(
+ false,
+ );
});
- it('declares access separately from model names', () => {
- expect(provider('anthropic').access).toEqual({ kind: 'subscription', product: 'Claude.ai' });
- expect(provider('openai').access).toEqual({ kind: 'subscription', product: 'ChatGPT' });
- expect(provider('xai').access).toEqual({ kind: 'subscription', product: 'SuperGrok' });
- expect(provider('xd').access).toEqual({ kind: 'managed' });
+ it("declares access separately from model names", () => {
+ expect(provider("anthropic").access).toEqual({
+ kind: "subscription",
+ product: "Claude.ai",
+ });
+ expect(provider("openai").access).toEqual({
+ kind: "subscription",
+ product: "ChatGPT",
+ });
+ expect(provider("xai").access).toEqual({
+ kind: "subscription",
+ product: "SuperGrok",
+ });
+ expect(provider("xd").access).toEqual({ kind: "managed" });
for (const p of BUNDLED_CATALOG.providers) {
- if (p.access?.kind !== 'subscription') continue;
+ if (p.access?.kind !== "subscription") continue;
const product = p.access.product;
for (const models of Object.values(p.models)) {
- expect(models?.every((m) => !m.name.includes(product) && !m.name.includes('订阅'))).toBe(true);
+ expect(
+ models?.every(
+ (m) => !m.name.includes(product) && !m.name.includes("订阅"),
+ ),
+ ).toBe(true);
}
}
});
- it('rejects malformed provider access metadata', () => {
- for (const access of [null, { kind: 'metered' }, { kind: 'subscription' }, { kind: 'subscription', product: ' ' }]) {
+ it("rejects malformed provider access metadata", () => {
+ for (const access of [
+ null,
+ { kind: "metered" },
+ { kind: "subscription" },
+ { kind: "subscription", product: " " },
+ ]) {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
(bad.providers[0] as unknown as Record<string, unknown>).access = access;
expect(() => parseCatalog(bad)).toThrow(/access/);
}
});
- it('model.icon 可选:合法字符串放行,空白串拒绝(展示图标以 AI Gateway / 目录设定为准)', () => {
+ it("model.icon 可选:合法字符串放行,空白串拒绝(展示图标以 AI Gateway / 目录设定为准)", () => {
const ok = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xaiOk = ok.providers.find((p) => p.id === 'xai')!;
- xaiOk.models['claude-code']![0].icon = 'claude';
+ const xaiOk = ok.providers.find((p) => p.id === "xai")!;
+ xaiOk.models["claude-code"]![0].icon = "claude";
expect(() => parseCatalog(ok)).not.toThrow();
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xaiBad = bad.providers.find((p) => p.id === 'xai')!;
- xaiBad.models['claude-code']![0].icon = ' ';
+ const xaiBad = bad.providers.find((p) => p.id === "xai")!;
+ xaiBad.models["claude-code"]![0].icon = " ";
expect(() => parseCatalog(bad)).toThrow(/icon/);
});
- it('accepts the four portable piApi values and rejects unknown PI protocols', () => {
+ it("accepts the four portable piApi values and rejects unknown PI protocols", () => {
for (const piApi of [
- 'anthropic-messages',
- 'openai-responses',
- 'openai-completions',
- 'google-generative-ai',
+ "anthropic-messages",
+ "openai-responses",
+ "openai-completions",
+ "google-generative-ai",
] as const) {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- catalog.providers.find((provider) => provider.id === 'xai')!
- .models['claude-code']![0]!.piApi = piApi;
+ catalog.providers.find((provider) => provider.id === "xai")!.models[
+ "claude-code"
+ ]![0]!.piApi = piApi;
expect(() => parseCatalog(catalog)).not.toThrow();
}
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- (bad.providers.find((provider) => provider.id === 'xai')!
- .models['claude-code']![0] as unknown as Record<string, unknown>).piApi = 'claude-v1';
+ (
+ bad.providers.find((provider) => provider.id === "xai")!.models[
+ "claude-code"
+ ]![0] as unknown as Record<string, unknown>
+ ).piApi = "claude-v1";
expect(() => parseCatalog(bad)).toThrow(/piApi/);
});
- it('ships custom-provider presets (OSS 热更的第三方模板)', () => {
+ it("ships custom-provider presets (OSS 热更的第三方模板)", () => {
const presets = BUNDLED_CATALOG.presets ?? [];
expect(presets.length).toBeGreaterThan(0);
- expect(presets.map((p) => p.id)).toContain('openrouter');
+ expect(presets.map((p) => p.id)).toContain("openrouter");
});
- it('DeepSeek 预设携带厂商文档确认的 1M contextWindow (#735)', () => {
+ it("DeepSeek 预设携带厂商文档确认的 1M contextWindow (#735)", () => {
// 官方 V4 起全线 1M(api-docs.deepseek.com news260424);预设不带时
// buildUserProvider 回落 200K 保守默认,长上下文模型被错误降级。
const presets = BUNDLED_CATALOG.presets ?? [];
- const deepseek = presets.find((p) => p.id === 'deepseek');
+ const deepseek = presets.find((p) => p.id === "deepseek");
expect(deepseek).toBeDefined();
for (const [agent, rt] of Object.entries(deepseek!.runtimes)) {
- for (const id of ['deepseek-v4-flash', 'deepseek-v4-pro']) {
+ for (const id of ["deepseek-v4-flash", "deepseek-v4-pro"]) {
const m = rt!.models.find((x) => x.id === id);
expect(m?.contextWindow, `${agent}/${id}`).toBe(1_000_000);
}
}
// OpenRouter 托管的同款模型页面同样标注 1,048,576,取与仓库口径一致的 1M。
- const openrouter = presets.find((p) => p.id === 'openrouter');
+ const openrouter = presets.find((p) => p.id === "openrouter");
expect(
- openrouter?.runtimes['claude-code']?.models.find((m) => m.id === 'deepseek/deepseek-v4-pro')
- ?.contextWindow,
+ openrouter?.runtimes["claude-code"]?.models.find(
+ (m) => m.id === "deepseek/deepseek-v4-pro",
+ )?.contextWindow,
).toBe(1_000_000);
expect(deepseek?.runtimes.pi).toMatchObject({
- wireProtocol: 'openai-chat',
+ wireProtocol: "openai-chat",
models: [
- { id: 'deepseek-v4-flash' },
- { id: 'deepseek-v4-flash-vision-exp' },
- { id: 'deepseek-v4-pro' },
+ { id: "deepseek-v4-flash" },
+ { id: "deepseek-v4-flash-vision-exp" },
+ { id: "deepseek-v4-pro" },
],
});
});
- it('Kimi Code(编程计划)按各 harness 的权威目录保留 contextWindow', () => {
+ it("Kimi Code(编程计划)按各 harness 的权威目录保留 contextWindow", () => {
const presets = BUNDLED_CATALOG.presets ?? [];
- const kimiCode = presets.find((p) => p.id === 'moonshot-kimi-code');
+ const kimiCode = presets.find((p) => p.id === "moonshot-kimi-code");
expect(kimiCode).toBeDefined();
for (const [agent, rt] of Object.entries(kimiCode!.runtimes)) {
for (const m of rt!.models) {
@@ -313,92 +394,111 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
`${agent}/${m.id} 缺 contextWindow`,
).toBe(true);
}
- expect(rt!.models.find((m) => m.id === 'k3')?.contextWindow, `${agent}/k3`).toBe(
- agent === 'pi' ? 1_048_576 : 262_144,
- );
+ expect(
+ rt!.models.find((m) => m.id === "k3")?.contextWindow,
+ `${agent}/k3`,
+ ).toBe(agent === "pi" ? 1_048_576 : 262_144);
}
});
- it('ships Codex support metadata for the current XD gateway model set', () => {
+ it("ships Codex support metadata for the current XD gateway model set", () => {
const expected = {
- 'qwen/qwen3.7-max': 'Qwen 3.7 Max',
- 'moonshot/kimi-k3': 'Kimi K3',
- 'z-ai/glm-5.2': 'GLM-5.2',
- 'deepseek/deepseek-v4-pro': 'DeepSeek V4 Pro',
- 'deepseek/deepseek-v4-flash': 'DeepSeek V4 Flash',
- 'bytedance-seed/seed-2.1-pro': 'Seed 2.1 Pro',
- 'qwen/qwen3.8-max-preview': 'Qwen 3.8 Max Preview',
+ "qwen/qwen3.7-max": "Qwen 3.7 Max",
+ "moonshot/kimi-k3": "Kimi K3",
+ "z-ai/glm-5.2": "GLM-5.2",
+ "deepseek/deepseek-v4-pro": "DeepSeek V4 Pro",
+ "deepseek/deepseek-v4-flash": "DeepSeek V4 Flash",
+ "bytedance-seed/seed-2.1-pro": "Seed 2.1 Pro",
+ "qwen/qwen3.8-max-preview": "Qwen 3.8 Max Preview",
};
for (const [id, name] of Object.entries(expected)) {
- const entry = registryEntryForRoute('xd', id);
+ const entry = registryEntryForRoute("xd", id);
const route = entry.routes.find(
- (candidate) => candidate.providerId === 'xd' && candidate.modelId === id,
+ (candidate) =>
+ candidate.providerId === "xd" && candidate.modelId === id,
);
expect(entry, id).toMatchObject({ name });
- expect(route?.agents, id).toEqual(['claude-code', 'codex']);
+ expect(route?.agents, id).toEqual(["claude-code", "codex"]);
}
- expect(registryEntryForRoute('xd', 'bytedance-seed/seed-2.1-pro')).toMatchObject({
- efforts: ['minimal', 'low', 'medium', 'high'],
- defaultEffort: 'medium',
+ expect(
+ registryEntryForRoute("xd", "bytedance-seed/seed-2.1-pro"),
+ ).toMatchObject({
+ efforts: ["minimal", "low", "medium", "high"],
+ defaultEffort: "medium",
supportsFastMode: false,
perAgent: {
- 'claude-code': {
- efforts: ['low', 'medium', 'high'],
+ "claude-code": {
+ efforts: ["low", "medium", "high"],
},
},
});
- expect(registryEntryForRoute('xd', 'moonshot/kimi-k3')).toMatchObject({
- efforts: ['low', 'medium', 'high', 'max'],
- defaultEffort: 'medium',
+ expect(registryEntryForRoute("xd", "moonshot/kimi-k3")).toMatchObject({
+ efforts: ["low", "medium", "high", "max"],
+ defaultEffort: "medium",
supportsFastMode: false,
});
- expect(registryEntryForRoute('xd', 'qwen/qwen3.8-max-preview')).toMatchObject({
- efforts: ['low', 'high', 'xhigh'],
- defaultEffort: 'high',
+ expect(
+ registryEntryForRoute("xd", "qwen/qwen3.8-max-preview"),
+ ).toMatchObject({
+ efforts: ["low", "high", "xhigh"],
+ defaultEffort: "high",
supportsFastMode: false,
});
- expect(registryEntryForRoute('xd', 'z-ai/glm-5.2')).toMatchObject({
- efforts: ['minimal', 'high', 'max'],
- defaultEffort: 'high',
+ expect(registryEntryForRoute("xd", "z-ai/glm-5.2")).toMatchObject({
+ efforts: ["minimal", "high", "max"],
+ defaultEffort: "high",
supportsFastMode: false,
perAgent: {
- 'claude-code': {
- efforts: ['high', 'max'],
+ "claude-code": {
+ efforts: ["high", "max"],
},
},
});
- for (const id of ['deepseek/deepseek-v4-pro', 'deepseek/deepseek-v4-flash']) {
- expect(registryEntryForRoute('xd', id), id).toMatchObject({
- efforts: ['low', 'high', 'max'],
- defaultEffort: 'high',
+ for (const id of [
+ "deepseek/deepseek-v4-pro",
+ "deepseek/deepseek-v4-flash",
+ ]) {
+ expect(registryEntryForRoute("xd", id), id).toMatchObject({
+ efforts: ["low", "high", "max"],
+ defaultEffort: "high",
supportsFastMode: false,
});
}
for (const id of [
- 'bytedance-seed/seed-2.1-pro',
- 'moonshot/kimi-k3',
- 'qwen/qwen3.8-max-preview',
+ "bytedance-seed/seed-2.1-pro",
+ "moonshot/kimi-k3",
+ "qwen/qwen3.8-max-preview",
]) {
- expect(registryEntryForRoute('xd', id), id).not.toHaveProperty('description');
+ expect(registryEntryForRoute("xd", id), id).not.toHaveProperty(
+ "description",
+ );
}
});
- it('enables DeepSeek V4 Flash by default', () => {
+ it("enables DeepSeek V4 Flash by default", () => {
expect(
- registryEntryForRoute('xd', 'deepseek/deepseek-v4-flash').defaultEnabled,
+ registryEntryForRoute("xd", "deepseek/deepseek-v4-flash").defaultEnabled,
).toBeUndefined();
});
- it('rejects legacy or ad-hoc top-level metadata blocks', () => {
- const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Record<string, unknown>;
+ it("rejects legacy or ad-hoc top-level metadata blocks", () => {
+ const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Record<
+ string,
+ unknown
+ >;
bad.cindyModelMeta = { version: 1, models: {} };
- expect(() => parseCatalog(bad)).toThrow(/catalog\.cindyModelMeta is not allowed/);
+ expect(() => parseCatalog(bad)).toThrow(
+ /catalog\.cindyModelMeta is not allowed/,
+ );
});
- it('models are grouped per-agent (no flat array, no rogue agent keys)', () => {
+ it("models are grouped per-agent (no flat array, no rogue agent keys)", () => {
for (const p of BUNDLED_CATALOG.providers) {
- expect(Array.isArray(p.models), `${p.id} models must be a per-agent map`).toBe(false);
+ expect(
+ Array.isArray(p.models),
+ `${p.id} models must be a per-agent map`,
+ ).toBe(false);
for (const key of Object.keys(p.models)) {
expect(p.agents, `${p.id} stray models[${key}]`).toContain(key);
}
@@ -406,22 +506,22 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
});
});
-describe('titleModel 契约(动态供应商豁免静态存在性校验)', () => {
- it('builtin providers configure titleModel for one-shot titles', () => {
- expect(provider('anthropic').titleModel).toBe('claude-haiku-4-5');
- expect(provider('openai').titleModel).toBe('gpt-5.4-mini');
- expect(provider('xd').titleModel).toBe('gpt-5.4-mini');
+describe("titleModel 契约(动态供应商豁免静态存在性校验)", () => {
+ it("builtin providers configure titleModel for one-shot titles", () => {
+ expect(provider("anthropic").titleModel).toBe("claude-haiku-4-5");
+ expect(provider("openai").titleModel).toBe("gpt-5.4-mini");
+ expect(provider("xd").titleModel).toBe("gpt-5.4-mini");
});
- it('parseCatalog allows titleModel on a dynamic-list provider (all models empty)', () => {
+ it("parseCatalog allows titleModel on a dynamic-list provider (all models empty)", () => {
// bundled 的 anthropic/openai/xd 正是这种形态,上面的 parse 测试已覆盖;这里显式守语义。
expect(() => parseCatalog(BUNDLED_CATALOG)).not.toThrow();
});
- it('parseCatalog still rejects titleModel not found in a static (non-empty) list', () => {
+ it("parseCatalog still rejects titleModel not found in a static (non-empty) list", () => {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xai = bad.providers.find((p) => p.id === 'xai')!;
- xai.titleModel = 'no-such-model';
+ const xai = bad.providers.find((p) => p.id === "xai")!;
+ xai.titleModel = "no-such-model";
expect(() => parseCatalog(bad)).toThrow(/titleModel/);
});
});
@@ -431,13 +531,13 @@ describe('titleModel 契约(动态供应商豁免静态存在性校验)', () =>
* 详注见 git 历史;要点:模型清单整体活在 `<ns>/` 命名空间的 (provider, agent)
* 必须声明 modelPrefixes,否则会话内 claude-* 辅助请求会被误路由。
*/
-describe('routing modelPrefixes 服务范围契约 (issue #886)', () => {
- it('模型清单整体带命名空间前缀的 (provider, agent) 必须声明 modelPrefixes,且覆盖全部模型 id', () => {
+describe("routing modelPrefixes 服务范围契约 (issue #886)", () => {
+ it("模型清单整体带命名空间前缀的 (provider, agent) 必须声明 modelPrefixes,且覆盖全部模型 id", () => {
for (const p of BUNDLED_CATALOG.providers) {
for (const agent of p.agents) {
const models = p.models[agent] ?? [];
if (models.length === 0) continue;
- const allNamespaced = models.every((m) => m.id.includes('/'));
+ const allNamespaced = models.every((m) => m.id.includes("/"));
if (!allNamespaced) continue;
const prefixes = p.routing[agent]?.modelPrefixes;
expect(
@@ -454,19 +554,26 @@ describe('routing modelPrefixes 服务范围契约 (issue #886)', () => {
}
});
- it('桥接型动态供应商(openai cc)的 modelPrefixes 保持声明(清单为空时范围门依然生效)', () => {
+ it("桥接型动态供应商(openai cc)的 modelPrefixes 保持声明(清单为空时范围门依然生效)", () => {
// openai claude-code 的动态清单全部落在 chatgpt/ 命名空间;静态清单虽空,
// 路由范围门必须常驻——否则 cc 会话的 claude-* 辅助请求会被误送 chatgpt 后端。
- expect(provider('openai').routing['claude-code']?.modelPrefixes).toEqual(['chatgpt/']);
- expect(provider('xai').routing['claude-code']?.modelPrefixes).toEqual(['xai/']);
- expect(provider('xai').routing.codex?.modelPrefixes).toEqual(['xai/']);
+ expect(provider("openai").routing["claude-code"]?.modelPrefixes).toEqual([
+ "chatgpt/",
+ ]);
+ expect(provider("xai").routing["claude-code"]?.modelPrefixes).toEqual([
+ "xai/",
+ ]);
+ expect(provider("xai").routing.codex?.modelPrefixes).toEqual(["xai/"]);
});
- it('声明的前缀必须是 `<ns>/` 命名空间形态', () => {
+ it("声明的前缀必须是 `<ns>/` 命名空间形态", () => {
for (const p of BUNDLED_CATALOG.providers) {
for (const agent of p.agents) {
for (const prefix of p.routing[agent]?.modelPrefixes ?? []) {
- expect(prefix, `${p.id} routing[${agent}] prefix '${prefix}'`).toMatch(/^[a-zA-Z0-9_-]+\/$/);
+ expect(
+ prefix,
+ `${p.id} routing[${agent}] prefix '${prefix}'`,
+ ).toMatch(/^[a-zA-Z0-9_-]+\/$/);
}
}
}
@@ -474,95 +581,197 @@ describe('routing modelPrefixes 服务范围契约 (issue #886)', () => {
it('parseCatalog 拒绝非命名空间形态的 modelPrefixes(如裸 "claude")', () => {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xai = bad.providers.find((p) => p.id === 'xai')!;
- xai.routing['claude-code'] = { ...xai.routing['claude-code']!, modelPrefixes: ['claude'] };
+ const xai = bad.providers.find((p) => p.id === "xai")!;
+ xai.routing["claude-code"] = {
+ ...xai.routing["claude-code"]!,
+ modelPrefixes: ["claude"],
+ };
expect(() => parseCatalog(bad)).toThrow(/modelPrefixes/);
});
- it('parseCatalog 拒绝空数组 modelPrefixes(声明了就必须有内容)', () => {
+ it("parseCatalog 拒绝空数组 modelPrefixes(声明了就必须有内容)", () => {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xai = bad.providers.find((p) => p.id === 'xai')!;
- xai.routing['claude-code'] = { ...xai.routing['claude-code']!, modelPrefixes: [] };
+ const xai = bad.providers.find((p) => p.id === "xai")!;
+ xai.routing["claude-code"] = {
+ ...xai.routing["claude-code"]!,
+ modelPrefixes: [],
+ };
expect(() => parseCatalog(bad)).toThrow(/modelPrefixes/);
});
});
-describe('routing wireProtocol per-agent 契约', () => {
- it('parseCatalog 拒绝 claude-code 使用 openai-chat', () => {
+describe("routing wireProtocol per-agent 契约", () => {
+ it("parseCatalog 拒绝 claude-code 使用 openai-chat", () => {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const anthropic = bad.providers.find((p) => p.id === 'anthropic')!;
- anthropic.routing['claude-code'] = { ...anthropic.routing['claude-code']!, wireProtocol: 'openai-chat' };
+ const anthropic = bad.providers.find((p) => p.id === "anthropic")!;
+ anthropic.routing["claude-code"] = {
+ ...anthropic.routing["claude-code"]!,
+ wireProtocol: "openai-chat",
+ };
expect(() => parseCatalog(bad)).toThrow(/openai-chat/);
});
- it('parseCatalog 允许 codex 使用 anthropic-messages(由本地 Responses→Anthropic bridge 接管)', () => {
+ it("parseCatalog 允许 codex 使用 anthropic-messages(由本地 Responses→Anthropic bridge 接管)", () => {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xai = bad.providers.find((p) => p.id === 'xai')!;
- xai.routing.codex = { ...xai.routing.codex!, wireProtocol: 'anthropic-messages' };
- expect(parseCatalog(bad).providers.find((p) => p.id === 'xai')?.routing.codex?.wireProtocol)
- .toBe('anthropic-messages');
+ const xai = bad.providers.find((p) => p.id === "xai")!;
+ xai.routing.codex = {
+ ...xai.routing.codex!,
+ wireProtocol: "anthropic-messages",
+ };
+ expect(
+ parseCatalog(bad).providers.find((p) => p.id === "xai")?.routing.codex
+ ?.wireProtocol,
+ ).toBe("anthropic-messages");
});
});
-describe('runtime-injected registry semantics(生产形态:动态清单注入后)', () => {
- const views = buildRegistry(runtimeCatalog(), { anthropic: true, openai: true, xai: true, xd: true });
+describe("runtime-injected registry semantics(生产形态:动态清单注入后)", () => {
+ const views = buildRegistry(runtimeCatalog(), {
+ anthropic: true,
+ openai: true,
+ xai: true,
+ xd: true,
+ });
- it('claude 模型 cc 双来源(anthropic+xd);gpt cc 单来源(xd);gpt codex 双来源(openai+xd)', () => {
- expect(sourcesForModel(views, 'claude-opus-4-8', 'claude-code').map((p) => p.id).sort()).toEqual(['anthropic', 'xd']);
- expect(sourcesForModel(views, 'gpt-5.5', 'claude-code').map((p) => p.id)).toEqual(['xd']);
- expect(sourcesForModel(views, 'gpt-5.5', 'codex').map((p) => p.id).sort()).toEqual(['openai', 'xd']);
+ it("claude 模型 cc 双来源(anthropic+xd);gpt cc 单来源(xd);gpt codex 双来源(openai+xd)", () => {
+ expect(
+ sourcesForModel(views, "claude-opus-4-8", "claude-code")
+ .map((p) => p.id)
+ .sort(),
+ ).toEqual(["anthropic", "xd"]);
+ expect(
+ sourcesForModel(views, "gpt-5.5", "claude-code").map((p) => p.id),
+ ).toEqual(["xd"]);
+ expect(
+ sourcesForModel(views, "gpt-5.5", "codex")
+ .map((p) => p.id)
+ .sort(),
+ ).toEqual(["openai", "xd"]);
});
- it('xai/grok 模型只经 xAI 提供(bundled 静态清单)', () => {
- expect(sourcesForModel(views, 'xai/grok-4.3', 'codex').map((p) => p.id)).toEqual(['xai']);
- expect(sourcesForModel(views, 'xai/grok-4.3', 'claude-code').map((p) => p.id)).toEqual(['xai']);
+ it("xai/grok 模型只经 xAI 提供(bundled 静态清单)", () => {
+ expect(
+ sourcesForModel(views, "xai/grok-4.3", "codex").map((p) => p.id),
+ ).toEqual(["xai"]);
+ expect(
+ sourcesForModel(views, "xai/grok-4.3", "claude-code").map((p) => p.id),
+ ).toEqual(["xai"]);
});
- it('未注入时(bundled 原样)动态供应商零来源——不用静态数据冒充', () => {
- const bare = buildRegistry(BUNDLED_CATALOG, { anthropic: true, openai: true, xai: true, xd: true });
- expect(sourcesForModel(bare, 'claude-opus-4-8', 'claude-code')).toEqual([]);
- expect(sourcesForModel(bare, 'gpt-5.5', 'codex')).toEqual([]);
- expect(sourcesForModel(bare, 'xai/grok-4.3', 'codex').map((p) => p.id)).toEqual(['xai']);
+ it("未注入时(bundled 原样)动态供应商零来源——不用静态数据冒充", () => {
+ const bare = buildRegistry(BUNDLED_CATALOG, {
+ anthropic: true,
+ openai: true,
+ xai: true,
+ xd: true,
+ });
+ expect(sourcesForModel(bare, "claude-opus-4-8", "claude-code")).toEqual([]);
+ expect(sourcesForModel(bare, "gpt-5.5", "codex")).toEqual([]);
+ expect(
+ sourcesForModel(bare, "xai/grok-4.3", "codex").map((p) => p.id),
+ ).toEqual(["xai"]);
});
});
-describe('fast-mode per-provider resolution (model-level SSoT)', () => {
- it('modelSupportsFastMode reads the specific provider entry (false on missing provider/model)', () => {
+describe("fast-mode per-provider resolution (model-level SSoT)", () => {
+ it("modelSupportsFastMode reads the specific provider entry (false on missing provider/model)", () => {
const views = buildRegistry(runtimeCatalog(), {});
- const anthropic = views.find((p) => p.id === 'anthropic');
- const xd = views.find((p) => p.id === 'xd');
+ const anthropic = views.find((p) => p.id === "anthropic");
+ const xd = views.find((p) => p.id === "xd");
// opus per-provider 分叉:anthropic(直连,SDK 声明支持)=true,xd(网关下发 false)=false。
- expect(modelSupportsFastMode(anthropic, 'claude-opus-4-8', 'claude-code')).toBe(true);
- expect(modelSupportsFastMode(xd, 'claude-opus-4-8', 'claude-code')).toBe(false);
- expect(modelSupportsFastMode(anthropic, 'gpt-5.5', 'claude-code')).toBe(false);
- expect(modelSupportsFastMode(undefined, 'claude-opus-4-8', 'claude-code')).toBe(false);
- expect(modelSupportsFastMode(anthropic, 'claude-sonnet-4-6', 'claude-code')).toBe(false);
+ expect(
+ modelSupportsFastMode(anthropic, "claude-opus-4-8", "claude-code"),
+ ).toBe(true);
+ expect(modelSupportsFastMode(xd, "claude-opus-4-8", "claude-code")).toBe(
+ false,
+ );
+ expect(modelSupportsFastMode(anthropic, "gpt-5.5", "claude-code")).toBe(
+ false,
+ );
+ expect(
+ modelSupportsFastMode(undefined, "claude-opus-4-8", "claude-code"),
+ ).toBe(false);
+ expect(
+ modelSupportsFastMode(anthropic, "claude-sonnet-4-6", "claude-code"),
+ ).toBe(false);
});
- it('sessionModelSupportsFastMode resolves the effective source then reads its entry', () => {
+ it("sessionModelSupportsFastMode resolves the effective source then reads its entry", () => {
const both = buildRegistry(runtimeCatalog(), { xd: true, anthropic: true });
// 未显式选源 → cc 原生默认 xd;xd 的 opus supportsFastMode=false ⇒ false。
- expect(sessionModelSupportsFastMode(both, null, 'claude-opus-4-8', 'claude-code')).toBe(false);
- expect(sessionModelSupportsFastMode(both, 'anthropic', 'claude-opus-4-8', 'claude-code')).toBe(true);
- expect(sessionModelSupportsFastMode(both, null, 'claude-sonnet-4-6', 'claude-code')).toBe(false);
- expect(sessionModelSupportsFastMode(buildRegistry(runtimeCatalog(), {}), null, 'claude-opus-4-8', 'claude-code')).toBe(false);
+ expect(
+ sessionModelSupportsFastMode(
+ both,
+ null,
+ "claude-opus-4-8",
+ "claude-code",
+ ),
+ ).toBe(false);
+ expect(
+ sessionModelSupportsFastMode(
+ both,
+ "anthropic",
+ "claude-opus-4-8",
+ "claude-code",
+ ),
+ ).toBe(true);
+ expect(
+ sessionModelSupportsFastMode(
+ both,
+ null,
+ "claude-sonnet-4-6",
+ "claude-code",
+ ),
+ ).toBe(false);
+ expect(
+ sessionModelSupportsFastMode(
+ buildRegistry(runtimeCatalog(), {}),
+ null,
+ "claude-opus-4-8",
+ "claude-code",
+ ),
+ ).toBe(false);
});
- it('parser ALLOWS per-provider fast divergence(同 id 跨 provider fast 不参与一致性校验)', () => {
+ it("parser ALLOWS per-provider fast divergence(同 id 跨 provider fast 不参与一致性校验)", () => {
const divergent: Catalog = {
- version: '1',
+ version: "1",
providers: [
{
- id: 'p-fast', name: 'P-Fast', source: 'builtin', agents: ['claude-code'],
- auth: { method: 'managed' },
- routing: { 'claude-code': { upstream: 'https://a', authStrategy: 'gateway-key' } },
- models: { 'claude-code': [model('m1', { name: 'M1', supportsFastMode: true })] },
+ id: "p-fast",
+ name: "P-Fast",
+ source: "builtin",
+ agents: ["claude-code"],
+ auth: { method: "managed" },
+ routing: {
+ "claude-code": {
+ upstream: "https://a",
+ authStrategy: "gateway-key",
+ },
+ },
+ models: {
+ "claude-code": [
+ model("m1", { name: "M1", supportsFastMode: true }),
+ ],
+ },
},
{
- id: 'p-slow', name: 'P-Slow', source: 'builtin', agents: ['claude-code'],
- auth: { method: 'managed' },
- routing: { 'claude-code': { upstream: 'https://b', authStrategy: 'gateway-key' } },
- models: { 'claude-code': [model('m1', { name: 'M1', supportsFastMode: false })] },
+ id: "p-slow",
+ name: "P-Slow",
+ source: "builtin",
+ agents: ["claude-code"],
+ auth: { method: "managed" },
+ routing: {
+ "claude-code": {
+ upstream: "https://b",
+ authStrategy: "gateway-key",
+ },
+ },
+ models: {
+ "claude-code": [
+ model("m1", { name: "M1", supportsFastMode: false }),
+ ],
+ },
},
],
};
@@ -570,228 +779,321 @@ describe('fast-mode per-provider resolution (model-level SSoT)', () => {
});
});
-describe('vendor grouping metadata (xai fallback metadata)', () => {
- it('every static model carries group=grok + numeric sortOrder', () => {
- const xai = provider('xai');
+describe("vendor grouping metadata (xai fallback metadata)", () => {
+ it("every static model carries group=grok + numeric sortOrder", () => {
+ const xai = provider("xai");
for (const agent of xai.agents) {
for (const m of xai.models[agent] ?? []) {
- expect(m.group, `${m.id} group`).toBe('grok');
- expect(typeof m.sortOrder, `${m.id} sortOrder`).toBe('number');
+ expect(m.group, `${m.id} group`).toBe("grok");
+ expect(typeof m.sortOrder, `${m.id} sortOrder`).toBe("number");
}
}
});
// 静态目录里的窗口是产品侧逐条写定的真实上限 —— 必须标记为已核实,否则运行期收敛不掉
// 上游报的虚高窗口(例:256K 的 xai/grok-code-fast 被报成基础模型的更大值)。
- it('静态清单的 contextWindow 标记为已核实(可用于收敛上报值)', () => {
- const xai = provider('xai');
+ it("静态清单的 contextWindow 标记为已核实(可用于收敛上报值)", () => {
+ const xai = provider("xai");
for (const agent of xai.agents) {
for (const m of xai.models[agent] ?? []) {
expect(m.contextWindow, `${m.id} contextWindow`).toBeGreaterThan(0);
- expect(m.contextWindowVerified, `${m.id} contextWindowVerified`).toBe(true);
+ expect(m.contextWindowVerified, `${m.id} contextWindowVerified`).toBe(
+ true,
+ );
}
}
});
// 远端下发目录与 bundled 同格式,同样要在解析时标记;条目自己表过态时尊重原值。
- it('parseCatalog 给远端下发的静态条目补标记,但不覆盖显式表态', () => {
+ it("parseCatalog 给远端下发的静态条目补标记,但不覆盖显式表态", () => {
const parsed = parseCatalog({
- version: '2',
+ version: "2",
providers: [
{
- ...provider('xai'),
+ ...provider("xai"),
models: {
codex: [
- { id: 'remote/known', name: 'Known', contextWindow: 262_144, efforts: [], defaultEffort: null, group: 'grok', sortOrder: 1 },
- { id: 'remote/opted-out', name: 'Opted Out', contextWindow: 272_000, contextWindowVerified: false, efforts: [], defaultEffort: null, group: 'grok', sortOrder: 2 },
+ {
+ id: "remote/known",
+ name: "Known",
+ contextWindow: 262_144,
+ efforts: [],
+ defaultEffort: null,
+ group: "grok",
+ sortOrder: 1,
+ },
+ {
+ id: "remote/opted-out",
+ name: "Opted Out",
+ contextWindow: 272_000,
+ contextWindowVerified: false,
+ efforts: [],
+ defaultEffort: null,
+ group: "grok",
+ sortOrder: 2,
+ },
],
},
- agents: ['codex'],
- titleModel: 'remote/known',
+ agents: ["codex"],
+ titleModel: "remote/known",
},
],
});
const models = parsed.providers[0].models.codex ?? [];
- expect(models.find((m) => m.id === 'remote/known')?.contextWindowVerified).toBe(true);
- expect(models.find((m) => m.id === 'remote/opted-out')?.contextWindowVerified).toBe(false);
+ expect(
+ models.find((m) => m.id === "remote/known")?.contextWindowVerified,
+ ).toBe(true);
+ expect(
+ models.find((m) => m.id === "remote/opted-out")?.contextWindowVerified,
+ ).toBe(false);
});
});
-describe('provider OAuth and upstream URL validation', () => {
+describe("provider OAuth and upstream URL validation", () => {
const oauthCatalog = (): Catalog => ({
- version: '1',
- providers: [{
- id: 'oauth-provider',
- name: 'OAuth Provider',
- source: 'builtin',
- agents: ['codex'],
- auth: {
- method: 'oauth',
- oauth: {
- flow: 'authorization-code',
- authorizeUrl: 'https://auth.example/authorize',
- tokenUrl: 'https://auth.example/token',
- clientId: 'client',
- scopes: 'openid',
+ version: "1",
+ providers: [
+ {
+ id: "oauth-provider",
+ name: "OAuth Provider",
+ source: "builtin",
+ agents: ["codex"],
+ auth: {
+ method: "oauth",
+ oauth: {
+ flow: "authorization-code",
+ authorizeUrl: "https://auth.example/authorize",
+ tokenUrl: "https://auth.example/token",
+ clientId: "client",
+ scopes: "openid",
+ },
},
- },
- routing: {
- codex: {
- upstream: 'https://api.example/v1',
- authStrategy: 'oauth-token',
+ routing: {
+ codex: {
+ upstream: "https://api.example/v1",
+ authStrategy: "oauth-token",
+ },
},
+ models: { codex: [model("m1")] },
},
- models: { codex: [model('m1')] },
- }],
+ ],
});
- it('rejects fields from the other OAuth flow', () => {
+ it("rejects fields from the other OAuth flow", () => {
const authorizationCode = oauthCatalog();
Object.assign(authorizationCode.providers[0]!.auth.oauth!, {
- deviceAuthorizationUrl: 'https://auth.example/device',
+ deviceAuthorizationUrl: "https://auth.example/device",
});
expect(() => parseCatalog(authorizationCode)).toThrow(/device-code fields/);
const deviceCode = oauthCatalog();
deviceCode.providers[0]!.auth.oauth = {
- flow: 'device-code',
- deviceAuthorizationUrl: 'https://auth.example/device',
- tokenUrl: 'https://auth.example/token',
- clientId: 'client',
- scopes: 'openid',
- authorizeUrl: 'https://auth.example/authorize',
+ flow: "device-code",
+ deviceAuthorizationUrl: "https://auth.example/device",
+ tokenUrl: "https://auth.example/token",
+ clientId: "client",
+ scopes: "openid",
+ authorizeUrl: "https://auth.example/authorize",
} as never;
expect(() => parseCatalog(deviceCode)).toThrow(/authorization-code fields/);
});
- it('rejects reserved OAuth extra params case-insensitively', () => {
+ it("rejects reserved OAuth extra params case-insensitively", () => {
const catalog = oauthCatalog();
catalog.providers[0]!.auth.oauth!.extraAuthParams = {
- Client_Id: 'shadow-client',
+ Client_Id: "shadow-client",
};
expect(() => parseCatalog(catalog)).toThrow(/cannot override 'Client_Id'/);
});
- it('rejects an OAuth descriptor on a non-OAuth auth method', () => {
+ it("rejects an OAuth descriptor on a non-OAuth auth method", () => {
const catalog = oauthCatalog();
catalog.providers[0]!.auth = {
- method: 'none',
+ method: "none",
oauth: catalog.providers[0]!.auth.oauth,
} as never;
- expect(() => parseCatalog(catalog)).toThrow(/auth\.oauth not allowed for none method/);
+ expect(() => parseCatalog(catalog)).toThrow(
+ /auth\.oauth not allowed for none method/,
+ );
});
- it('rejects an upstream URL with embedded credentials', () => {
+ it("rejects an upstream URL with embedded credentials", () => {
const catalog = oauthCatalog();
- catalog.providers[0]!.routing.codex!.upstream = 'https://user:[email protected]/v1';
+ catalog.providers[0]!.routing.codex!.upstream =
+ "https://user:[email protected]/v1";
expect(() => parseCatalog(catalog)).toThrow(/upstream invalid/);
});
- it('accepts a same-origin Responses model route', () => {
+ it("accepts a same-origin Responses model route", () => {
const catalog = oauthCatalog();
- catalog.providers[0]!.models.codex![0] = model('m1', {
+ catalog.providers[0]!.models.codex![0] = model("m1", {
route: {
- baseUrl: 'https://api.example/v1',
- wireProtocol: 'openai-responses',
- requestPath: '/responses',
+ baseUrl: "https://api.example/v1",
+ wireProtocol: "openai-responses",
+ requestPath: "/responses",
},
});
- expect(parseCatalog(catalog).providers[0]!.models.codex![0]!.route).toEqual({
- baseUrl: 'https://api.example/v1',
- wireProtocol: 'openai-responses',
- requestPath: '/responses',
- });
+ expect(parseCatalog(catalog).providers[0]!.models.codex![0]!.route).toEqual(
+ {
+ baseUrl: "https://api.example/v1",
+ wireProtocol: "openai-responses",
+ requestPath: "/responses",
+ },
+ );
});
it.each([
- ['non-object route', null],
- ['missing base URL', { wireProtocol: 'openai-responses' }],
- ['cross-origin base URL', { baseUrl: 'https://other.example/v1', wireProtocol: 'openai-responses' }],
- ['embedded credentials', { baseUrl: 'https://user:[email protected]/v1', wireProtocol: 'openai-responses' }],
- ['invalid protocol', { baseUrl: 'https://api.example/v1', wireProtocol: 'invalid' }],
- ['unsafe request path', { baseUrl: 'https://api.example/v1', wireProtocol: 'openai-responses', requestPath: '//other.example' }],
- ['Claude-incompatible protocol', { baseUrl: 'https://api.example/v1', wireProtocol: 'openai-responses' }],
- ])('rejects %s model routes', (_label, route) => {
+ ["non-object route", null],
+ ["missing base URL", { wireProtocol: "openai-responses" }],
+ [
+ "cross-origin base URL",
+ { baseUrl: "https://other.example/v1", wireProtocol: "openai-responses" },
+ ],
+ [
+ "embedded credentials",
+ {
+ baseUrl: "https://user:[email protected]/v1",
+ wireProtocol: "openai-responses",
+ },
+ ],
+ [
+ "invalid protocol",
+ { baseUrl: "https://api.example/v1", wireProtocol: "invalid" },
+ ],
+ [
+ "unsafe request path",
+ {
+ baseUrl: "https://api.example/v1",
+ wireProtocol: "openai-responses",
+ requestPath: "//other.example",
+ },
+ ],
+ [
+ "Claude-incompatible protocol",
+ { baseUrl: "https://api.example/v1", wireProtocol: "openai-responses" },
+ ],
+ ])("rejects %s model routes", (_label, route) => {
const catalog = oauthCatalog();
- if (_label === 'Claude-incompatible protocol') {
- catalog.providers[0]!.agents = ['claude-code'];
+ if (_label === "Claude-incompatible protocol") {
+ catalog.providers[0]!.agents = ["claude-code"];
catalog.providers[0]!.routing = {
- 'claude-code': {
- upstream: 'https://api.example/v1',
- authStrategy: 'oauth-token',
+ "claude-code": {
+ upstream: "https://api.example/v1",
+ authStrategy: "oauth-token",
},
};
catalog.providers[0]!.models = {
- 'claude-code': [model('m1', { route: route as never })],
+ "claude-code": [model("m1", { route: route as never })],
};
} else {
- catalog.providers[0]!.models.codex![0] = model('m1', { route: route as never });
+ catalog.providers[0]!.models.codex![0] = model("m1", {
+ route: route as never,
+ });
}
expect(() => parseCatalog(catalog)).toThrow(/model\.route invalid/);
});
});
-describe('buildRegistry 的清单发现失败投影', () => {
+describe("buildRegistry 的清单发现失败投影", () => {
const failure = {
- kind: 'regionBlocked' as const,
- at: '2026-07-27T00:00:00.000Z',
- detail: 'HTTP 403: {"error":{"type":"unsupported_country_region_territory"}}',
+ kind: "regionBlocked" as const,
+ at: "2026-07-27T00:00:00.000Z",
+ detail:
+ 'HTTP 403: {"error":{"type":"unsupported_country_region_territory"}}',
};
- it('剥掉 detail 再下发 —— 原始上游响应体不出 Main', () => {
- const views = buildRegistry(BUNDLED_CATALOG, { anthropic: true }, { anthropic: failure });
- const anthropic = views.find((p) => p.id === 'anthropic');
- expect(anthropic?.modelDiscoveryFailure).toEqual({ kind: 'regionBlocked', at: failure.at });
- expect(anthropic?.modelDiscoveryFailure).not.toHaveProperty('detail');
+ it("剥掉 detail 再下发 —— 原始上游响应体不出 Main", () => {
+ const views = buildRegistry(
+ BUNDLED_CATALOG,
+ { anthropic: true },
+ { anthropic: failure },
+ );
+ const anthropic = views.find((p) => p.id === "anthropic");
+ expect(anthropic?.modelDiscoveryFailure).toEqual({
+ kind: "regionBlocked",
+ at: failure.at,
+ });
+ expect(anthropic?.modelDiscoveryFailure).not.toHaveProperty("detail");
// 原对象不被就地改坏:host 侧还要拿 detail 写日志。
- expect(failure.detail).toContain('unsupported_country_region_territory');
+ expect(failure.detail).toContain("unsupported_country_region_territory");
});
- it('没有失败态的供应商不长出该字段;稀疏 map 缺键也不报错', () => {
- const views = buildRegistry(BUNDLED_CATALOG, { anthropic: true }, { anthropic: null });
- expect(views.find((p) => p.id === 'anthropic')?.modelDiscoveryFailure).toBeUndefined();
+ it("没有失败态的供应商不长出该字段;稀疏 map 缺键也不报错", () => {
+ const views = buildRegistry(
+ BUNDLED_CATALOG,
+ { anthropic: true },
+ { anthropic: null },
+ );
+ expect(
+ views.find((p) => p.id === "anthropic")?.modelDiscoveryFailure,
+ ).toBeUndefined();
const bare = buildRegistry(BUNDLED_CATALOG, { anthropic: true });
- expect(bare.find((p) => p.id === 'anthropic')?.modelDiscoveryFailure).toBeUndefined();
+ expect(
+ bare.find((p) => p.id === "anthropic")?.modelDiscoveryFailure,
+ ).toBeUndefined();
});
});
-describe('媒体清单跨供应商契约(2026-07 图像多来源)', () => {
+describe("媒体清单跨供应商契约(2026-07 图像多来源)", () => {
// deriveCindyMediaConfig(desktop 侧)按目录序 first-wins 选默认与归属:
// BUILTIN 顺序里 openai/xai 排在 xd 前面,任何非 xd 供应商声明 imageDefaults
// 都会把 xd 的出厂默认顶掉;同 id 撞车会把 xd 条目的归属抢走(派发错通道)。
// 这两条是数据契约,在目录层锁死,不等运行时踩雷。
- it('声明 imageDefaults / videoDefaults 的内置供应商只能是 xd(防 first-wins 顶默认)', () => {
+ it("声明 imageDefaults / videoDefaults 的内置供应商只能是 xd(防 first-wins 顶默认)", () => {
for (const p of BUNDLED_CATALOG.providers) {
- if (p.id === 'xd') continue;
+ if (p.id === "xd") continue;
expect(p.imageDefaults, `${p.id} 不得声明 imageDefaults`).toBeUndefined();
expect(p.videoDefaults, `${p.id} 不得声明 videoDefaults`).toBeUndefined();
}
});
- it('embeddingModels / embeddingDefaults 与 image/video 同一套入口校验', () => {
+ it("embeddingModels / embeddingDefaults 与 image/video 同一套入口校验", () => {
// 不校验的话坏数据能通过 parseCatalog,随后在 deriveCindyMediaConfig 的
// for...of 里抛错、被上层降级成空清单 —— 表现是所有插件向量请求变
// NO_CANDIDATE,而真正的原因在目录里,排查时毫无线索(PR #1707 review)。
const withXd = (mutate: (xd: Record<string, unknown>) => void): Catalog => {
const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- mutate(bad.providers.find((p) => p.id === 'xd')! as unknown as Record<string, unknown>);
+ mutate(
+ bad.providers.find((p) => p.id === "xd")! as unknown as Record<
+ string,
+ unknown
+ >,
+ );
return bad;
};
// 写成对象而不是数组(远端手写目录最常见的形态错误)。
- expect(() => parseCatalog(withXd((xd) => { xd.embeddingModels = { a: 1 }; })))
- .toThrow(/embeddingModels/);
+ expect(() =>
+ parseCatalog(
+ withXd((xd) => {
+ xd.embeddingModels = { a: 1 };
+ }),
+ ),
+ ).toThrow(/embeddingModels/);
// 条目缺 id / name。
- expect(() => parseCatalog(withXd((xd) => { xd.embeddingModels = [{ name: 'x' }]; })))
- .toThrow(/embeddingModels/);
- expect(() => parseCatalog(withXd((xd) => { xd.embeddingModels = [{ id: 'a', name: '' }]; })))
- .toThrow(/embeddingModels/);
+ expect(() =>
+ parseCatalog(
+ withXd((xd) => {
+ xd.embeddingModels = [{ name: "x" }];
+ }),
+ ),
+ ).toThrow(/embeddingModels/);
+ expect(() =>
+ parseCatalog(
+ withXd((xd) => {
+ xd.embeddingModels = [{ id: "a", name: "" }];
+ }),
+ ),
+ ).toThrow(/embeddingModels/);
// id 重复(first-wins 去重会静默吃掉后一条)。
expect(() =>
parseCatalog(
withXd((xd) => {
- xd.embeddingModels = [{ id: 'a', name: 'A' }, { id: 'a', name: 'A2' }];
- xd.embeddingDefaults = { standard: 'a' };
+ xd.embeddingModels = [
+ { id: "a", name: "A" },
+ { id: "a", name: "A2" },
+ ];
+ xd.embeddingDefaults = { standard: "a" };
}),
),
).toThrow(/duplicate/);
@@ -799,16 +1101,16 @@ describe('媒体清单跨供应商契约(2026-07 图像多来源)', () => {
expect(() =>
parseCatalog(
withXd((xd) => {
- xd.embeddingModels = [{ id: 'a', name: 'A' }];
- xd.embeddingDefaults = { standard: 'not-in-list' };
+ xd.embeddingModels = [{ id: "a", name: "A" }];
+ xd.embeddingDefaults = { standard: "not-in-list" };
}),
),
).toThrow(/embeddingDefaults/);
});
- it('只声明向量清单的供应商可以没有 agents(媒体-only 同理)', () => {
+ it("只声明向量清单的供应商可以没有 agents(媒体-only 同理)", () => {
const cat = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- const xd = cat.providers.find((p) => p.id === 'xd')!;
+ const xd = cat.providers.find((p) => p.id === "xd")!;
xd.agents = [];
xd.models = {};
xd.routing = {};
@@ -821,7 +1123,7 @@ describe('媒体清单跨供应商契约(2026-07 图像多来源)', () => {
it('非 xd 内置供应商的媒体模型 id 必须带 "<providerId>/" 前缀(防 first-wins 归属漂移)', () => {
for (const p of BUNDLED_CATALOG.providers) {
- if (p.id === 'xd') continue;
+ if (p.id === "xd") continue;
for (const m of [...(p.imageModels ?? []), ...(p.videoModels ?? [])]) {
expect(
m.id.startsWith(`${p.id}/`),
diff --git a/packages/model-providers/src/__tests__/localModelCatalog.test.ts b/packages/model-providers/src/__tests__/localModelCatalog.test.ts
new file mode 100644
index 0000000000..1633b36846
--- /dev/null
+++ b/packages/model-providers/src/__tests__/localModelCatalog.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest";
+import { parseLocalModelCatalog } from "../localModelCatalog.js";
+import { parseModelRegistry } from "../modelAccessValidator.js";
+const catalog = {
+ version: 1,
+ featuredIds: ["example"],
+ models: [
+ {
+ id: "example",
+ name: "Example",
+ aliases: ["example"],
+ variants: [
+ {
+ libraryName: "example:4b-mlx",
+ sizeBytes: 4 * 1024 ** 3,
+ minUnifiedMemoryGb: 8,
+ appleSiliconOnly: true,
+ },
+ ],
+ descriptions: { "zh-CN": "本地候选", en: "Local candidate" },
+ runtimeProfile: "plain",
+ evidence: [
+ {
+ url: "https://example.com/bench",
+ verifiedAt: "2026-09-05",
+ status: "pending",
+ },
+ ],
+ },
+ ],
+};
+describe("Registry V4 local model contract", () => {
+ it.each([200, 201, 256, 257])(
+ "matches public ID and local reference limits at %i characters",
+ (length) => {
+ const modelRef = "m".repeat(length);
+ const localModels = {
+ ...catalog,
+ models: [{ ...catalog.models[0], modelRef }],
+ };
+ const registry = {
+ schemaVersion: 4,
+ updatedAt: "2026-09-08T00:00:00.000Z",
+ baseModels: [{ id: modelRef, aliases: [], defaults: {} }],
+ models: [],
+ localModels,
+ };
+ expect(parseLocalModelCatalog(localModels) !== null).toBe(length <= 256);
+ expect(parseModelRegistry(registry).ok).toBe(length <= 256);
+ expect(parseModelRegistry({ ...registry, baseModels: [] }).ok).toBe(
+ false,
+ );
+ },
+ );
+ it("accepts curated metadata only in V4 and permits explicit empty withdrawal", () => {
+ expect(parseLocalModelCatalog(catalog)).toEqual(catalog);
+ for (const localModels of [
+ catalog,
+ { version: 1, models: [], featuredIds: [] },
+ ]) {
+ expect(
+ parseModelRegistry({
+ schemaVersion: 4,
+ updatedAt: "2026-09-08T00:00:00.000Z",
+ models: [],
+ localModels,
+ }).ok,
+ ).toBe(true);
+ for (const schemaVersion of [1, 2, 3]) {
+ expect(
+ parseModelRegistry({
+ schemaVersion,
+ updatedAt: "2026-09-08T00:00:00.000Z",
+ models: [],
+ localModels,
+ }).ok,
+ ).toBe(false);
+ }
+ }
+ });
+ it.each([
+ (c: any) => {
+ c.models[0].variants[0].libraryName = "https://example.com/model";
+ },
+ (c: any) => {
+ c.models[0].variants[0].libraryName = "../model:latest";
+ },
+ (c: any) => {
+ c.models[0].variants[0].sizeBytes = -1;
+ },
+ (c: any) => {
+ c.models[0].variants[0].minUnifiedMemoryGb = 0;
+ },
+ (c: any) => {
+ delete c.models[0].variants[0].appleSiliconOnly;
+ },
+ (c: any) => {
+ c.models[0].runtimeProfile = "shell";
+ },
+ (c: any) => {
+ c.models[0].runtimeProfile = "qwen-xhigh";
+ },
+ (c: any) => {
+ c.models[0].evidence[0].verifiedAt = "2026-02-30";
+ },
+ (c: any) => {
+ c.models[0].command = "run";
+ },
+ (c: any) => {
+ c.models[0].descriptions.en = "";
+ },
+ (c: any) => {
+ c.featuredIds = ["missing"];
+ },
+ (c: any) => {
+ c.models.push(c.models[0]);
+ },
+ (c: any) => {
+ c.models[0].evidence[0].url = "file:///etc/passwd";
+ },
+ ])(
+ "rejects invalid data before it can replace a cached snapshot",
+ (mutate) => {
+ const bad = structuredClone(catalog);
+ mutate(bad);
+ expect(parseLocalModelCatalog(bad)).toBeNull();
+ expect(
+ parseModelRegistry({
+ schemaVersion: 4,
+ updatedAt: "2026-09-08T00:00:00.000Z",
+ models: [],
+ localModels: bad,
+ }).ok,
+ ).toBe(false);
+ },
+ );
+});
diff --git a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
index 877a237079..8c058ff943 100644
--- a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
+++ b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it } from "vitest";
import {
MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
@@ -15,27 +15,27 @@ import {
parseModelRegistry,
type ListModelsResponse,
type ModelRegistry,
-} from '../index.js';
+} from "../index.js";
const VALID_RESPONSE: ListModelsResponse = {
schemaVersion: MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION,
models: [
{
- id: 'example-chat-model',
- mode: 'chat',
- currency: 'CNY',
- agents: ['claude-code', 'codex'],
- newSessionDefault: ['claude-code', 'codex'],
- name: 'Example Chat Model',
- icon: 'example',
+ id: "example-chat-model",
+ mode: "chat",
+ currency: "CNY",
+ agents: ["claude-code", "codex"],
+ newSessionDefault: ["claude-code", "codex"],
+ name: "Example Chat Model",
+ icon: "example",
contextWindow: 200_000,
- modalities: { input: ['text', 'image'], output: ['text'] },
+ modalities: { input: ["text", "image"], output: ["text"] },
inputCostPerToken: 0.000_001,
outputCostPerToken: 0.000_002,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
+ efforts: ["low", "medium", "high"],
+ defaultEffort: "medium",
perAgent: {
- 'claude-code': { supportsFastMode: false },
+ "claude-code": { supportsFastMode: false },
},
tieredPricing: [
{
@@ -55,11 +55,11 @@ const VALID_V3_RESPONSE: ListModelsResponse = {
{
...VALID_RESPONSE.models[0]!,
perAgent: {
- 'claude-code': {
+ "claude-code": {
supportsFastMode: false,
- wireProtocol: 'anthropic-messages',
+ wireProtocol: "anthropic-messages",
},
- codex: { wireProtocol: 'openai-responses' },
+ codex: { wireProtocol: "openai-responses" },
},
},
],
@@ -72,43 +72,43 @@ const VALID_V4_RESPONSE: ListModelsResponse = {
const VALID_V5_RESPONSE: ListModelsResponse = {
schemaVersion: MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
- accountTier: 'free',
+ accountTier: "free",
models: VALID_V4_RESPONSE.models.map((model) => ({
...model,
- availability: 'requires_payment',
+ availability: "requires_payment",
})),
};
const VALID_REGISTRY: ModelRegistry = {
schemaVersion: MODEL_REGISTRY_SCHEMA_VERSION,
- updatedAt: '2026-07-31T00:00:00.000Z',
+ updatedAt: "2026-07-31T00:00:00.000Z",
models: [
{
- id: 'example/model',
- name: 'Example Model',
- status: 'active',
+ id: "example/model",
+ name: "Example Model",
+ status: "active",
contextWindow: 200_000,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
+ efforts: ["low", "medium", "high"],
+ defaultEffort: "medium",
routes: [
{
- providerId: 'example',
- modelId: 'example-model',
- agents: ['claude-code', 'codex'],
+ providerId: "example",
+ modelId: "example-model",
+ agents: ["claude-code", "codex"],
referencePrices: [
{
- currency: 'USD',
- variant: 'standard',
+ currency: "USD",
+ variant: "standard",
inputPerMtok: 1,
outputPerMtok: 5,
cacheReadPerMtok: 0.1,
minInputTokens: 0,
maxInputTokens: 200_000,
- effectiveFrom: '2026-07-01',
+ effectiveFrom: "2026-07-01",
source: {
- kind: 'provider-official',
- url: 'https://example.com/pricing',
- verifiedAt: '2026-07-31',
+ kind: "provider-official",
+ url: "https://example.com/pricing",
+ verifiedAt: "2026-07-31",
},
},
],
@@ -121,52 +121,61 @@ const VALID_REGISTRY: ModelRegistry = {
function expectReject(value: unknown, path: string): void {
const result = parseListModelsResponse(value);
expect(result.ok).toBe(false);
- if (result.ok) throw new Error('unreachable');
+ if (result.ok) throw new Error("unreachable");
expect(result.error).toContain(path);
}
-describe('model access catalog contract', () => {
- it('round-trips the versioned model catalog with its declared currency', () => {
+describe("model access catalog contract", () => {
+ it("round-trips the versioned model catalog with its declared currency", () => {
const wire = JSON.parse(JSON.stringify(VALID_RESPONSE));
const result = parseListModelsResponse(wire);
expect(result).toEqual({ ok: true, value: VALID_RESPONSE });
- expect(MODEL_ACCESS_MODELS_PATH).toBe('/api/model-access/models');
+ expect(MODEL_ACCESS_MODELS_PATH).toBe("/api/model-access/models");
});
- it('parses strict v5 availability and account tier fields', () => {
+ it("parses strict v5 availability and account tier fields", () => {
expect(parseListModelsResponse(VALID_V5_RESPONSE)).toEqual({
ok: true,
value: VALID_V5_RESPONSE,
});
- expectReject({ ...VALID_V5_RESPONSE, accountTier: 'vip' }, 'response.accountTier');
+ expectReject(
+ { ...VALID_V5_RESPONSE, accountTier: "vip" },
+ "response.accountTier",
+ );
expectReject(
{
...VALID_V5_RESPONSE,
- models: [{ ...VALID_V5_RESPONSE.models[0]!, availability: 'unavailable' }],
+ models: [
+ { ...VALID_V5_RESPONSE.models[0]!, availability: "unavailable" },
+ ],
},
- 'response.models[0].availability',
+ "response.models[0].availability",
);
});
- it('continues to parse v1 responses, while v1 rejects the v2-only default field', () => {
- const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
+ it("continues to parse v1 responses, while v1 rejects the v2-only default field", () => {
+ const { newSessionDefault: _newSessionDefault, ...legacyModel } =
+ VALID_RESPONSE.models[0]!;
const legacy = {
...VALID_RESPONSE,
schemaVersion: MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
models: [legacyModel],
};
- expect(parseListModelsResponse(JSON.parse(JSON.stringify(legacy))).ok).toBe(true);
+ expect(parseListModelsResponse(JSON.parse(JSON.stringify(legacy))).ok).toBe(
+ true,
+ );
expectReject(
{
...legacy,
- models: [{ ...legacyModel, newSessionDefault: ['claude-code'] }],
+ models: [{ ...legacyModel, newSessionDefault: ["claude-code"] }],
},
- 'response.models[0].newSessionDefault',
+ "response.models[0].newSessionDefault",
);
});
- it('enforces the complete per-version ListModels allowlist', () => {
- const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
+ it("enforces the complete per-version ListModels allowlist", () => {
+ const { newSessionDefault: _newSessionDefault, ...legacyModel } =
+ VALID_RESPONSE.models[0]!;
const versions = [
[MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION, legacyModel],
[MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION, VALID_RESPONSE.models[0]!],
@@ -178,14 +187,20 @@ describe('model access catalog contract', () => {
const response = { schemaVersion, models: [model] };
const tier = model.tieredPricing![0]!;
const cases: [unknown, string][] = [
- [{ ...response, producerRevision: 'stale-v2' }, 'response.producerRevision'],
- [{ ...response, models: [{ ...model, family: 'example' }] }, 'response.models[0].family'],
+ [
+ { ...response, producerRevision: "stale-v2" },
+ "response.producerRevision",
+ ],
+ [
+ { ...response, models: [{ ...model, family: "example" }] },
+ "response.models[0].family",
+ ],
[
{
...response,
- models: [{ ...model, provenance: { source: 'stale-v2' } }],
+ models: [{ ...model, provenance: { source: "stale-v2" } }],
},
- 'response.models[0].provenance',
+ "response.models[0].provenance",
],
[
{
@@ -194,12 +209,12 @@ describe('model access catalog contract', () => {
{
...model,
perAgent: {
- 'claude-code': { supportsFastMode: false, verified: true },
+ "claude-code": { supportsFastMode: false, verified: true },
},
},
],
},
- 'response.models[0].perAgent.claude-code.verified',
+ "response.models[0].perAgent.claude-code.verified",
],
[
{
@@ -207,11 +222,11 @@ describe('model access catalog contract', () => {
models: [
{
...model,
- tieredPricing: [{ ...tier, provenance: 'stale-v2' }],
+ tieredPricing: [{ ...tier, provenance: "stale-v2" }],
},
],
},
- 'response.models[0].tieredPricing[0].provenance',
+ "response.models[0].tieredPricing[0].provenance",
],
[
{
@@ -219,11 +234,11 @@ describe('model access catalog contract', () => {
models: [
{
...model,
- modalities: { ...model.modalities!, source: 'stale-v2' },
+ modalities: { ...model.modalities!, source: "stale-v2" },
},
],
},
- 'response.models[0].modalities.source',
+ "response.models[0].modalities.source",
],
];
@@ -231,14 +246,17 @@ describe('model access catalog contract', () => {
}
});
- it('rejects malformed v2 newSessionDefault values', () => {
+ it("rejects malformed v2 newSessionDefault values", () => {
const withDefault = (value: unknown) => ({
...VALID_RESPONSE,
models: [{ ...VALID_RESPONSE.models[0], newSessionDefault: value }],
});
- expectReject(withDefault([]), 'response.models[0].newSessionDefault');
- expectReject(withDefault(['codex', 'codex']), 'response.models[0].newSessionDefault');
- expect(parseListModelsResponse(withDefault(['pi']))).toMatchObject({
+ expectReject(withDefault([]), "response.models[0].newSessionDefault");
+ expectReject(
+ withDefault(["codex", "codex"]),
+ "response.models[0].newSessionDefault",
+ );
+ expect(parseListModelsResponse(withDefault(["pi"]))).toMatchObject({
ok: true,
});
expectReject(
@@ -247,66 +265,85 @@ describe('model access catalog contract', () => {
models: [
{
...VALID_RESPONSE.models[0],
- agents: ['claude-code'],
- newSessionDefault: ['codex'],
+ agents: ["claude-code"],
+ newSessionDefault: ["codex"],
},
],
},
- 'response.models[0].newSessionDefault',
+ "response.models[0].newSessionDefault",
);
});
- it('validates existing mode and normalized modalities in both schema versions', () => {
- const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
+ it("validates existing mode and normalized modalities in both schema versions", () => {
+ const { newSessionDefault: _newSessionDefault, ...legacyModel } =
+ VALID_RESPONSE.models[0]!;
for (const [schemaVersion, model] of [
[MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION, legacyModel],
[MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION, VALID_RESPONSE.models[0]!],
[MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION, VALID_V3_RESPONSE.models[0]!],
[MODEL_ACCESS_CATALOG_SCHEMA_VERSION, VALID_V4_RESPONSE.models[0]!],
] as const) {
- expect(parseListModelsResponse({ schemaVersion, models: [model] }).ok).toBe(true);
- expectReject({ schemaVersion, models: [{ ...model, mode: 42 }] }, 'response.models[0].mode');
+ expect(
+ parseListModelsResponse({ schemaVersion, models: [model] }).ok,
+ ).toBe(true);
+ expectReject(
+ { schemaVersion, models: [{ ...model, mode: 42 }] },
+ "response.models[0].mode",
+ );
expectReject(
- { schemaVersion, models: [{ ...model, icon: ' ' }] },
- 'response.models[0].icon',
+ { schemaVersion, models: [{ ...model, icon: " " }] },
+ "response.models[0].icon",
+ );
+ expectReject(
+ { schemaVersion, models: [{ ...model, icon: 42 }] },
+ "response.models[0].icon",
);
- expectReject({ schemaVersion, models: [{ ...model, icon: 42 }] }, 'response.models[0].icon');
expectReject(
{
schemaVersion,
- models: [{ ...model, modalities: { input: ['text', 42], output: ['text'] } }],
+ models: [
+ { ...model, modalities: { input: ["text", 42], output: ["text"] } },
+ ],
},
- 'response.models[0].modalities.input',
+ "response.models[0].modalities.input",
);
}
});
- it.each([undefined, 'responses'] as const)(
- '仍要求 mode=%s 的可聊天模型提供 contextWindow',
+ it.each([undefined, "responses"] as const)(
+ "仍要求 mode=%s 的可聊天模型提供 contextWindow",
(mode) => {
- const { contextWindow: _contextWindow, mode: _mode, ...withoutContextWindow } =
- VALID_V3_RESPONSE.models[0]!;
+ const {
+ contextWindow: _contextWindow,
+ mode: _mode,
+ ...withoutContextWindow
+ } = VALID_V3_RESPONSE.models[0]!;
expectReject(
{
schemaVersion: MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
- models: [{ ...withoutContextWindow, ...(mode === undefined ? {} : { mode }) }],
+ models: [
+ {
+ ...withoutContextWindow,
+ ...(mode === undefined ? {} : { mode }),
+ },
+ ],
},
- 'response.models[0].contextWindow',
+ "response.models[0].contextWindow",
);
},
);
- it('v4 允许媒体模型省略 contextWindow,v3 保持已发布约束', () => {
- for (const mode of ['image_generation', 'video_generation'] as const) {
+ it("v4 允许媒体模型省略 contextWindow,v3 保持已发布约束", () => {
+ for (const mode of ["image_generation", "video_generation"] as const) {
const mediaModel = {
id: `${mode}-model`,
name: `${mode} model`,
mode,
- currency: 'CNY',
+ currency: "CNY",
agents: [],
modalities: {
- input: mode === 'image_generation' ? ['text'] : ['text', 'image'],
- output: [mode === 'image_generation' ? 'image' : 'video'],
+ input: mode === "image_generation" ? ["text"] : ["text", "image"],
+ output: [mode === "image_generation" ? "image" : "video"],
},
} as const;
expect(
@@ -320,24 +357,24 @@ describe('model access catalog contract', () => {
schemaVersion: MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION,
models: [mediaModel],
},
- 'response.models[0].agents',
+ "response.models[0].agents",
);
expectReject(
{
schemaVersion: MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
- models: [{ ...mediaModel, agents: ['codex'] }],
+ models: [{ ...mediaModel, agents: ["codex"] }],
},
- 'response.models[0].agents must be empty',
+ "response.models[0].agents must be empty",
);
}
});
- it('v4/v5 允许 provider-level embedding 模型使用空 agents 且省略 contextWindow', () => {
+ it("v4/v5 允许 provider-level embedding 模型使用空 agents 且省略 contextWindow", () => {
const embeddingModel = {
- id: 'voyage/voyage-4',
- name: 'Voyage 4',
- mode: 'embedding',
- currency: 'CNY',
+ id: "voyage/voyage-4",
+ name: "Voyage 4",
+ mode: "embedding",
+ currency: "CNY",
agents: [],
} as const;
@@ -350,8 +387,8 @@ describe('model access catalog contract', () => {
expect(
parseListModelsResponse({
schemaVersion: MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
- accountTier: 'paid',
- models: [{ ...embeddingModel, availability: 'available' }],
+ accountTier: "paid",
+ models: [{ ...embeddingModel, availability: "available" }],
}).ok,
).toBe(true);
expect(
@@ -363,36 +400,42 @@ describe('model access catalog contract', () => {
expectReject(
{
schemaVersion: MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
- models: [{ ...embeddingModel, agents: ['codex'] }],
+ models: [{ ...embeddingModel, agents: ["codex"] }],
},
- 'response.models[0].agents must be empty',
+ "response.models[0].agents must be empty",
);
});
- it.each(['CNY', 'USD'] as const)('accepts the supported %s currency', (currency) => {
- const result = parseListModelsResponse({
- ...VALID_RESPONSE,
- models: [{ ...VALID_RESPONSE.models[0], currency }],
- });
- expect(result.ok).toBe(true);
- });
+ it.each(["CNY", "USD"] as const)(
+ "accepts the supported %s currency",
+ (currency) => {
+ const result = parseListModelsResponse({
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0], currency }],
+ });
+ expect(result.ok).toBe(true);
+ },
+ );
- it('accepts missing currency for legacy fallback and rejects unsupported explicit values', () => {
- const { currency: _currency, ...withoutCurrency } = VALID_RESPONSE.models[0]!;
- expect(parseListModelsResponse({ ...VALID_RESPONSE, models: [withoutCurrency] })).toEqual({
+ it("accepts missing currency for legacy fallback and rejects unsupported explicit values", () => {
+ const { currency: _currency, ...withoutCurrency } =
+ VALID_RESPONSE.models[0]!;
+ expect(
+ parseListModelsResponse({ ...VALID_RESPONSE, models: [withoutCurrency] }),
+ ).toEqual({
ok: true,
value: { ...VALID_RESPONSE, models: [withoutCurrency] },
});
expectReject(
{
...VALID_RESPONSE,
- models: [{ ...VALID_RESPONSE.models[0], currency: 'EUR' }],
+ models: [{ ...VALID_RESPONSE.models[0], currency: "EUR" }],
},
- 'response.models[0].currency',
+ "response.models[0].currency",
);
});
- it('accepts missing or empty agents, filters future kinds, and rejects malformed values', () => {
+ it("accepts missing or empty agents, filters future kinds, and rejects malformed values", () => {
const {
agents: _agents,
newSessionDefault: _newSessionDefault,
@@ -401,21 +444,23 @@ describe('model access catalog contract', () => {
} = VALID_RESPONSE.models[0]!;
for (const model of [withoutAgents, { ...withoutAgents, agents: [] }]) {
- expect(parseListModelsResponse({ ...VALID_RESPONSE, models: [model] }).ok).toBe(true);
+ expect(
+ parseListModelsResponse({ ...VALID_RESPONSE, models: [model] }).ok,
+ ).toBe(true);
}
expect(
parseListModelsResponse({
...VALID_RESPONSE,
- models: [{ ...withoutAgents, agents: ['future-agent'] }],
+ models: [{ ...withoutAgents, agents: ["future-agent"] }],
}),
).toMatchObject({ ok: true, value: { models: [{ agents: [] }] } });
expectReject(
{ ...VALID_RESPONSE, models: [{ ...withoutAgents, agents: [42] }] },
- 'response.models[0].agents',
+ "response.models[0].agents",
);
});
- it('accepts null defaults from Model Access at the model and agent-override levels', () => {
+ it("accepts null defaults from Model Access at the model and agent-override levels", () => {
expect(
parseListModelsResponse({
...VALID_RESPONSE,
@@ -430,8 +475,11 @@ describe('model access catalog contract', () => {
).toBe(true);
});
- it('rejects unsupported schema versions and malformed nested pricing', () => {
- expectReject({ ...VALID_RESPONSE, schemaVersion: 6 }, 'response.schemaVersion');
+ it("rejects unsupported schema versions and malformed nested pricing", () => {
+ expectReject(
+ { ...VALID_RESPONSE, schemaVersion: 6 },
+ "response.schemaVersion",
+ );
expectReject(
{
...VALID_RESPONSE,
@@ -442,91 +490,101 @@ describe('model access catalog contract', () => {
},
],
},
- 'response.models[0].tieredPricing[0].range',
+ "response.models[0].tieredPricing[0].range",
);
});
- it('treats Pi wireProtocol as a forward-compatible last-priority hint while keeping Claude and Codex fixed', () => {
+ it("treats Pi wireProtocol as a forward-compatible last-priority hint while keeping Claude and Codex fixed", () => {
const piModel = {
...VALID_V3_RESPONSE.models[0],
- agents: ['claude-code', 'codex', 'pi'],
+ agents: ["claude-code", "codex", "pi"],
perAgent: {
...VALID_V3_RESPONSE.models[0]!.perAgent,
- pi: { wireProtocol: 'openai-responses' },
+ pi: { wireProtocol: "openai-responses" },
},
} as const;
for (const wireProtocol of [
- 'anthropic-messages',
- 'openai-responses',
- 'openai-completions',
- 'google-generative-ai',
+ "anthropic-messages",
+ "openai-responses",
+ "openai-completions",
+ "google-generative-ai",
] as const) {
expect(
parseListModelsResponse({
...VALID_V3_RESPONSE,
- models: [{
- ...piModel,
- perAgent: { ...piModel.perAgent, pi: { wireProtocol } },
- }],
+ models: [
+ {
+ ...piModel,
+ perAgent: { ...piModel.perAgent, pi: { wireProtocol } },
+ },
+ ],
}).ok,
).toBe(true);
}
expect(
parseListModelsResponse({
...VALID_V3_RESPONSE,
- models: [{
- ...piModel,
- perAgent: {
- 'claude-code': { wireProtocol: 'anthropic-messages' },
- codex: { wireProtocol: 'openai-responses' },
+ models: [
+ {
+ ...piModel,
+ perAgent: {
+ "claude-code": { wireProtocol: "anthropic-messages" },
+ codex: { wireProtocol: "openai-responses" },
+ },
},
- }],
+ ],
}).ok,
).toBe(true);
expectReject(
{ ...VALID_V3_RESPONSE, models: [{ ...piModel, perAgent: {} }] },
- 'response.models[0].perAgent.claude-code.wireProtocol',
+ "response.models[0].perAgent.claude-code.wireProtocol",
);
expectReject(
{
...VALID_V3_RESPONSE,
- models: [{
- ...piModel,
- perAgent: {
- ...piModel.perAgent,
- codex: { wireProtocol: 'anthropic-messages' },
+ models: [
+ {
+ ...piModel,
+ perAgent: {
+ ...piModel.perAgent,
+ codex: { wireProtocol: "anthropic-messages" },
+ },
},
- }],
+ ],
},
- 'response.models[0].perAgent.codex.wireProtocol must be openai-responses',
+ "response.models[0].perAgent.codex.wireProtocol must be openai-responses",
);
expect(
parseListModelsResponse({
...VALID_V3_RESPONSE,
- models: [{
- ...piModel,
- perAgent: {
- ...piModel.perAgent,
- pi: { wireProtocol: 'future-protocol' },
+ models: [
+ {
+ ...piModel,
+ perAgent: {
+ ...piModel.perAgent,
+ pi: { wireProtocol: "future-protocol" },
+ },
},
- }],
+ ],
}).ok,
).toBe(true);
- for (const wireProtocol of ['', 42, { api: 'openai-responses' }]) {
+ for (const wireProtocol of ["", 42, { api: "openai-responses" }]) {
expectReject(
{
...VALID_V3_RESPONSE,
- models: [{
- ...piModel,
- perAgent: { ...piModel.perAgent, pi: { wireProtocol } },
- }],
+ models: [
+ {
+ ...piModel,
+ perAgent: { ...piModel.perAgent, pi: { wireProtocol } },
+ },
+ ],
},
- 'response.models[0].perAgent.pi.wireProtocol must be a non-empty string',
+ "response.models[0].perAgent.pi.wireProtocol must be a non-empty string",
);
}
});
- it('requires complete runtime metadata in v3 without changing v2', () => {
+ it("requires complete runtime metadata in v3 without changing v2", () => {
const {
name: _name,
contextWindow: _contextWindow,
@@ -537,36 +595,38 @@ describe('model access catalog contract', () => {
...VALID_V3_RESPONSE,
models: [{ ...incomplete, contextWindow: 200_000 }],
},
- 'response.models[0].name',
+ "response.models[0].name",
);
expectReject(
{
...VALID_V3_RESPONSE,
- models: [{ ...incomplete, name: 'Example Chat Model' }],
+ models: [{ ...incomplete, name: "Example Chat Model" }],
},
- 'response.models[0].contextWindow',
+ "response.models[0].contextWindow",
);
expect(
parseListModelsResponse({
...VALID_RESPONSE,
- models: [{ ...incomplete, perAgent: VALID_RESPONSE.models[0]!.perAgent }],
+ models: [
+ { ...incomplete, perAgent: VALID_RESPONSE.models[0]!.perAgent },
+ ],
}).ok,
).toBe(true);
});
- it('rejects defaults that are absent from the declared effort list', () => {
+ it("rejects defaults that are absent from the declared effort list", () => {
expectReject(
{
...VALID_RESPONSE,
models: [
{
...VALID_RESPONSE.models[0],
- efforts: ['low'],
- defaultEffort: 'high',
+ efforts: ["low"],
+ defaultEffort: "high",
},
],
},
- 'response.models[0].defaultEffort',
+ "response.models[0].defaultEffort",
);
expectReject(
{
@@ -574,11 +634,11 @@ describe('model access catalog contract', () => {
models: [
{
...VALID_RESPONSE.models[0],
- perAgent: { codex: { efforts: ['low'], defaultEffort: 'high' } },
+ perAgent: { codex: { efforts: ["low"], defaultEffort: "high" } },
},
],
},
- 'response.models[0].perAgent.codex.defaultEffort',
+ "response.models[0].perAgent.codex.defaultEffort",
);
expectReject(
{
@@ -586,23 +646,26 @@ describe('model access catalog contract', () => {
models: [
{
...VALID_RESPONSE.models[0],
- efforts: ['low', 'high'],
- defaultEffort: 'high',
- perAgent: { codex: { efforts: ['low'] } },
+ efforts: ["low", "high"],
+ defaultEffort: "high",
+ perAgent: { codex: { efforts: ["low"] } },
},
],
},
- 'response.models[0].perAgent.codex.efforts',
+ "response.models[0].perAgent.codex.efforts",
);
});
- it('rejects duplicate ids and overrides for unsupported agents', () => {
+ it("rejects duplicate ids and overrides for unsupported agents", () => {
expectReject(
{
...VALID_RESPONSE,
- models: [{ ...VALID_RESPONSE.models[0] }, { ...VALID_RESPONSE.models[0] }],
+ models: [
+ { ...VALID_RESPONSE.models[0] },
+ { ...VALID_RESPONSE.models[0] },
+ ],
},
- 'response.models[1].id',
+ "response.models[1].id",
);
expectReject(
{
@@ -610,13 +673,13 @@ describe('model access catalog contract', () => {
models: [
{
...VALID_RESPONSE.models[0],
- agents: ['claude-code'],
- newSessionDefault: ['claude-code'],
+ agents: ["claude-code"],
+ newSessionDefault: ["claude-code"],
perAgent: { codex: { supportsFastMode: true } },
},
],
},
- 'response.models[0].perAgent.codex',
+ "response.models[0].perAgent.codex",
);
});
});
@@ -624,12 +687,12 @@ describe('model access catalog contract', () => {
function expectRegistryReject(value: unknown, path: string): void {
const result = parseModelRegistry(value);
expect(result.ok).toBe(false);
- if (result.ok) throw new Error('unreachable');
+ if (result.ok) throw new Error("unreachable");
expect(result.error).toContain(path);
}
-describe('public model registry contract', () => {
- it('round-trips canonical metadata, provider routes, and sourced reference prices', () => {
+describe("public model registry contract", () => {
+ it("round-trips canonical metadata, provider routes, and sourced reference prices", () => {
const wire = JSON.parse(JSON.stringify(VALID_REGISTRY));
expect(parseModelRegistry(wire)).toEqual({
ok: true,
@@ -637,48 +700,59 @@ describe('public model registry contract', () => {
});
});
- it('continues to parse legacy v1 registries, while v1 rejects the v2-only field', () => {
+ it("continues to parse legacy v1 registries, while v1 rejects the v2-only field", () => {
const legacy = {
...VALID_REGISTRY,
schemaVersion: MODEL_REGISTRY_LEGACY_SCHEMA_VERSION,
};
- expect(parseModelRegistry(JSON.parse(JSON.stringify(legacy))).ok).toBe(true);
+ expect(parseModelRegistry(JSON.parse(JSON.stringify(legacy))).ok).toBe(
+ true,
+ );
expectRegistryReject(
{
...legacy,
- models: [{ ...legacy.models[0], newSessionDefault: ['claude-code'] }],
+ models: [{ ...legacy.models[0], newSessionDefault: ["claude-code"] }],
},
- 'modelRegistry.models[0].newSessionDefault',
+ "modelRegistry.models[0].newSessionDefault",
);
});
- it('accepts newSessionDefault as a subset of the entry route agents', () => {
+ it("accepts newSessionDefault as a subset of the entry route agents", () => {
const entry = VALID_REGISTRY.models[0]!;
const wire = {
...VALID_REGISTRY,
- models: [{ ...entry, newSessionDefault: ['claude-code', 'codex'] }],
+ models: [{ ...entry, newSessionDefault: ["claude-code", "codex"] }],
};
const result = parseModelRegistry(JSON.parse(JSON.stringify(wire)));
expect(result.ok).toBe(true);
- if (!result.ok) throw new Error('unreachable');
- expect(result.value.models[0]!.newSessionDefault).toEqual(['claude-code', 'codex']);
+ if (!result.ok) throw new Error("unreachable");
+ expect(result.value.models[0]!.newSessionDefault).toEqual([
+ "claude-code",
+ "codex",
+ ]);
});
- it('rejects a malformed newSessionDefault (empty / duplicate / unknown agent)', () => {
+ it("rejects a malformed newSessionDefault (empty / duplicate / unknown agent)", () => {
const entry = VALID_REGISTRY.models[0]!;
const withDefault = (v: unknown) => ({
...VALID_REGISTRY,
models: [{ ...entry, newSessionDefault: v }],
});
- expectRegistryReject(withDefault([]), 'modelRegistry.models[0].newSessionDefault');
expectRegistryReject(
- withDefault(['claude-code', 'claude-code']),
- 'modelRegistry.models[0].newSessionDefault',
+ withDefault([]),
+ "modelRegistry.models[0].newSessionDefault",
+ );
+ expectRegistryReject(
+ withDefault(["claude-code", "claude-code"]),
+ "modelRegistry.models[0].newSessionDefault",
+ );
+ expectRegistryReject(
+ withDefault(["bogus-agent"]),
+ "modelRegistry.models[0].newSessionDefault",
);
- expectRegistryReject(withDefault(['bogus-agent']), 'modelRegistry.models[0].newSessionDefault');
});
- it('rejects newSessionDefault agents not backed by any route', () => {
+ it("rejects newSessionDefault agents not backed by any route", () => {
const entry = VALID_REGISTRY.models[0]!;
const route = entry.routes[0]!;
const wire = {
@@ -686,40 +760,45 @@ describe('public model registry contract', () => {
models: [
{
...entry,
- routes: [{ ...route, agents: ['claude-code'] }],
- newSessionDefault: ['codex'],
+ routes: [{ ...route, agents: ["claude-code"] }],
+ newSessionDefault: ["codex"],
},
],
};
expectRegistryReject(
JSON.parse(JSON.stringify(wire)),
- 'modelRegistry.models[0].newSessionDefault',
+ "modelRegistry.models[0].newSessionDefault",
);
});
- it('rejects newSessionDefault on retired registry entries', () => {
+ it("rejects newSessionDefault on retired registry entries", () => {
const entry = VALID_REGISTRY.models[0]!;
expectRegistryReject(
{
...VALID_REGISTRY,
- models: [{ ...entry, status: 'retired', newSessionDefault: ['claude-code'] }],
+ models: [
+ { ...entry, status: "retired", newSessionDefault: ["claude-code"] },
+ ],
},
- 'modelRegistry.models[0].newSessionDefault',
+ "modelRegistry.models[0].newSessionDefault",
);
});
- it('rejects client provenance and every other field outside the versioned schema', () => {
+ it("rejects client provenance and every other field outside the versioned schema", () => {
const entry = VALID_REGISTRY.models[0]!;
const route = entry.routes[0]!;
const price = route.referencePrices![0]!;
const cases: [unknown, string][] = [
- [{ ...VALID_REGISTRY, contextWindowVerified: true }, 'modelRegistry.contextWindowVerified'],
+ [
+ { ...VALID_REGISTRY, contextWindowVerified: true },
+ "modelRegistry.contextWindowVerified",
+ ],
[
{
...VALID_REGISTRY,
models: [{ ...entry, contextWindowExplicit: true }],
},
- 'modelRegistry.models[0].contextWindowExplicit',
+ "modelRegistry.models[0].contextWindowExplicit",
],
[
{
@@ -727,18 +806,18 @@ describe('public model registry contract', () => {
models: [
{
...entry,
- routes: [{ ...route, discoveredAt: '2026-07-31T00:00:00.000Z' }],
+ routes: [{ ...route, discoveredAt: "2026-07-31T00:00:00.000Z" }],
},
],
},
- 'modelRegistry.models[0].routes[0].discoveredAt',
+ "modelRegistry.models[0].routes[0].discoveredAt",
],
[
{
...VALID_REGISTRY,
models: [{ ...entry, perAgent: { codex: { verified: true } } }],
},
- 'modelRegistry.models[0].perAgent.codex.verified',
+ "modelRegistry.models[0].perAgent.codex.verified",
],
[
{
@@ -755,7 +834,7 @@ describe('public model registry contract', () => {
},
],
},
- 'modelRegistry.models[0].routes[0].referencePrices[0].userOverride',
+ "modelRegistry.models[0].routes[0].referencePrices[0].userOverride",
],
[
{
@@ -769,7 +848,7 @@ describe('public model registry contract', () => {
referencePrices: [
{
...price,
- source: { ...price.source, internalNote: 'client-only' },
+ source: { ...price.source, internalNote: "client-only" },
},
],
},
@@ -777,21 +856,24 @@ describe('public model registry contract', () => {
},
],
},
- 'modelRegistry.models[0].routes[0].referencePrices[0].source.internalNote',
+ "modelRegistry.models[0].routes[0].referencePrices[0].source.internalNote",
],
];
for (const [value, path] of cases) expectRegistryReject(value, path);
});
- it('rejects unsupported versions, duplicate canonical ids, and duplicate routes', () => {
- expectRegistryReject({ ...VALID_REGISTRY, schemaVersion: 4 }, 'modelRegistry.schemaVersion');
+ it("rejects unsupported versions, duplicate canonical ids, and duplicate routes", () => {
+ expectRegistryReject(
+ { ...VALID_REGISTRY, schemaVersion: 99 },
+ "modelRegistry.schemaVersion",
+ );
expectRegistryReject(
{
...VALID_REGISTRY,
models: [VALID_REGISTRY.models[0], VALID_REGISTRY.models[0]],
},
- 'modelRegistry.models[1].id',
+ "modelRegistry.models[1].id",
);
expectRegistryReject(
{
@@ -799,27 +881,33 @@ describe('public model registry contract', () => {
models: [
{
...VALID_REGISTRY.models[0],
- routes: [VALID_REGISTRY.models[0]!.routes[0], VALID_REGISTRY.models[0]!.routes[0]],
+ routes: [
+ VALID_REGISTRY.models[0]!.routes[0],
+ VALID_REGISTRY.models[0]!.routes[0],
+ ],
},
],
},
- 'modelRegistry.models[0].routes[1]',
+ "modelRegistry.models[0].routes[1]",
);
});
- it('requires a canonical, calendar-valid UTC timestamp', () => {
+ it("requires a canonical, calendar-valid UTC timestamp", () => {
for (const updatedAt of [
- '2026-07-31',
- 'July 31, 2026',
- '2026-07-31T00:00:00Z',
- '2026-02-29T00:00:00.000Z',
- '2026-07-31T08:00:00.000+08:00',
+ "2026-07-31",
+ "July 31, 2026",
+ "2026-07-31T00:00:00Z",
+ "2026-02-29T00:00:00.000Z",
+ "2026-07-31T08:00:00.000+08:00",
]) {
- expectRegistryReject({ ...VALID_REGISTRY, updatedAt }, 'modelRegistry.updatedAt');
+ expectRegistryReject(
+ { ...VALID_REGISTRY, updatedAt },
+ "modelRegistry.updatedAt",
+ );
}
});
- it('rejects malformed price bands and untraceable price sources', () => {
+ it("rejects malformed price bands and untraceable price sources", () => {
const baseRoute = VALID_REGISTRY.models[0]!.routes[0]!;
const basePrice = baseRoute.referencePrices![0]!;
expectRegistryReject(
@@ -843,7 +931,7 @@ describe('public model registry contract', () => {
},
],
},
- 'maxInputTokens',
+ "maxInputTokens",
);
expectRegistryReject(
{
@@ -859,7 +947,7 @@ describe('public model registry contract', () => {
...basePrice,
source: {
...basePrice.source,
- url: 'http://example.com/pricing',
+ url: "http://example.com/pricing",
},
},
],
@@ -868,11 +956,11 @@ describe('public model registry contract', () => {
},
],
},
- 'source.url',
+ "source.url",
);
});
- it('allows scheduled prices and agent-specific metadata only on supported routes', () => {
+ it("allows scheduled prices and agent-specific metadata only on supported routes", () => {
const baseRoute = VALID_REGISTRY.models[0]!.routes[0]!;
const basePrice = baseRoute.referencePrices![0]!;
expect(
@@ -886,12 +974,12 @@ describe('public model registry contract', () => {
{
...baseRoute,
referencePrices: [
- { ...basePrice, effectiveUntil: '2026-09-01' },
+ { ...basePrice, effectiveUntil: "2026-09-01" },
{
...basePrice,
inputPerMtok: 2,
outputPerMtok: 10,
- effectiveFrom: '2026-09-01',
+ effectiveFrom: "2026-09-01",
},
],
},
@@ -907,16 +995,16 @@ describe('public model registry contract', () => {
models: [
{
...VALID_REGISTRY.models[0],
- routes: [{ ...baseRoute, agents: ['claude-code'] }],
+ routes: [{ ...baseRoute, agents: ["claude-code"] }],
perAgent: { codex: { contextWindow: 272_000 } },
},
],
},
- 'perAgent.codex',
+ "perAgent.codex",
);
});
- it('carries a materialization-complete presence shape on the current v2 wire', () => {
+ it("carries a materialization-complete presence shape on the current v2 wire", () => {
// The exact shape a policy-based client requires before deriving a
// selectable entry (MODEL_REGISTRY.md "Presence, entitlement, and sale
// availability"): explicit status + self-consistent capability set +
@@ -927,13 +1015,13 @@ describe('public model registry contract', () => {
models: [
{
...VALID_REGISTRY.models[0],
- status: 'preview',
+ status: "preview",
maxOutputTokens: 64_000,
perAgent: {
codex: {
contextWindow: 272_000,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'high',
+ efforts: ["low", "medium", "high"],
+ defaultEffort: "high",
},
},
},
@@ -942,17 +1030,21 @@ describe('public model registry contract', () => {
expect(parseModelRegistry(JSON.parse(JSON.stringify(wire))).ok).toBe(true);
});
- it.each(MODEL_REGISTRY_STATUSES)('accepts the %s lifecycle status', (status) => {
- expect(
- parseModelRegistry({
- ...VALID_REGISTRY,
- models: [{ ...VALID_REGISTRY.models[0], status }],
- }).ok,
- ).toBe(true);
- });
+ it.each(MODEL_REGISTRY_STATUSES)(
+ "accepts the %s lifecycle status",
+ (status) => {
+ expect(
+ parseModelRegistry({
+ ...VALID_REGISTRY,
+ models: [{ ...VALID_REGISTRY.models[0], status }],
+ }).ok,
+ ).toBe(true);
+ },
+ );
- it('accepts a fixed-effort entry: empty efforts with no default', () => {
- const { defaultEffort: _defaultEffort, ...entry } = VALID_REGISTRY.models[0]!;
+ it("accepts a fixed-effort entry: empty efforts with no default", () => {
+ const { defaultEffort: _defaultEffort, ...entry } =
+ VALID_REGISTRY.models[0]!;
expect(
parseModelRegistry({
...VALID_REGISTRY,
@@ -961,13 +1053,15 @@ describe('public model registry contract', () => {
).toBe(true);
});
- it('canonicalizes object key order while preserving snapshot content changes', () => {
+ it("canonicalizes object key order while preserving snapshot content changes", () => {
const reordered = {
models: VALID_REGISTRY.models,
updatedAt: VALID_REGISTRY.updatedAt,
schemaVersion: VALID_REGISTRY.schemaVersion,
};
- expect(modelRegistryCanonicalJson(reordered)).toBe(modelRegistryCanonicalJson(VALID_REGISTRY));
+ expect(modelRegistryCanonicalJson(reordered)).toBe(
+ modelRegistryCanonicalJson(VALID_REGISTRY),
+ );
expect(
modelRegistryCanonicalJson({
...reordered,
@@ -977,16 +1071,18 @@ describe('public model registry contract', () => {
const secondModel = {
...VALID_REGISTRY.models[0]!,
- id: 'example/other-model',
+ id: "example/other-model",
routes: [
{
...VALID_REGISTRY.models[0]!.routes[0]!,
- modelId: 'other-model',
+ modelId: "other-model",
},
],
};
const orderedModels = [VALID_REGISTRY.models[0]!, secondModel];
- expect(modelRegistryCanonicalJson({ ...VALID_REGISTRY, models: orderedModels })).not.toBe(
+ expect(
+ modelRegistryCanonicalJson({ ...VALID_REGISTRY, models: orderedModels }),
+ ).not.toBe(
modelRegistryCanonicalJson({
...VALID_REGISTRY,
models: [...orderedModels].reverse(),
@@ -994,17 +1090,17 @@ describe('public model registry contract', () => {
);
});
- it('keeps availability and selectability out of the wire schema', () => {
+ it("keeps availability and selectability out of the wire schema", () => {
// Presence is the only registry-owned signal; availability/selectability
// markers are foreign fields at every level.
const entry = VALID_REGISTRY.models[0]!;
const route = entry.routes[0]!;
const cases: [unknown, string][] = [
- [{ ...entry, available: true }, 'modelRegistry.models[0].available'],
- [{ ...entry, selectable: true }, 'modelRegistry.models[0].selectable'],
+ [{ ...entry, available: true }, "modelRegistry.models[0].available"],
+ [{ ...entry, selectable: true }, "modelRegistry.models[0].selectable"],
[
{ ...entry, routes: [{ ...route, available: true }] },
- 'modelRegistry.models[0].routes[0].available',
+ "modelRegistry.models[0].routes[0].available",
],
];
for (const [model, path] of cases) {
@@ -1012,19 +1108,19 @@ describe('public model registry contract', () => {
}
});
- it('rejects client-derived agent harnesses on routes and per-agent overrides', () => {
+ it("rejects client-derived agent harnesses on routes and per-agent overrides", () => {
// Projection harnesses (for example a client-side pi tab) never appear on
// the wire; the closed agent enum keeps them client-owned.
const entry = VALID_REGISTRY.models[0]!;
const route = entry.routes[0]!;
const cases: [unknown, string][] = [
[
- { ...entry, routes: [{ ...route, agents: ['claude-code', 'pi'] }] },
- 'modelRegistry.models[0].routes[0].agents',
+ { ...entry, routes: [{ ...route, agents: ["claude-code", "pi"] }] },
+ "modelRegistry.models[0].routes[0].agents",
],
[
{ ...entry, perAgent: { pi: { contextWindow: 200_000 } } },
- 'modelRegistry.models[0].perAgent.pi',
+ "modelRegistry.models[0].perAgent.pi",
],
];
for (const [model, path] of cases) {
@@ -1032,7 +1128,7 @@ describe('public model registry contract', () => {
}
});
- it('rejects ambiguous overlapping reference prices for the same currency and variant', () => {
+ it("rejects ambiguous overlapping reference prices for the same currency and variant", () => {
const baseRoute = VALID_REGISTRY.models[0]!.routes[0]!;
const basePrice = baseRoute.referencePrices![0]!;
for (const overlappingPrice of [
@@ -1040,8 +1136,8 @@ describe('public model registry contract', () => {
{ ...basePrice, minInputTokens: 100_000, maxInputTokens: 300_000 },
{
...basePrice,
- effectiveFrom: '2026-07-15',
- effectiveUntil: '2026-08-01',
+ effectiveFrom: "2026-07-15",
+ effectiveUntil: "2026-08-01",
},
]) {
expectRegistryReject(
@@ -1059,7 +1155,7 @@ describe('public model registry contract', () => {
},
],
},
- 'referencePrices[1] overlaps referencePrices[0]',
+ "referencePrices[1] overlaps referencePrices[0]",
);
}
});
diff --git a/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts b/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts
index 64d476c6f1..7e4b6dd0f9 100644
--- a/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts
+++ b/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts
@@ -1,48 +1,87 @@
-import { describe, expect, it } from 'vitest';
-import registry from '../../catalog/model-registry.json';
-import { modelDefaultEffort, defaultEffortForCapabilities } from '../effortResolution.js';
+import { expandedRegistryEntries } from "../modelMetadataLayers.js";
+import type { ModelRegistry } from "../modelAccessBean.js";
+import { describe, expect, it } from "vitest";
+import rawRegistry from "../../catalog/model-registry.json";
+import {
+ modelDefaultEffort,
+ defaultEffortForCapabilities,
+} from "../effortResolution.js";
-describe('model-level default effort', () => {
- it('ignores conflicting harness defaults when the model declares its own', () => {
- expect(modelDefaultEffort({ defaultEffort: 'medium', perAgent: {
- codex: { defaultEffort: 'high' }, pi: { defaultEffort: 'xhigh' },
- } })).toBe('medium');
- expect(modelDefaultEffort({ defaultEffort: null, perAgent: {
- codex: { defaultEffort: 'high' },
- } })).toBeNull();
+describe("model-level default effort", () => {
+ it("ignores conflicting harness defaults when the model declares its own", () => {
+ expect(
+ modelDefaultEffort({
+ defaultEffort: "medium",
+ perAgent: {
+ codex: { defaultEffort: "high" },
+ pi: { defaultEffort: "xhigh" },
+ },
+ }),
+ ).toBe("medium");
+ expect(
+ modelDefaultEffort({
+ defaultEffort: null,
+ perAgent: {
+ codex: { defaultEffort: "high" },
+ },
+ }),
+ ).toBeNull();
});
- it('promotes a consistent legacy value once for every harness', () => {
- expect(modelDefaultEffort({ perAgent: { codex: { defaultEffort: 'medium' } } }))
- .toBe('medium');
- expect(modelDefaultEffort({ perAgent: {
- codex: { defaultEffort: 'high' }, 'claude-code': { defaultEffort: 'high' },
- } })).toBe('high');
+ it("promotes a consistent legacy value once for every harness", () => {
+ expect(
+ modelDefaultEffort({ perAgent: { codex: { defaultEffort: "medium" } } }),
+ ).toBe("medium");
+ expect(
+ modelDefaultEffort({
+ perAgent: {
+ codex: { defaultEffort: "high" },
+ "claude-code": { defaultEffort: "high" },
+ },
+ }),
+ ).toBe("high");
});
- it('resolves legacy conflicts conservatively without depending on the harness order', () => {
+ it("resolves legacy conflicts conservatively without depending on the harness order", () => {
expect(modelDefaultEffort({})).toBeUndefined();
- expect(modelDefaultEffort({ perAgent: {
- codex: { defaultEffort: 'high' }, 'claude-code': { defaultEffort: 'medium' },
- } })).toBe('medium');
- expect(modelDefaultEffort({ perAgent: {
- 'claude-code': { defaultEffort: 'medium' }, codex: { defaultEffort: 'high' },
- } })).toBe('medium');
+ expect(
+ modelDefaultEffort({
+ perAgent: {
+ codex: { defaultEffort: "high" },
+ "claude-code": { defaultEffort: "medium" },
+ },
+ }),
+ ).toBe("medium");
+ expect(
+ modelDefaultEffort({
+ perAgent: {
+ "claude-code": { defaultEffort: "medium" },
+ codex: { defaultEffort: "high" },
+ },
+ }),
+ ).toBe("medium");
});
});
-
-describe('medium-first defaults', () => {
- it('uses actual capabilities independent of discovery order', () => {
- expect(defaultEffortForCapabilities(['max', 'low', 'medium'])).toBe('medium');
- expect(defaultEffortForCapabilities(['minimal', 'high', 'max'])).toBe('high');
- expect(defaultEffortForCapabilities(['low'])).toBe('low');
+describe("medium-first defaults", () => {
+ it("uses actual capabilities independent of discovery order", () => {
+ expect(defaultEffortForCapabilities(["max", "low", "medium"])).toBe(
+ "medium",
+ );
+ expect(defaultEffortForCapabilities(["minimal", "high", "max"])).toBe(
+ "high",
+ );
+ expect(defaultEffortForCapabilities(["low"])).toBe("low");
expect(defaultEffortForCapabilities([])).toBeNull();
});
- it('keeps the maintained table consistent across harnesses without fabricating medium', () => {
- for (const model of registry.models) {
+ it("keeps the maintained table consistent across harnesses without fabricating medium", () => {
+ for (const model of expandedRegistryEntries(
+ rawRegistry as unknown as ModelRegistry,
+ )) {
if (!model.efforts?.length) continue;
- expect(model.defaultEffort, model.id).toBe(defaultEffortForCapabilities(model.efforts));
+ expect(model.defaultEffort, model.id).toBe(
+ defaultEffortForCapabilities(model.efforts),
+ );
for (const override of Object.values(model.perAgent ?? {})) {
- expect(override, model.id).not.toHaveProperty('defaultEffort');
+ expect(override.defaultEffort, model.id).toBe(model.defaultEffort);
}
}
});
diff --git a/packages/model-providers/src/__tests__/modelMetadataLayers.test.ts b/packages/model-providers/src/__tests__/modelMetadataLayers.test.ts
new file mode 100644
index 0000000000..e73a7fa029
--- /dev/null
+++ b/packages/model-providers/src/__tests__/modelMetadataLayers.test.ts
@@ -0,0 +1,422 @@
+import { describe, expect, it } from "vitest";
+import {
+ resolveModelMetadata,
+ expandedRegistryEntries,
+} from "../modelMetadataLayers.js";
+import { parseModelRegistry } from "../modelAccessValidator.js";
+import type { ModelRegistry } from "../modelAccessBean.js";
+
+const registry: ModelRegistry = {
+ schemaVersion: 4,
+ updatedAt: "2026-09-08T06:00:00.000Z",
+ baseModels: [
+ {
+ id: "vendor/model",
+ aliases: ["model"],
+ defaults: {
+ name: "Model",
+ contextWindow: 100,
+ maxOutputTokens: 10,
+ efforts: ["low", "high"],
+ defaultEffort: "low",
+ supportsFastMode: true,
+ },
+ },
+ ],
+ models: [
+ {
+ id: "saved-model-id",
+ name: "Model",
+ modelRef: "vendor/model",
+ routes: [
+ {
+ providerId: "supplier",
+ modelId: "model",
+ agents: ["codex"],
+ defaults: { contextWindow: 200 },
+ forceOverrides: { maxOutputTokens: 20 },
+ overrideReason: "Supplier output limit is incorrectly reported",
+ },
+ ],
+ },
+ ],
+};
+
+it("honors entry names below route, live, force and user names", () => {
+ const r = structuredClone(registry);
+ r.models[0].name = "Entry";
+ const route = r.models[0].routes[0];
+ expect(expandedRegistryEntries(r)[0].name).toBe("Entry");
+ expect(
+ resolveModelMetadata(
+ r,
+ "supplier",
+ "model",
+ undefined,
+ undefined,
+ undefined,
+ { name: "Provider default" },
+ ).name,
+ ).toBe("Entry");
+ expect(resolveModelMetadata(r, "unknown", "model").name).toBe("Model");
+ route.defaults = { name: "Route" };
+ expect(expandedRegistryEntries(r)[0].name).toBe("Route");
+ expect(
+ resolveModelMetadata(r, "supplier", "model", { name: "Live" }).name,
+ ).toBe("Live");
+ route.forceOverrides = { name: "Force" };
+ expect(
+ resolveModelMetadata(r, "supplier", "model", { name: "Live" }).name,
+ ).toBe("Force");
+ expect(
+ resolveModelMetadata(
+ r,
+ "supplier",
+ "model",
+ { name: "Live" },
+ { name: "User" },
+ ).name,
+ ).toBe("User");
+});
+
+it("requires public effort defaults to stand alone even without registry routes", () => {
+ const r = structuredClone(registry);
+ r.models = [];
+ const defaults = r.baseModels![0].defaults;
+ defaults.efforts = ["low"];
+ defaults.defaultEffort = "high";
+ expect(parseModelRegistry(r).ok).toBe(false);
+ defaults.defaultEffort = "low";
+ expect(parseModelRegistry(r).ok).toBe(true);
+ defaults.efforts = [];
+ expect(parseModelRegistry(r).ok).toBe(false);
+ defaults.defaultEffort = null;
+ expect(parseModelRegistry(r).ok).toBe(true);
+ delete defaults.defaultEffort;
+ expect(parseModelRegistry(r).ok).toBe(true);
+});
+describe("model metadata precedence", () => {
+ it("inherits per field and lets supplier data beat defaults, explicit force beat supplier and user beat force", () => {
+ expect(parseModelRegistry(registry).ok).toBe(true);
+ expect(resolveModelMetadata(registry, "supplier", "model")).toMatchObject({
+ name: "Model",
+ contextWindow: 200,
+ maxOutputTokens: 20,
+ });
+ expect(
+ resolveModelMetadata(registry, "supplier", "model", {
+ contextWindow: 300,
+ maxOutputTokens: 30,
+ supportsFastMode: false,
+ }),
+ ).toMatchObject({
+ contextWindow: 300,
+ maxOutputTokens: 20,
+ supportsFastMode: false,
+ });
+ expect(
+ resolveModelMetadata(
+ registry,
+ "supplier",
+ "model",
+ { contextWindow: 300 },
+ { maxOutputTokens: 40 },
+ ),
+ ).toMatchObject({ contextWindow: 300, maxOutputTokens: 40 });
+ });
+ it("uses only public defaults for an unknown supplier, never another supplier force", () => {
+ expect(
+ resolveModelMetadata(registry, "new-supplier", "model"),
+ ).toMatchObject({
+ contextWindow: 100,
+ maxOutputTokens: 10,
+ });
+ expect(
+ resolveModelMetadata(registry, "new-supplier", "similar-model"),
+ ).toEqual({});
+ });
+ it("preserves explicit empty effort lists, null defaults and false flags", () => {
+ expect(
+ resolveModelMetadata(registry, "supplier", "model", {
+ efforts: [],
+ supportsFastMode: false,
+ }),
+ ).toMatchObject({
+ efforts: [],
+ defaultEffort: null,
+ supportsFastMode: false,
+ });
+ expect(
+ resolveModelMetadata(registry, "supplier", "model", {
+ defaultEffort: null,
+ }).defaultEffort,
+ ).toBeNull();
+ });
+ it("keeps the saved entry and upstream identifiers when expanding public defaults", () => {
+ expect(expandedRegistryEntries(registry)[0]).toMatchObject({
+ id: "saved-model-id",
+ contextWindow: 200,
+ routes: [{ modelId: "model", providerId: "supplier" }],
+ });
+ });
+ it.each([
+ (r: ModelRegistry) => {
+ r.baseModels!.push({ ...r.baseModels![0], id: "other" });
+ },
+ (r: ModelRegistry) => {
+ r.models[0].modelRef = "missing";
+ },
+ (r: ModelRegistry) => {
+ delete r.models[0].routes[0].overrideReason;
+ },
+ (r: ModelRegistry) => {
+ r.models[0].routes[0].forceOverrides = { contextWindow: -1 };
+ },
+ (r: ModelRegistry) => {
+ r.schemaVersion = 3;
+ },
+ ])(
+ "rejects ambiguous identities, invalid overrides and unsupported versions",
+ (mutate) => {
+ const bad = structuredClone(registry);
+ mutate(bad);
+ expect(parseModelRegistry(bad).ok).toBe(false);
+ },
+ );
+});
+
+describe("routing-only V4 layers", () => {
+ it("honors route layers without public models and clears legacy per-agent defaults", () => {
+ const r: ModelRegistry = {
+ schemaVersion: 4,
+ updatedAt: registry.updatedAt,
+ models: [
+ {
+ id: "existing",
+ name: "Existing",
+ contextWindow: 100,
+ efforts: ["low", "high"],
+ defaultEffort: "low",
+ perAgent: { codex: { defaultEffort: "high" } },
+ routes: [
+ {
+ providerId: "one",
+ modelId: "existing",
+ agents: ["codex"],
+ defaults: { contextWindow: 200 },
+ forceOverrides: { defaultEffort: null },
+ overrideReason: "Clear incorrect default",
+ },
+ ],
+ },
+ ],
+ };
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(resolveModelMetadata(r, "one", "existing")).toMatchObject({
+ contextWindow: 200,
+ defaultEffort: null,
+ });
+ expect(
+ expandedRegistryEntries(r)[0].perAgent?.codex?.defaultEffort,
+ ).toBeUndefined();
+ expect(expandedRegistryEntries(r)[0].contextWindow).toBe(200);
+ });
+});
+
+it("validates force corrections after per-agent defaults", () => {
+ const r = structuredClone(registry);
+ r.models[0].efforts = ["high"];
+ r.models[0].defaultEffort = "high";
+ r.models[0].perAgent = { codex: { defaultEffort: "high" } };
+ r.models[0].routes[0].forceOverrides = {
+ efforts: ["low"],
+ defaultEffort: "low",
+ };
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(expandedRegistryEntries(r)[0].perAgent?.codex).toMatchObject({
+ efforts: ["low"],
+ defaultEffort: "low",
+ });
+});
+
+it("groups equal effective route metadata regardless of layer key insertion order", () => {
+ const r: ModelRegistry = {
+ schemaVersion: 4,
+ updatedAt: registry.updatedAt,
+ models: [
+ {
+ id: "stable",
+ name: "Stable",
+ routes: [
+ {
+ providerId: "one",
+ modelId: "model",
+ agents: ["codex"],
+ defaults: { contextWindow: 200, supportsFastMode: false },
+ forceOverrides: { maxOutputTokens: 20 },
+ overrideReason: "Verified limit",
+ },
+ {
+ providerId: "two",
+ modelId: "model",
+ agents: ["codex"],
+ defaults: { maxOutputTokens: 20, supportsFastMode: false },
+ forceOverrides: { contextWindow: 200 },
+ overrideReason: "Verified window",
+ },
+ ],
+ },
+ ],
+ };
+ const before = structuredClone(r);
+ expect(parseModelRegistry(r).ok).toBe(true);
+ const projected = expandedRegistryEntries(r);
+ expect(projected).toHaveLength(1);
+ expect(projected[0].id).toBe("stable");
+ expect(projected[0].routes.map((route) => route.providerId)).toEqual([
+ "one",
+ "two",
+ ]);
+ expect(r).toEqual(before);
+ r.models[0].routes[1].forceOverrides!.contextWindow = 300;
+ expect(expandedRegistryEntries(r)).toHaveLength(2);
+});
+
+it.each(["entry", "runtime"] as const)(
+ "accepts V4 null clears at the %s layer and keeps legacy wire valid",
+ (layer) => {
+ const r = structuredClone(registry);
+ r.models[0].routes[0].agents = ["codex", "claude-code"];
+ if (layer === "entry") r.models[0].defaultEffort = null;
+ else
+ r.models[0].perAgent = {
+ codex: { efforts: ["high"], defaultEffort: null },
+ };
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(
+ resolveModelMetadata(
+ r,
+ "supplier",
+ "model",
+ undefined,
+ undefined,
+ "codex",
+ ).defaultEffort,
+ ).toBeNull();
+ const projected = expandedRegistryEntries(r);
+ expect(projected[0].defaultEffort).toBeUndefined();
+ expect(projected[0].perAgent?.codex?.defaultEffort).toBeUndefined();
+ if (layer === "runtime")
+ expect(projected[0].perAgent?.["claude-code"]?.defaultEffort).toBe("low");
+ for (const schemaVersion of [1, 2, 3] as const) {
+ const legacy = structuredClone(r);
+ legacy.schemaVersion = schemaVersion;
+ delete legacy.baseModels;
+ delete legacy.models[0].modelRef;
+ delete legacy.models[0].routes[0].defaults;
+ delete legacy.models[0].routes[0].forceOverrides;
+ delete legacy.models[0].routes[0].overrideReason;
+ expect(parseModelRegistry(legacy).ok).toBe(false);
+ legacy.models = structuredClone(projected);
+ for (const entry of legacy.models) {
+ delete entry.modelRef;
+ for (const route of entry.routes) {
+ delete route.defaults;
+ delete route.forceOverrides;
+ delete route.overrideReason;
+ }
+ }
+ expect(parseModelRegistry(legacy).ok).toBe(true);
+ }
+ },
+);
+
+it("keeps local packaging names outside supplier public identity fallback", () => {
+ const r = structuredClone(registry);
+ r.localModels = {
+ version: 1,
+ featuredIds: [],
+ models: [
+ {
+ id: "local-model",
+ name: "Local",
+ modelRef: "vendor/model",
+ aliases: [],
+ variants: [
+ {
+ libraryName: "model:local",
+ sizeBytes: 1024 ** 3,
+ minUnifiedMemoryGb: 4,
+ },
+ ],
+ },
+ ],
+ };
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(resolveModelMetadata(r, "unknown", "model:local")).toEqual({});
+ expect(resolveModelMetadata(r, "unknown", "vendor/model").name).toBe("Model");
+ expect(resolveModelMetadata(r, "unknown", "model").name).toBe("Model");
+ // Local modelRef continues resolving explicitly; only public aliases opt cloud IDs in.
+ expect(
+ resolveModelMetadata(r, "unknown", r.localModels.models[0].modelRef!).name,
+ ).toBe("Model");
+ r.baseModels![0].aliases.push("model:local");
+ expect(resolveModelMetadata(r, "unknown", "model:local").name).toBe("Model");
+});
+
+it.each([true, false])(
+ "accepts V4 entry image capability %s and strips it from legacy entries",
+ (image) => {
+ const r = structuredClone(registry);
+ r.models[0].supportsImageInput = image;
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(
+ resolveModelMetadata(r, "supplier", "model").supportsImageInput,
+ ).toBe(image);
+ expect(
+ resolveModelMetadata(r, "supplier", "model", {
+ supportsImageInput: !image,
+ }).supportsImageInput,
+ ).toBe(!image);
+ r.models[0].routes[0].forceOverrides!.supportsImageInput = image;
+ expect(
+ resolveModelMetadata(r, "supplier", "model", {
+ supportsImageInput: !image,
+ }).supportsImageInput,
+ ).toBe(image);
+ const expanded = expandedRegistryEntries(r);
+ expect(expanded[0]).not.toHaveProperty("supportsImageInput");
+ const invalid = structuredClone(r) as unknown as {
+ models: Record<string, unknown>[];
+ };
+ invalid.models[0].supportsImageInput = "true";
+ expect(parseModelRegistry(invalid).ok).toBe(false);
+ for (const schemaVersion of [1, 2, 3] as const) {
+ const legacy = {
+ schemaVersion,
+ updatedAt: r.updatedAt,
+ models: expanded.map((entry) => {
+ const { modelRef, ...rest } = entry;
+ return {
+ ...rest,
+ routes: entry.routes.map((route) => ({
+ providerId: route.providerId,
+ modelId: route.modelId,
+ agents: route.agents,
+ })),
+ };
+ }),
+ };
+ expect(parseModelRegistry(legacy).ok).toBe(true);
+ expect(
+ parseModelRegistry({
+ ...legacy,
+ models: legacy.models.map((entry) => ({
+ ...entry,
+ supportsImageInput: image,
+ })),
+ }).ok,
+ ).toBe(false);
+ }
+ },
+);
diff --git a/packages/model-providers/src/__tests__/modelMetadataValidation.test.ts b/packages/model-providers/src/__tests__/modelMetadataValidation.test.ts
new file mode 100644
index 0000000000..753ff30f77
--- /dev/null
+++ b/packages/model-providers/src/__tests__/modelMetadataValidation.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from "vitest";
+import { parseModelRegistry } from "../modelAccessValidator.js";
+import { expandedRegistryEntries } from "../modelMetadataLayers.js";
+import type { ModelRegistry } from "../modelAccessBean.js";
+
+function fixture(): ModelRegistry {
+ return {
+ schemaVersion: 4,
+ updatedAt: "2026-09-08T06:00:00.000Z",
+ baseModels: [{ id: "public", aliases: ["alias"], defaults: {} }],
+ models: [
+ {
+ id: "route",
+ name: "Route",
+ efforts: ["low"],
+ routes: [
+ { providerId: "supplier", modelId: "route", agents: ["codex"] },
+ ],
+ },
+ ],
+ };
+}
+
+describe("V4 metadata validation boundaries", () => {
+ it.each([1, 247, 248, 256])(
+ "keeps split routes valid with a %i-character ID and reserved ID collisions",
+ (length) => {
+ const r = fixture();
+ const entry = r.models[0];
+ entry.id = "a".repeat(length);
+ entry.newSessionDefault = ["codex"];
+ entry.perAgent = { codex: { contextWindow: 1000 } };
+ entry.routes.push({
+ providerId: "other",
+ modelId: "route",
+ agents: ["claude-code"],
+ defaults: { contextWindow: 2000 },
+ });
+ const projectedId = entry.id.slice(0, 247) + "::route-2";
+ r.models.push({
+ id: projectedId,
+ name: "Reserved",
+ routes: [
+ { providerId: "reserved", modelId: "reserved", agents: ["codex"] },
+ ],
+ });
+ const expanded = expandedRegistryEntries(r);
+ expect(expanded).toHaveLength(3);
+ expect(expanded[0].id).toBe(entry.id);
+ expect(expanded[0].newSessionDefault).toEqual(["codex"]);
+ expect(expanded[1]).not.toHaveProperty("newSessionDefault");
+ expect(expanded[1]).not.toHaveProperty("perAgent");
+ expect(expanded[2].id).toBe(projectedId);
+ expect(new Set(expanded.map((model) => model.id)).size).toBe(3);
+ expect(expanded.every((model) => model.id.length <= 256)).toBe(true);
+ expect(expandedRegistryEntries(r)).toEqual(expanded);
+ expect(parseModelRegistry(r).ok).toBe(true);
+ for (const schemaVersion of [2, 3] as const) {
+ const legacy = expanded.map(({ modelRef, ...model }) => ({
+ ...model,
+ routes: model.routes.map(
+ ({ defaults, forceOverrides, overrideReason, ...route }) => route,
+ ),
+ }));
+ expect(
+ parseModelRegistry({
+ schemaVersion,
+ updatedAt: r.updatedAt,
+ models: legacy,
+ }).ok,
+ ).toBe(true);
+ }
+ // Projection does not mutate the original defaults or route membership.
+ expect(entry.newSessionDefault).toEqual(["codex"]);
+ expect(entry.routes).toHaveLength(2);
+ },
+ );
+
+ it.each([
+ ["name", 256],
+ ["group", 128],
+ ["description", 2000],
+ ] as const)(
+ "enforces %s wire limits even on unreferenced public models and all route layers",
+ (field, max) => {
+ for (const layer of ["public", "defaults", "forceOverrides"] as const) {
+ const r = fixture();
+ const route = r.models[0].routes[0];
+ const metadata = { [field]: "a".repeat(max) };
+ if (layer === "public") r.baseModels![0].defaults = metadata;
+ else {
+ route[layer] = metadata;
+ route.overrideReason = "Correct supplier metadata";
+ }
+ expect(parseModelRegistry(r).ok).toBe(true);
+ metadata[field] += "a";
+ expect(parseModelRegistry(r).ok).toBe(false);
+ }
+ },
+ );
+
+ it.each(["entry", "agent", "inherited-agent"] as const)(
+ "checks %s effort dependencies after route defaults",
+ (scope) => {
+ const r = fixture();
+ const entry = r.models[0];
+ if (scope === "entry") entry.defaultEffort = "high";
+ else if (scope === "agent")
+ entry.perAgent = { codex: { defaultEffort: "high" } };
+ else {
+ entry.defaultEffort = "low";
+ entry.perAgent = { codex: { efforts: ["high"] } };
+ }
+ entry.routes[0].defaults = { efforts: ["high"], defaultEffort: "high" };
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(expandedRegistryEntries(r)[0]).toMatchObject({
+ efforts: ["high"],
+ defaultEffort: "high",
+ });
+ delete entry.routes[0].defaults;
+ expect(parseModelRegistry(r).ok).toBe(false);
+ },
+ );
+
+ it("applies force after inconsistent entry and agent defaults but still validates final dependencies", () => {
+ const r = fixture();
+ const entry = r.models[0];
+ entry.defaultEffort = "high";
+ entry.perAgent = { codex: { efforts: ["low"], defaultEffort: "high" } };
+ const route = entry.routes[0];
+ route.forceOverrides = { efforts: ["high"] };
+ route.overrideReason = "Correct supported efforts";
+ expect(parseModelRegistry(r).ok).toBe(true);
+ expect(expandedRegistryEntries(r)[0].perAgent?.codex).toMatchObject({
+ efforts: ["high"],
+ defaultEffort: "high",
+ });
+ route.forceOverrides = { efforts: ["low"] };
+ expect(parseModelRegistry(r).ok).toBe(false);
+ });
+
+ it("does not hide invalid raw field types behind valid force corrections", () => {
+ const r = fixture();
+ const entry = r.models[0];
+ entry.routes[0].forceOverrides = {
+ efforts: ["high"],
+ defaultEffort: "high",
+ };
+ entry.routes[0].overrideReason = "Correct supplier metadata";
+ for (const target of [entry, (entry.perAgent = { codex: {} }).codex]) {
+ Object.assign(target, { defaultEffort: "unknown" });
+ expect(parseModelRegistry(r).ok).toBe(false);
+ Reflect.deleteProperty(target, "defaultEffort");
+ }
+ });
+
+ it.each([1, 2, 3] as const)(
+ "preserves V%s dependency validation",
+ (schemaVersion) => {
+ const r = fixture();
+ r.schemaVersion = schemaVersion;
+ delete r.baseModels;
+ r.models[0].defaultEffort = "high";
+ expect(parseModelRegistry(r).ok).toBe(false);
+ },
+ );
+});
diff --git a/packages/model-providers/src/__tests__/modelRegistry.test.ts b/packages/model-providers/src/__tests__/modelRegistry.test.ts
index 1d3600936e..22c56ba23c 100644
--- a/packages/model-providers/src/__tests__/modelRegistry.test.ts
+++ b/packages/model-providers/src/__tests__/modelRegistry.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { BUNDLED_CATALOG } from "../builtin.js";
+import { expandedRegistryEntries } from "../modelMetadataLayers.js";
import {
compareModelRegistryRevisions,
findModelRegistryRoute,
@@ -115,7 +116,10 @@ describe("model registry", () => {
).toMatchObject({
entry: {
contextWindow: 1_050_000,
- perAgent: { codex: { contextWindow: 272_000 }, 'claude-code': { contextWindow: 272_000 } },
+ perAgent: {
+ codex: { contextWindow: 272_000 },
+ "claude-code": { contextWindow: 272_000 },
+ },
maxOutputTokens: 128_000,
},
});
@@ -322,20 +326,37 @@ describe("model registry", () => {
});
});
-
it.each([
- { variant: 'standard' as const, input: 20, output: 75, read: 2, write: 25 },
- { variant: 'fast' as const, input: 40, output: 150, read: 4, write: 50 },
-])('uses verified Astra $variant long-input rates from September 7', ({ variant, input, output, read, write }) => {
- const options = { variant, at: new Date('2026-09-07T00:00:00Z') };
- expect(resolveModelReferencePrice(registry, 'openai', 'gpt-6-astra', { ...options, inputTokens: 272_000 })?.price)
- .toMatchObject({ inputPerMtok: input / 2, outputPerMtok: output / 1.5 });
- expect(resolveModelReferencePrice(registry, 'openai', 'gpt-6-astra', { ...options, inputTokens: 272_001 })?.price)
- .toMatchObject({ inputPerMtok: input, outputPerMtok: output, cacheReadPerMtok: read, cacheWritePerMtok: write });
-});
-
+ { variant: "standard" as const, input: 20, output: 75, read: 2, write: 25 },
+ { variant: "fast" as const, input: 40, output: 150, read: 4, write: 50 },
+])(
+ "uses verified Astra $variant long-input rates from September 7",
+ ({ variant, input, output, read, write }) => {
+ const options = { variant, at: new Date("2026-09-07T00:00:00Z") };
+ expect(
+ resolveModelReferencePrice(registry, "openai", "gpt-6-astra", {
+ ...options,
+ inputTokens: 272_000,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: input / 2, outputPerMtok: output / 1.5 });
+ expect(
+ resolveModelReferencePrice(registry, "openai", "gpt-6-astra", {
+ ...options,
+ inputTokens: 272_001,
+ })?.price,
+ ).toMatchObject({
+ inputPerMtok: input,
+ outputPerMtok: output,
+ cacheReadPerMtok: read,
+ cacheWritePerMtok: write,
+ });
+ },
+);
-it('records the GA DeepSeek V4 Pro tiers without changing its daily default', () => {
- expect(registry?.models.find((m) => m.id === 'deepseek/deepseek-v4-pro'))
- .toMatchObject({ efforts: ['low', 'high', 'max'], defaultEffort: 'high' });
+it("records the GA DeepSeek V4 Pro tiers without changing its daily default", () => {
+ expect(
+ expandedRegistryEntries(registry!).find(
+ (m) => m.id === "deepseek/deepseek-v4-pro",
+ ),
+ ).toMatchObject({ efforts: ["low", "high", "max"], defaultEffort: "high" });
});
diff --git a/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts b/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts
index 38e119945c..ed00417866 100644
--- a/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts
+++ b/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts
@@ -1,3 +1,4 @@
+import { expandedRegistryEntries } from "../modelMetadataLayers.js";
import { describe, expect, it } from "vitest";
import modelRegistryJson from "../../catalog/model-registry.json" with { type: "json" };
@@ -23,7 +24,11 @@ import type {
* maxInputTokens) —— max 为排他上界(`inputTokens >= max` 不命中)。
*/
-const registry = modelRegistryJson as unknown as ModelRegistry;
+const rawRegistry = modelRegistryJson as unknown as ModelRegistry;
+const registry = {
+ ...rawRegistry,
+ models: expandedRegistryEntries(rawRegistry),
+};
function effectiveWindow(
entry: ModelRegistryEntry,
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index 4f44f54717..2a2c5d2f5b 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -6,10 +6,10 @@
* (与生产一致:active-catalog 把 SDK 发现 / codex 注册表 / 网关下发注入后再 buildRegistry)。
*/
-import { describe, it, expect, vi } from 'vitest';
-import { modelRegistryCanonicalJson } from '../modelRegistryCanonical.js';
+import { describe, it, expect, vi } from "vitest";
+import { modelRegistryCanonicalJson } from "../modelRegistryCanonical.js";
-import { BUNDLED_CATALOG } from '../catalog.js';
+import { BUNDLED_CATALOG } from "../catalog.js";
import {
loadCatalog,
loadCatalogWithSource,
@@ -18,7 +18,7 @@ import {
mergeWithBundled,
CATALOG_CFG_PATH,
type CatalogIO,
-} from '../source.js';
+} from "../source.js";
import {
buildRegistry,
providersForAgent,
@@ -29,22 +29,33 @@ import {
chatEligibleSourcesForModel,
effectiveSourceIdForModel,
resolveRoute,
-} from '../registry.js';
-import type { Catalog, CatalogModel, Provider } from '../types.js';
+} from "../registry.js";
+import type { Catalog, CatalogModel, Provider } from "../types.js";
const MINIMAL: Catalog = {
- version: 'test',
+ version: "test",
providers: [
{
- id: 'anthropic',
- name: 'Anthropic',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: { 'claude-code': { upstream: 'https://api.anthropic.com', authStrategy: 'oauth-passthrough' } },
+ id: "anthropic",
+ name: "Anthropic",
+ source: "builtin",
+ agents: ["claude-code"],
+ auth: { method: "oauth" },
+ routing: {
+ "claude-code": {
+ upstream: "https://api.anthropic.com",
+ authStrategy: "oauth-passthrough",
+ },
+ },
models: {
- 'claude-code': [
- { id: 'claude-opus-4-8', name: 'Opus 4.8', contextWindow: 1_000_000, efforts: ['high'], defaultEffort: 'high' },
+ "claude-code": [
+ {
+ id: "claude-opus-4-8",
+ name: "Opus 4.8",
+ contextWindow: 1_000_000,
+ efforts: ["high"],
+ defaultEffort: "high",
+ },
],
},
},
@@ -52,74 +63,100 @@ const MINIMAL: Catalog = {
};
function model(id: string, extra: Partial<CatalogModel> = {}): CatalogModel {
- return { id, name: id, contextWindow: 200_000, efforts: [], defaultEffort: null, ...extra };
+ return {
+ id,
+ name: id,
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ ...extra,
+ };
}
/** 模拟生产形态:动态清单注入后的目录(active-catalog 合并结果的等价物)。 */
function runtimeCatalog(): Catalog {
const clone = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
for (const p of clone.providers) {
- if (p.id === 'anthropic') {
- const models = [model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000 })];
- p.models['claude-code'] = models;
+ if (p.id === "anthropic") {
+ const models = [
+ model("claude-opus-4-8", {
+ name: "Opus 4.8",
+ contextWindow: 1_000_000,
+ }),
+ ];
+ p.models["claude-code"] = models;
p.models.codex = models;
}
- if (p.id === 'openai') {
- p.models.codex = [model('gpt-5.5', { name: 'GPT-5.5' })];
- p.models['claude-code'] = [model('chatgpt/gpt-5.5', { name: 'GPT-5.5' })];
+ if (p.id === "openai") {
+ p.models.codex = [model("gpt-5.5", { name: "GPT-5.5" })];
+ p.models["claude-code"] = [model("chatgpt/gpt-5.5", { name: "GPT-5.5" })];
}
- if (p.id === 'xd') {
- p.models['claude-code'] = [
- model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000 }),
- model('gpt-5.5', { name: 'GPT-5.5' }),
+ if (p.id === "xd") {
+ p.models["claude-code"] = [
+ model("claude-opus-4-8", {
+ name: "Opus 4.8",
+ contextWindow: 1_000_000,
+ }),
+ model("gpt-5.5", { name: "GPT-5.5" }),
];
- p.models.codex = [model('gpt-5.5', { name: 'GPT-5.5' })];
+ p.models.codex = [model("gpt-5.5", { name: "GPT-5.5" })];
}
}
return clone;
}
-describe('resolveCatalogUrl', () => {
- it('prefers explicit url', () => {
- expect(resolveCatalogUrl({ url: 'https://x/y.json', baseUrl: 'https://b' })).toBe('https://x/y.json');
+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 + public catalog API path', () => {
- expect(resolveCatalogUrl({ baseUrl: 'https://model-access.example.com/' })).toBe(
- 'https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=3',
+ 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?registrySchemaVersion=4",
);
});
- it('builds the migration OSS fallback URL', () => {
- expect(resolveFallbackCatalogUrl({ fallbackBaseUrl: 'https://cdn.example.com/base/' })).toBe(
- `https://cdn.example.com/base${CATALOG_CFG_PATH}`,
- );
+ it("builds the migration OSS fallback URL", () => {
+ expect(
+ resolveFallbackCatalogUrl({
+ fallbackBaseUrl: "https://cdn.example.com/base/",
+ }),
+ ).toBe(`https://cdn.example.com/base${CATALOG_CFG_PATH}`);
});
- it('returns null when neither given', () => {
+ it("returns null when neither given", () => {
expect(resolveCatalogUrl({})).toBeNull();
});
});
-describe('mergeWithBundled', () => {
- it('keeps primary providers and fills missing bundled ones by id', () => {
+describe("mergeWithBundled", () => {
+ it("keeps primary providers and fills missing bundled ones by id", () => {
const merged = mergeWithBundled(MINIMAL);
const ids = merged.providers.map((p) => p.id);
- expect(ids).toContain('anthropic');
- expect(ids).toContain('openai');
- expect(ids).toContain('xd');
+ expect(ids).toContain("anthropic");
+ expect(ids).toContain("openai");
+ expect(ids).toContain("xd");
// primary's anthropic wins (only 1 cc model in MINIMAL)
- expect(merged.providers.find((p) => p.id === 'anthropic')!.models['claude-code']!.length).toBe(1);
+ expect(
+ merged.providers.find((p) => p.id === "anthropic")!.models["claude-code"]!
+ .length,
+ ).toBe(1);
});
- it('keeps a newer bundled Registry without replacing the independent xAI fallback provider', () => {
+ it("keeps a newer bundled Registry without replacing the independent xAI fallback provider", () => {
const bundledRegistry = BUNDLED_CATALOG.modelRegistry;
- const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');
- if (!bundledRegistry) throw new Error('missing bundled modelRegistry');
- if (!bundledXai) throw new Error('missing bundled xAI provider');
+ const bundledXai = BUNDLED_CATALOG.providers.find(
+ (provider) => provider.id === "xai",
+ );
+ if (!bundledRegistry) throw new Error("missing bundled modelRegistry");
+ if (!bundledXai) throw new Error("missing bundled xAI provider");
const staleRegistry = {
...bundledRegistry,
- updatedAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: "2026-01-01T00:00:00.000Z",
models: [bundledRegistry.models[0]!],
};
- const staleXai = { ...bundledXai, name: 'STALE-XAI' };
+ const staleXai = { ...bundledXai, name: "STALE-XAI" };
const merged = mergeWithBundled({
...MINIMAL,
@@ -128,21 +165,27 @@ describe('mergeWithBundled', () => {
});
expect(merged.modelRegistry).toBe(bundledRegistry);
- expect(merged.modelRegistry?.models.length).toBeGreaterThan(staleRegistry.models.length);
- expect(merged.providers.find((provider) => provider.id === 'xai')?.name).toBe('STALE-XAI');
+ expect(merged.modelRegistry?.models.length).toBeGreaterThan(
+ staleRegistry.models.length,
+ );
+ expect(
+ merged.providers.find((provider) => provider.id === "xai")?.name,
+ ).toBe("STALE-XAI");
});
- it('uses a newer primary modelRegistry as one complete snapshot, including retirements', () => {
+ it("uses a newer primary modelRegistry as one complete snapshot, including retirements", () => {
const bundledRegistry = BUNDLED_CATALOG.modelRegistry;
- const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');
- if (!bundledRegistry) throw new Error('missing bundled modelRegistry');
- if (!bundledXai) throw new Error('missing bundled xAI provider');
+ const bundledXai = BUNDLED_CATALOG.providers.find(
+ (provider) => provider.id === "xai",
+ );
+ if (!bundledRegistry) throw new Error("missing bundled modelRegistry");
+ if (!bundledXai) throw new Error("missing bundled xAI provider");
const newerRegistry = {
...bundledRegistry,
- updatedAt: '2099-01-01T00:00:00.000Z',
- models: [{ ...bundledRegistry.models[0]!, status: 'retired' as const }],
+ updatedAt: "2099-01-01T00:00:00.000Z",
+ models: [{ ...bundledRegistry.models[0]!, status: "retired" as const }],
};
- const newerXai = { ...bundledXai, name: 'NEWER-XAI' };
+ const newerXai = { ...bundledXai, name: "NEWER-XAI" };
const merged = mergeWithBundled({
...MINIMAL,
@@ -152,150 +195,181 @@ describe('mergeWithBundled', () => {
expect(merged.modelRegistry).toBe(newerRegistry);
expect(merged.modelRegistry?.models).toHaveLength(1);
- expect(merged.modelRegistry?.models[0]?.status).toBe('retired');
- const mergedXai = merged.providers.find((provider) => provider.id === 'xai');
+ expect(merged.modelRegistry?.models[0]?.status).toBe("retired");
+ const mergedXai = merged.providers.find(
+ (provider) => provider.id === "xai",
+ );
expect(mergedXai).toMatchObject({
...newerXai,
- agents: expect.arrayContaining(['claude-code', 'codex', 'pi']),
+ agents: expect.arrayContaining(["claude-code", "codex", "pi"]),
routing: expect.objectContaining({ pi: bundledXai.routing.pi }),
models: expect.objectContaining({ pi: bundledXai.models.pi }),
});
});
- it('orders result by bundled provider order (v2 远端只带 xai 时不得窜位)', () => {
+ it("orders result by bundled provider order (v2 远端只带 xai 时不得窜位)", () => {
const v2Remote: Catalog = {
- version: '2',
- providers: [JSON.parse(JSON.stringify(BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')))],
+ version: "2",
+ providers: [
+ JSON.parse(
+ JSON.stringify(BUNDLED_CATALOG.providers.find((p) => p.id === "xai")),
+ ),
+ ],
};
const merged = mergeWithBundled(v2Remote);
- expect(merged.providers.map((p) => p.id)).toEqual(['anthropic', 'openai', 'xai', 'xd', 'gemini']);
+ expect(merged.providers.map((p) => p.id)).toEqual([
+ "anthropic",
+ "openai",
+ "xai",
+ "xd",
+ "gemini",
+ ]);
// 远端独有的新供应商追加在 bundled 之后。
const withExtra: Catalog = {
- version: '2',
+ version: "2",
providers: [
...v2Remote.providers,
- { ...MINIMAL.providers[0], id: 'newvendor', name: 'NewVendor' },
+ { ...MINIMAL.providers[0], id: "newvendor", name: "NewVendor" },
],
};
expect(mergeWithBundled(withExtra).providers.map((p) => p.id)).toEqual([
- 'anthropic', 'openai', 'xai', 'xd', 'gemini', 'newvendor',
+ "anthropic",
+ "openai",
+ "xai",
+ "xd",
+ "gemini",
+ "newvendor",
]);
});
- it('backfills the bundled SuperGrok Pi runtime when a legacy v2 xAI block masks it', () => {
+ it("backfills the bundled SuperGrok Pi runtime when a legacy v2 xAI block masks it", () => {
const bundledXai = structuredClone(
- BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
);
const legacyXai = structuredClone(bundledXai);
- legacyXai.agents = legacyXai.agents.filter((agent) => agent !== 'pi');
+ legacyXai.agents = legacyXai.agents.filter((agent) => agent !== "pi");
delete legacyXai.routing.pi;
delete legacyXai.models.pi;
- const merged = mergeWithBundled({ version: '2', providers: [legacyXai] });
- const xai = merged.providers.find((provider) => provider.id === 'xai');
+ const merged = mergeWithBundled({ version: "2", providers: [legacyXai] });
+ const xai = merged.providers.find((provider) => provider.id === "xai");
- expect(xai?.agents).toContain('pi');
+ expect(xai?.agents).toContain("pi");
expect(xai?.routing.pi).toEqual(bundledXai.routing.pi);
expect(xai?.models.pi).toEqual(bundledXai.models.pi);
});
- it('does not invent a SuperGrok Pi runtime for current or differently routed xAI providers', () => {
+ it("does not invent a SuperGrok Pi runtime for current or differently routed xAI providers", () => {
const bundledXai = structuredClone(
- BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
);
const withoutPi = structuredClone(bundledXai);
- withoutPi.agents = withoutPi.agents.filter((agent) => agent !== 'pi');
+ withoutPi.agents = withoutPi.agents.filter((agent) => agent !== "pi");
delete withoutPi.routing.pi;
delete withoutPi.models.pi;
const current = mergeWithBundled({
version: BUNDLED_CATALOG.version,
providers: [withoutPi],
- }).providers.find((provider) => provider.id === 'xai');
- expect(current?.agents).not.toContain('pi');
+ }).providers.find((provider) => provider.id === "xai");
+ expect(current?.agents).not.toContain("pi");
expect(current?.routing.pi).toBeUndefined();
expect(current?.models.pi).toBeUndefined();
const rerouted = mergeWithBundled({
- version: '2',
- providers: [{
- ...withoutPi,
- routing: {
- ...withoutPi.routing,
- codex: {
- ...withoutPi.routing.codex!,
- upstream: 'https://different.example.test/v1',
+ version: "2",
+ providers: [
+ {
+ ...withoutPi,
+ routing: {
+ ...withoutPi.routing,
+ codex: {
+ ...withoutPi.routing.codex!,
+ upstream: "https://different.example.test/v1",
+ },
},
},
- }],
- }).providers.find((provider) => provider.id === 'xai');
- expect(rerouted?.agents).not.toContain('pi');
+ ],
+ }).providers.find((provider) => provider.id === "xai");
+ expect(rerouted?.agents).not.toContain("pi");
expect(rerouted?.routing.pi).toBeUndefined();
expect(rerouted?.models.pi).toBeUndefined();
});
it.each([
- { label: 'api access', access: { kind: 'api' } as const },
- { label: 'managed access', access: { kind: 'managed' } as const },
- { label: 'different subscription', access: { kind: 'subscription', product: 'OtherGrok' } as const },
- ])('does not backfill SuperGrok Pi for explicit $label', ({ access }) => {
+ { label: "api access", access: { kind: "api" } as const },
+ { label: "managed access", access: { kind: "managed" } as const },
+ {
+ label: "different subscription",
+ access: { kind: "subscription", product: "OtherGrok" } as const,
+ },
+ ])("does not backfill SuperGrok Pi for explicit $label", ({ access }) => {
const bundledXai = structuredClone(
- BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
);
const legacyXai = structuredClone(bundledXai);
legacyXai.access = access;
- legacyXai.agents = legacyXai.agents.filter((agent) => agent !== 'pi');
+ legacyXai.agents = legacyXai.agents.filter((agent) => agent !== "pi");
delete legacyXai.routing.pi;
delete legacyXai.models.pi;
- const merged = mergeWithBundled({ version: '2', providers: [legacyXai] });
- const xai = merged.providers.find((provider) => provider.id === 'xai');
+ const merged = mergeWithBundled({ version: "2", providers: [legacyXai] });
+ const xai = merged.providers.find((provider) => provider.id === "xai");
expect(xai?.access).toEqual(access);
- expect(xai?.agents).not.toContain('pi');
+ expect(xai?.agents).not.toContain("pi");
expect(xai?.routing.pi).toBeUndefined();
expect(xai?.models.pi).toBeUndefined();
});
- it('keeps the SuperGrok Pi backfill when an old catalog explicitly repeats the same access', () => {
+ it("keeps the SuperGrok Pi backfill when an old catalog explicitly repeats the same access", () => {
const bundledXai = structuredClone(
- BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
);
const legacyXai = structuredClone(bundledXai);
- legacyXai.access = { kind: 'subscription', product: 'SuperGrok' };
- legacyXai.agents = legacyXai.agents.filter((agent) => agent !== 'pi');
+ legacyXai.access = { kind: "subscription", product: "SuperGrok" };
+ legacyXai.agents = legacyXai.agents.filter((agent) => agent !== "pi");
delete legacyXai.routing.pi;
delete legacyXai.models.pi;
- const merged = mergeWithBundled({ version: '2', providers: [legacyXai] });
- const xai = merged.providers.find((provider) => provider.id === 'xai');
+ const merged = mergeWithBundled({ version: "2", providers: [legacyXai] });
+ const xai = merged.providers.find((provider) => provider.id === "xai");
- expect(xai?.agents).toContain('pi');
+ expect(xai?.agents).toContain("pi");
expect(xai?.routing.pi).toEqual(bundledXai.routing.pi);
expect(xai?.models.pi).toEqual(bundledXai.models.pi);
});
- it('backfills access for an old primary catalog without mutating it', () => {
+ it("backfills access for an old primary catalog without mutating it", () => {
const merged = mergeWithBundled(MINIMAL);
expect(MINIMAL.providers[0].access).toBeUndefined();
- expect(merged.providers.find((p) => p.id === 'anthropic')?.access).toEqual({
- kind: 'subscription',
- product: 'Claude.ai',
+ expect(merged.providers.find((p) => p.id === "anthropic")?.access).toEqual({
+ kind: "subscription",
+ product: "Claude.ai",
});
});
- it('preserves access explicitly supplied by the primary catalog', () => {
+ it("preserves access explicitly supplied by the primary catalog", () => {
const primary: Catalog = {
...MINIMAL,
- providers: MINIMAL.providers.map((p) => ({ ...p, access: { kind: 'api' } })),
+ providers: MINIMAL.providers.map((p) => ({
+ ...p,
+ access: { kind: "api" },
+ })),
};
- expect(mergeWithBundled(primary).providers.find((p) => p.id === 'anthropic')?.access).toEqual({ kind: 'api' });
+ expect(
+ mergeWithBundled(primary).providers.find((p) => p.id === "anthropic")
+ ?.access,
+ ).toEqual({ kind: "api" });
});
- it('同 updatedAt 异 Registry 内容在首次启动合并时保留 bundled 不可变快照', () => {
+ it("同 updatedAt 异 Registry 内容在首次启动合并时保留 bundled 不可变快照", () => {
const bundledRegistry = structuredClone(BUNDLED_CATALOG.modelRegistry!);
const mutatedRegistry = structuredClone(bundledRegistry);
- mutatedRegistry.models[0] = { ...mutatedRegistry.models[0]!, name: 'Mutated in place' };
+ mutatedRegistry.models[0] = {
+ ...mutatedRegistry.models[0]!,
+ name: "Mutated in place",
+ };
const primary: Catalog = { ...MINIMAL, modelRegistry: mutatedRegistry };
const merged = mergeWithBundled(primary);
@@ -304,15 +378,17 @@ describe('mergeWithBundled', () => {
);
});
- it('首次启动合并把等价时区表示视为同一 Registry revision', () => {
+ it("首次启动合并把等价时区表示视为同一 Registry revision", () => {
const bundledRegistry = structuredClone(BUNDLED_CATALOG.modelRegistry!);
- const shifted = new Date(Date.parse(bundledRegistry.updatedAt) + 8 * 60 * 60 * 1_000)
+ const shifted = new Date(
+ Date.parse(bundledRegistry.updatedAt) + 8 * 60 * 60 * 1_000,
+ )
.toISOString()
- .replace('Z', '+08:00');
+ .replace("Z", "+08:00");
const remoteXai = structuredClone(
- BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
);
- remoteXai.name = 'REMOTE-XAI';
+ remoteXai.name = "REMOTE-XAI";
const primary: Catalog = {
...MINIMAL,
providers: [...MINIMAL.providers, remoteXai],
@@ -321,61 +397,75 @@ describe('mergeWithBundled', () => {
const merged = mergeWithBundled(primary);
expect(merged.modelRegistry?.updatedAt).toBe(shifted);
- expect(merged.providers.find((provider) => provider.id === 'xai')?.name).toBe('REMOTE-XAI');
+ expect(
+ merged.providers.find((provider) => provider.id === "xai")?.name,
+ ).toBe("REMOTE-XAI");
});
- it('旧远端未声明 xAI 媒体能力时继承 bundled;显式空清单仍可停用', () => {
- const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
+ it("旧远端未声明 xAI 媒体能力时继承 bundled;显式空清单仍可停用", () => {
+ const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === "xai")!;
const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
delete oldRemoteXai.imageModels;
delete oldRemoteXai.videoModels;
- const inherited = mergeWithBundled({ version: '2', providers: [oldRemoteXai] });
- expect(inherited.providers.find((p) => p.id === 'xai')?.imageModels)
- .toEqual(bundledXai.imageModels);
- expect(inherited.providers.find((p) => p.id === 'xai')?.videoModels)
- .toEqual(bundledXai.videoModels);
+ const inherited = mergeWithBundled({
+ version: "2",
+ providers: [oldRemoteXai],
+ });
+ expect(
+ inherited.providers.find((p) => p.id === "xai")?.imageModels,
+ ).toEqual(bundledXai.imageModels);
+ expect(
+ inherited.providers.find((p) => p.id === "xai")?.videoModels,
+ ).toEqual(bundledXai.videoModels);
const explicitlyDisabled = mergeWithBundled({
- version: '2',
+ version: "2",
providers: [{ ...oldRemoteXai, imageModels: [], videoModels: [] }],
});
- expect(explicitlyDisabled.providers.find((p) => p.id === 'xai')?.imageModels).toEqual([]);
- expect(explicitlyDisabled.providers.find((p) => p.id === 'xai')?.videoModels).toEqual([]);
+ expect(
+ explicitlyDisabled.providers.find((p) => p.id === "xai")?.imageModels,
+ ).toEqual([]);
+ expect(
+ explicitlyDisabled.providers.find((p) => p.id === "xai")?.videoModels,
+ ).toEqual([]);
});
- it('旧远端未声明向量清单时继承 bundled;显式空清单仍是停用语义', () => {
+ it("旧远端未声明向量清单时继承 bundled;显式空清单仍是停用语义", () => {
// 与 xai 图像清单同一个道理(PR #1707 review):向量清单是客户端新增的 bundled
// 元数据,远端 / 本地目录里同 id 的 xd 可能还是升级前的结构。primary 整体优先
// 会让旧结构把新字段整段遮掉 → 目录派生空清单 → 设置页"无可用模型"、所有
// embed_text 直接 NO_CANDIDATE,能力等于没上线。
- const bundledXd = BUNDLED_CATALOG.providers.find((p) => p.id === 'xd')!;
+ const bundledXd = BUNDLED_CATALOG.providers.find((p) => p.id === "xd")!;
const oldRemoteXd = JSON.parse(JSON.stringify(bundledXd)) as Provider;
delete oldRemoteXd.embeddingModels;
delete oldRemoteXd.embeddingDefaults;
- const inherited = mergeWithBundled({ version: '2', providers: [oldRemoteXd] });
- const inheritedXd = inherited.providers.find((p) => p.id === 'xd');
+ const inherited = mergeWithBundled({
+ version: "2",
+ providers: [oldRemoteXd],
+ });
+ const inheritedXd = inherited.providers.find((p) => p.id === "xd");
expect(inheritedXd?.embeddingModels).toEqual(bundledXd.embeddingModels);
expect(inheritedXd?.embeddingDefaults).toEqual(bundledXd.embeddingDefaults);
// 显式 `[]` = "这个供应商不提供向量",不能被 bundled 顶回来。
const explicitlyDisabled = mergeWithBundled({
- version: '2',
+ version: "2",
providers: [{ ...oldRemoteXd, embeddingModels: [] }],
});
expect(
- explicitlyDisabled.providers.find((p) => p.id === 'xd')?.embeddingModels,
+ explicitlyDisabled.providers.find((p) => p.id === "xd")?.embeddingModels,
).toEqual([]);
});
- it('旧远端改变鉴权或路由形状时不继承 bundled 图像能力', () => {
- const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
+ it("旧远端改变鉴权或路由形状时不继承 bundled 图像能力", () => {
+ const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === "xai")!;
const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
delete oldRemoteXai.imageModels;
delete oldRemoteXai.videoModels;
const apiKeyXai: Provider = {
...oldRemoteXai,
- auth: { method: 'apiKey' },
+ auth: { method: "apiKey" },
};
const alternateRouteXai: Provider = {
...oldRemoteXai,
@@ -383,85 +473,90 @@ describe('mergeWithBundled', () => {
...oldRemoteXai.routing,
codex: {
...oldRemoteXai.routing.codex!,
- upstream: 'https://oauth-proxy.example.test',
+ upstream: "https://oauth-proxy.example.test",
},
},
};
expect(
- mergeWithBundled({ version: '2', providers: [apiKeyXai] }).providers.find(
- (p) => p.id === 'xai',
+ mergeWithBundled({ version: "2", providers: [apiKeyXai] }).providers.find(
+ (p) => p.id === "xai",
)?.imageModels,
).toBeUndefined();
expect(
- mergeWithBundled({ version: '2', providers: [apiKeyXai] }).providers.find(
- (p) => p.id === 'xai',
+ mergeWithBundled({ version: "2", providers: [apiKeyXai] }).providers.find(
+ (p) => p.id === "xai",
)?.videoModels,
).toBeUndefined();
expect(
- mergeWithBundled({ version: '2', providers: [alternateRouteXai] }).providers.find(
- (p) => p.id === 'xai',
- )?.imageModels,
+ mergeWithBundled({
+ version: "2",
+ providers: [alternateRouteXai],
+ }).providers.find((p) => p.id === "xai")?.imageModels,
).toBeUndefined();
expect(
- mergeWithBundled({ version: '2', providers: [alternateRouteXai] }).providers.find(
- (p) => p.id === 'xai',
- )?.videoModels,
+ mergeWithBundled({
+ version: "2",
+ providers: [alternateRouteXai],
+ }).providers.find((p) => p.id === "xai")?.videoModels,
).toBeUndefined();
});
- it('旧 xAI 条目仅在 access 缺省或仍为同一订阅时继承 bundled 图像能力', () => {
- const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
+ it("旧 xAI 条目仅在 access 缺省或仍为同一订阅时继承 bundled 图像能力", () => {
+ const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === "xai")!;
const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
delete oldRemoteXai.imageModels;
delete oldRemoteXai.videoModels;
for (const access of [
- { kind: 'api' as const },
- { kind: 'managed' as const },
- { kind: 'subscription' as const, product: 'Another subscription' },
+ { kind: "api" as const },
+ { kind: "managed" as const },
+ { kind: "subscription" as const, product: "Another subscription" },
]) {
expect(
mergeWithBundled({
- version: '2',
+ version: "2",
providers: [{ ...oldRemoteXai, access }],
- }).providers.find((p) => p.id === 'xai')?.imageModels,
+ }).providers.find((p) => p.id === "xai")?.imageModels,
).toBeUndefined();
expect(
mergeWithBundled({
- version: '2',
+ version: "2",
providers: [{ ...oldRemoteXai, access }],
- }).providers.find((p) => p.id === 'xai')?.videoModels,
+ }).providers.find((p) => p.id === "xai")?.videoModels,
).toBeUndefined();
}
expect(
mergeWithBundled({
- version: '2',
+ version: "2",
providers: [{ ...oldRemoteXai, access: bundledXai.access }],
- }).providers.find((p) => p.id === 'xai')?.imageModels,
+ }).providers.find((p) => p.id === "xai")?.imageModels,
).toEqual(bundledXai.imageModels);
expect(
mergeWithBundled({
- version: '2',
+ version: "2",
providers: [{ ...oldRemoteXai, access: bundledXai.access }],
- }).providers.find((p) => p.id === 'xai')?.videoModels,
+ }).providers.find((p) => p.id === "xai")?.videoModels,
).toEqual(bundledXai.videoModels);
});
- it('非 xAI 远端条目缺少媒体字段时不从 bundled 恢复已撤下能力', () => {
- const bundledOpenai = BUNDLED_CATALOG.providers.find((p) => p.id === 'openai')!;
+ it("非 xAI 远端条目缺少媒体字段时不从 bundled 恢复已撤下能力", () => {
+ const bundledOpenai = BUNDLED_CATALOG.providers.find(
+ (p) => p.id === "openai",
+ )!;
const remoteOpenai = JSON.parse(JSON.stringify(bundledOpenai)) as Provider;
delete remoteOpenai.imageModels;
expect(
- mergeWithBundled({ version: '2', providers: [remoteOpenai] }).providers.find(
- (p) => p.id === 'openai',
- )?.imageModels,
+ mergeWithBundled({
+ version: "2",
+ providers: [remoteOpenai],
+ }).providers.find((p) => p.id === "openai")?.imageModels,
).toBeUndefined();
});
- it('旧目录在官方 Codex 路由未声明 custom tool 能力时继承 bundled 能力', () => {
+ it("旧目录在官方 Codex 路由未声明 custom tool 能力时继承 bundled 能力", () => {
const oldProviders = BUNDLED_CATALOG.providers.map((provider) => {
const oldProvider = structuredClone(provider);
if (oldProvider.routing.codex) {
@@ -470,32 +565,42 @@ describe('mergeWithBundled', () => {
return oldProvider;
});
- const merged = mergeWithBundled({ version: '2', providers: oldProviders });
+ const merged = mergeWithBundled({ version: "2", providers: oldProviders });
- expect(merged.providers.find((provider) => provider.id === 'openai')
- ?.routing.codex?.supportsResponsesCustomTools).toBe(true);
- expect(merged.providers.find((provider) => provider.id === 'xai')
- ?.routing.codex?.supportsResponsesCustomTools).toBe(false);
- expect(merged.providers.find((provider) => provider.id === 'xd')
- ?.routing.codex?.supportsResponsesCustomTools).toBe(false);
+ expect(
+ merged.providers.find((provider) => provider.id === "openai")?.routing
+ .codex?.supportsResponsesCustomTools,
+ ).toBe(true);
+ expect(
+ merged.providers.find((provider) => provider.id === "xai")?.routing.codex
+ ?.supportsResponsesCustomTools,
+ ).toBe(false);
+ expect(
+ merged.providers.find((provider) => provider.id === "xd")?.routing.codex
+ ?.supportsResponsesCustomTools,
+ ).toBe(false);
const explicitOpenai = structuredClone(
- oldProviders.find((provider) => provider.id === 'openai')!,
+ oldProviders.find((provider) => provider.id === "openai")!,
);
explicitOpenai.routing.codex!.supportsResponsesCustomTools = false;
- expect(mergeWithBundled({ version: '2', providers: [explicitOpenai] })
- .providers.find((provider) => provider.id === 'openai')
- ?.routing.codex?.supportsResponsesCustomTools).toBe(false);
+ expect(
+ mergeWithBundled({
+ version: "2",
+ providers: [explicitOpenai],
+ }).providers.find((provider) => provider.id === "openai")?.routing.codex
+ ?.supportsResponsesCustomTools,
+ ).toBe(false);
});
- it('不为改变鉴权或 upstream 的同名 Provider 猜测 custom tool 能力', () => {
+ it("不为改变鉴权或 upstream 的同名 Provider 猜测 custom tool 能力", () => {
const bundledOpenai = structuredClone(
- BUNDLED_CATALOG.providers.find((provider) => provider.id === 'openai')!,
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === "openai")!,
);
delete bundledOpenai.routing.codex!.supportsResponsesCustomTools;
const apiKeyOpenai: Provider = {
...bundledOpenai,
- auth: { method: 'apiKey' },
+ auth: { method: "apiKey" },
};
const reroutedOpenai: Provider = {
...bundledOpenai,
@@ -503,29 +608,37 @@ describe('mergeWithBundled', () => {
...bundledOpenai.routing,
codex: {
...bundledOpenai.routing.codex!,
- upstream: 'https://responses.example.test/v1',
+ upstream: "https://responses.example.test/v1",
},
},
};
- expect(mergeWithBundled({ version: '2', providers: [apiKeyOpenai] })
- .providers.find((provider) => provider.id === 'openai')
- ?.routing.codex?.supportsResponsesCustomTools).toBeUndefined();
- expect(mergeWithBundled({ version: '2', providers: [reroutedOpenai] })
- .providers.find((provider) => provider.id === 'openai')
- ?.routing.codex?.supportsResponsesCustomTools).toBeUndefined();
+ expect(
+ mergeWithBundled({
+ version: "2",
+ providers: [apiKeyOpenai],
+ }).providers.find((provider) => provider.id === "openai")?.routing.codex
+ ?.supportsResponsesCustomTools,
+ ).toBeUndefined();
+ expect(
+ mergeWithBundled({
+ version: "2",
+ providers: [reroutedOpenai],
+ }).providers.find((provider) => provider.id === "openai")?.routing.codex
+ ?.supportsResponsesCustomTools,
+ ).toBeUndefined();
});
- it('does not infer bundled billing when a same-id primary changes auth or upstream', () => {
+ it("does not infer bundled billing when a same-id primary changes auth or upstream", () => {
const apiKeyPrimary: Catalog = {
...MINIMAL,
providers: MINIMAL.providers.map((p) => ({
...p,
- auth: { method: 'apiKey' as const },
+ auth: { method: "apiKey" as const },
routing: {
- 'claude-code': {
- ...p.routing['claude-code']!,
- authStrategy: 'api-key-header' as const,
+ "claude-code": {
+ ...p.routing["claude-code"]!,
+ authStrategy: "api-key-header" as const,
},
},
})),
@@ -535,101 +648,118 @@ describe('mergeWithBundled', () => {
providers: MINIMAL.providers.map((p) => ({
...p,
routing: {
- 'claude-code': {
- ...p.routing['claude-code']!,
- upstream: 'https://oauth-proxy.example.test',
+ "claude-code": {
+ ...p.routing["claude-code"]!,
+ upstream: "https://oauth-proxy.example.test",
},
},
})),
};
- const apiKeyMerged = mergeWithBundled(apiKeyPrimary).providers.find((p) => p.id === 'anthropic');
- const altMerged = mergeWithBundled(alternateOAuthPrimary).providers.find((p) => p.id === 'anthropic');
+ const apiKeyMerged = mergeWithBundled(apiKeyPrimary).providers.find(
+ (p) => p.id === "anthropic",
+ );
+ const altMerged = mergeWithBundled(alternateOAuthPrimary).providers.find(
+ (p) => p.id === "anthropic",
+ );
expect(apiKeyMerged?.access).toBeUndefined();
expect(altMerged?.access).toBeUndefined();
});
});
-describe('loadCatalog', () => {
- it('reports whether local, remote, or bundled supplied the snapshot', async () => {
+describe("loadCatalog", () => {
+ it("reports whether local, remote, or bundled supplied the snapshot", async () => {
const local = await loadCatalogWithSource(
- { localPath: '/repo/providers.json' },
+ { localPath: "/repo/providers.json" },
{ readFile: vi.fn(async () => JSON.stringify(MINIMAL)) },
);
const remote = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json' },
+ { url: "https://catalog.example.test/providers.json" },
{ fetchText: vi.fn(async () => JSON.stringify(MINIMAL)) },
);
const bundled = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json' },
- { fetchText: vi.fn(async () => { throw new Error('network down'); }) },
+ { url: "https://catalog.example.test/providers.json" },
+ {
+ fetchText: vi.fn(async () => {
+ throw new Error("network down");
+ }),
+ },
);
expect(local).toMatchObject({
- source: 'local',
- capabilityEvidence: 'current',
- unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
- catalog: { version: 'test' },
- authorityCatalog: { version: 'test' },
+ source: "local",
+ capabilityEvidence: "current",
+ unverifiedXdMediaKinds: ["image", "video", "embedding"],
+ catalog: { version: "test" },
+ authorityCatalog: { version: "test" },
});
expect(remote).toMatchObject({
- source: 'remote',
- capabilityEvidence: 'current',
- unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
- catalog: { version: 'test' },
- authorityCatalog: { version: 'test' },
+ source: "remote",
+ capabilityEvidence: "current",
+ unverifiedXdMediaKinds: ["image", "video", "embedding"],
+ catalog: { version: "test" },
+ authorityCatalog: { version: "test" },
});
expect(bundled).toEqual({
- source: 'bundled',
- capabilityEvidence: 'fallback',
- unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ source: "bundled",
+ capabilityEvidence: "fallback",
+ unverifiedXdMediaKinds: ["image", "video", "embedding"],
catalog: BUNDLED_CATALOG,
authorityCatalog: null,
});
});
- it('tracks only XD media fields inherited from bundled in a current snapshot', async () => {
- const bundledXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');
- if (!bundledXd) throw new Error('missing bundled XD provider');
+ it("tracks only XD media fields inherited from bundled in a current snapshot", async () => {
+ const bundledXd = BUNDLED_CATALOG.providers.find(
+ (provider) => provider.id === "xd",
+ );
+ if (!bundledXd) throw new Error("missing bundled XD provider");
const oldXd = structuredClone(bundledXd);
delete oldXd.embeddingModels;
delete oldXd.embeddingDefaults;
const inherited = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json' },
+ { url: "https://catalog.example.test/providers.json" },
{
fetchText: vi.fn(async () =>
- JSON.stringify({ version: '2', providers: [oldXd] }),
+ JSON.stringify({ version: "2", providers: [oldXd] }),
),
},
);
- expect(inherited.capabilityEvidence).toBe('current');
- expect(inherited.unverifiedXdMediaKinds).toEqual(['embedding']);
+ expect(inherited.capabilityEvidence).toBe("current");
+ expect(inherited.unverifiedXdMediaKinds).toEqual(["embedding"]);
expect(
- inherited.catalog.providers.find((provider) => provider.id === 'xd')?.embeddingModels,
+ inherited.catalog.providers.find((provider) => provider.id === "xd")
+ ?.embeddingModels,
).toEqual(bundledXd.embeddingModels);
const explicitlyDisabled = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json' },
+ { url: "https://catalog.example.test/providers.json" },
{
fetchText: vi.fn(async () =>
- JSON.stringify({ version: '2', providers: [{ ...oldXd, embeddingModels: [] }] }),
+ JSON.stringify({
+ version: "2",
+ providers: [{ ...oldXd, embeddingModels: [] }],
+ }),
),
},
);
expect(explicitlyDisabled.unverifiedXdMediaKinds).toEqual([]);
expect(
- explicitlyDisabled.catalog.providers.find((provider) => provider.id === 'xd')
- ?.embeddingModels,
+ explicitlyDisabled.catalog.providers.find(
+ (provider) => provider.id === "xd",
+ )?.embeddingModels,
).toEqual([]);
});
- it('only backfills Pi metadata for proven legacy snapshots across local, remote, and cache', async () => {
- const bundledPreset = BUNDLED_CATALOG.presets?.find((preset) => preset.id === 'deepseek');
- if (!bundledPreset) throw new Error('missing bundled DeepSeek preset');
+ it("only backfills Pi metadata for proven legacy snapshots across local, remote, and cache", async () => {
+ const bundledPreset = BUNDLED_CATALOG.presets?.find(
+ (preset) => preset.id === "deepseek",
+ );
+ if (!bundledPreset) throw new Error("missing bundled DeepSeek preset");
const { pi: _missing, ...legacyRuntimes } = bundledPreset.runtimes;
const legacy = JSON.stringify({
- version: '2',
+ version: "2",
providers: MINIMAL.providers,
presets: [{ ...bundledPreset, runtimes: legacyRuntimes }],
});
@@ -639,36 +769,44 @@ describe('loadCatalog', () => {
presets: [{ ...bundledPreset, runtimes: legacyRuntimes }],
});
const local = await loadCatalogWithSource(
- { localPath: '/repo/providers.json' },
+ { localPath: "/repo/providers.json" },
{ readFile: vi.fn(async () => legacy) },
);
const remote = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json' },
+ { url: "https://catalog.example.test/providers.json" },
{ fetchText: vi.fn(async () => legacy) },
);
const cache = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json', remoteBudgetMs: 0 },
+ { url: "https://catalog.example.test/providers.json", remoteBudgetMs: 0 },
{ readCache: vi.fn(async () => legacy) },
);
for (const loaded of [local, remote, cache]) {
- expect(loaded.catalog.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi)
- .toEqual(bundledPreset.runtimes.pi);
expect(
- loaded.authorityCatalog?.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi,
+ loaded.catalog.presets?.find((preset) => preset.id === "deepseek")
+ ?.runtimes.pi,
+ ).toEqual(bundledPreset.runtimes.pi);
+ expect(
+ loaded.authorityCatalog?.presets?.find(
+ (preset) => preset.id === "deepseek",
+ )?.runtimes.pi,
).toBeUndefined();
}
const currentLoaded = await loadCatalogWithSource(
- { url: 'https://catalog.example.test/providers.json' },
+ { url: "https://catalog.example.test/providers.json" },
{ fetchText: vi.fn(async () => current) },
);
- expect(currentLoaded.catalog.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi)
- .toBeUndefined();
+ expect(
+ currentLoaded.catalog.presets?.find((preset) => preset.id === "deepseek")
+ ?.runtimes.pi,
+ ).toBeUndefined();
});
- it('persists a valid remote snapshot and uses its source-scoped LKG after failure', async () => {
- const url = 'https://catalog.example.test/providers.json';
- const writeCache = vi.fn(async (_scope: string, _text: string) => undefined);
+ it("persists a valid remote snapshot and uses its source-scoped LKG after failure", async () => {
+ const url = "https://catalog.example.test/providers.json";
+ const writeCache = vi.fn(
+ async (_scope: string, _text: string) => undefined,
+ );
const remote = await loadCatalogWithSource(
{ url },
{
@@ -676,53 +814,64 @@ describe('loadCatalog', () => {
writeCache,
},
);
- expect(remote.source).toBe('remote');
+ expect(remote.source).toBe("remote");
expect(writeCache).toHaveBeenCalledWith(url, JSON.stringify(MINIMAL));
const cached = await loadCatalogWithSource(
{ url },
{
fetchText: vi.fn(async () => {
- throw new Error('offline');
+ throw new Error("offline");
}),
readCache: vi.fn(async (scope) =>
scope === url ? JSON.stringify(MINIMAL) : null,
),
},
);
- expect(cached).toMatchObject({ source: 'cache', catalog: { version: 'test' } });
- expect(cached.capabilityEvidence).toBe('fallback');
+ expect(cached).toMatchObject({
+ source: "cache",
+ catalog: { version: "test" },
+ });
+ expect(cached.capabilityEvidence).toBe("fallback");
});
- it('keeps a newer cached modelRegistry when a valid remote Catalog is stale', async () => {
- const url = 'https://catalog.example.test/providers.json';
- const newerUpdatedAt = '2099-08-02T00:00:00.000Z';
+ it("keeps a newer cached modelRegistry when a valid remote Catalog is stale", async () => {
+ const url = "https://catalog.example.test/providers.json";
+ const newerUpdatedAt = "2099-08-02T00:00:00.000Z";
const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
- const xai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');
- if (!xai) throw new Error('missing bundled xAI provider');
+ const xai = BUNDLED_CATALOG.providers.find(
+ (provider) => provider.id === "xai",
+ );
+ if (!xai) throw new Error("missing bundled xAI provider");
const older: Catalog = {
...MINIMAL,
- providers: [...MINIMAL.providers, { ...xai, name: 'STALE-XAI' }],
+ providers: [...MINIMAL.providers, { ...xai, name: "STALE-XAI" }],
modelRegistry: {
...registry,
- updatedAt: '2026-07-30T00:00:00.000Z',
- models: registry.models.map((entry: { id: string }) => (
- entry.id === 'openai/gpt-5.6-sol' ? { ...entry, name: 'STALE' } : entry
- )),
+ updatedAt: "2026-07-30T00:00:00.000Z",
+ models: registry.models.map((entry: { id: string }) =>
+ entry.id === "openai/gpt-5.6-sol"
+ ? { ...entry, name: "STALE" }
+ : entry,
+ ),
},
};
const newer: Catalog = {
...MINIMAL,
- providers: [...MINIMAL.providers, { ...xai, name: 'NEWER-LKG-XAI' }],
+ providers: [...MINIMAL.providers, { ...xai, name: "NEWER-LKG-XAI" }],
modelRegistry: {
...registry,
updatedAt: newerUpdatedAt,
- models: registry.models.map((entry: { id: string }) => (
- entry.id === 'openai/gpt-5.6-sol' ? { ...entry, name: 'NEWER-LKG' } : entry
- )),
+ models: registry.models.map((entry: { id: string }) =>
+ entry.id === "openai/gpt-5.6-sol"
+ ? { ...entry, name: "NEWER-LKG" }
+ : entry,
+ ),
},
};
- const writeCache = vi.fn(async (_scope: string, _text: string) => undefined);
+ const writeCache = vi.fn(
+ async (_scope: string, _text: string) => undefined,
+ );
const loaded = await loadCatalogWithSource(
{ url },
@@ -733,25 +882,30 @@ describe('loadCatalog', () => {
},
);
- expect(loaded.source).toBe('remote');
- expect(loaded.capabilityEvidence).toBe('fallback');
+ expect(loaded.source).toBe("remote");
+ expect(loaded.capabilityEvidence).toBe("fallback");
expect(loaded.catalog.providers[0]?.name).toBe(MINIMAL.providers[0]?.name);
expect(loaded.catalog.modelRegistry?.updatedAt).toBe(newerUpdatedAt);
expect(
- loaded.catalog.modelRegistry?.models.find((entry) => entry.id === 'openai/gpt-5.6-sol')?.name,
- ).toBe('NEWER-LKG');
- expect(loaded.catalog.providers.find((provider) => provider.id === 'xai')?.name)
- .toBe('NEWER-LKG-XAI');
+ loaded.catalog.modelRegistry?.models.find(
+ (entry) => entry.id === "openai/gpt-5.6-sol",
+ )?.name,
+ ).toBe("NEWER-LKG");
+ expect(
+ loaded.catalog.providers.find((provider) => provider.id === "xai")?.name,
+ ).toBe("NEWER-LKG-XAI");
const persisted = JSON.parse(writeCache.mock.calls[0]![1]);
expect(persisted.modelRegistry.updatedAt).toBe(newerUpdatedAt);
- expect(persisted.providers.find((provider: Provider) => provider.id === 'xai')?.name)
- .toBe('NEWER-LKG-XAI');
+ expect(
+ persisted.providers.find((provider: Provider) => provider.id === "xai")
+ ?.name,
+ ).toBe("NEWER-LKG-XAI");
});
- it('rejects a remote registry that republishes the same updatedAt with different content (keeps LKG)', async () => {
- const url = 'https://catalog.example.test/providers.json';
+ it("rejects a remote registry that republishes the same updatedAt with different content (keeps LKG)", async () => {
+ const url = "https://catalog.example.test/providers.json";
const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
- const updatedAt = '2026-08-01T00:00:00.000Z';
+ const updatedAt = "2026-08-01T00:00:00.000Z";
const cached: Catalog = {
...MINIMAL,
modelRegistry: { ...registry, updatedAt },
@@ -774,20 +928,24 @@ describe('loadCatalog', () => {
readCache: vi.fn(async () => JSON.stringify(cached)),
writeCache: vi.fn(async () => undefined),
log: (level, msg) => {
- if (level === 'warn') warns.push(msg);
+ if (level === "warn") warns.push(msg);
},
},
);
- expect(loaded.source).toBe('remote');
- expect(loaded.capabilityEvidence).toBe('fallback');
- expect(loaded.catalog.modelRegistry?.models).toHaveLength(registry.models.length);
- expect(warns.some((msg) => msg.includes('republished the same updatedAt'))).toBe(true);
+ expect(loaded.source).toBe("remote");
+ expect(loaded.capabilityEvidence).toBe("fallback");
+ expect(loaded.catalog.modelRegistry?.models).toHaveLength(
+ registry.models.length,
+ );
+ expect(
+ warns.some((msg) => msg.includes("republished the same updatedAt")),
+ ).toBe(true);
});
- it('adopts the newer snapshot returned by a serialized LKG commit', async () => {
- const url = 'https://catalog.example.test/providers.json';
- const newerUpdatedAt = '2099-08-01T00:00:00.000Z';
+ it("adopts the newer snapshot returned by a serialized LKG commit", async () => {
+ const url = "https://catalog.example.test/providers.json";
+ const newerUpdatedAt = "2099-08-01T00:00:00.000Z";
const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
const newer: Catalog = {
...MINIMAL,
@@ -800,7 +958,7 @@ describe('loadCatalog', () => {
...MINIMAL,
modelRegistry: {
...registry,
- updatedAt: '2026-07-30T00:00:00.000Z',
+ updatedAt: "2026-07-30T00:00:00.000Z",
},
};
@@ -812,13 +970,13 @@ describe('loadCatalog', () => {
},
);
- expect(loaded.source).toBe('remote');
- expect(loaded.capabilityEvidence).toBe('fallback');
+ expect(loaded.source).toBe("remote");
+ expect(loaded.capabilityEvidence).toBe("fallback");
expect(loaded.catalog.modelRegistry?.updatedAt).toBe(newerUpdatedAt);
});
- it('reads LKG even when the startup network budget is zero and rejects bad cache', async () => {
- const url = 'https://catalog.example.test/providers.json';
+ it("reads LKG even when the startup network budget is zero and rejects bad cache", async () => {
+ const url = "https://catalog.example.test/providers.json";
const fetchText = vi.fn();
const cached = await loadCatalogWithSource(
{ url, remoteBudgetMs: 0 },
@@ -828,7 +986,7 @@ describe('loadCatalog', () => {
},
);
expect(fetchText).not.toHaveBeenCalled();
- expect(cached.source).toBe('cache');
+ expect(cached.source).toBe("cache");
const invalid = await loadCatalogWithSource(
{ url, remoteBudgetMs: 0 },
@@ -838,82 +996,95 @@ describe('loadCatalog', () => {
},
);
expect(invalid).toEqual({
- source: 'bundled',
- capabilityEvidence: 'fallback',
- unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ source: "bundled",
+ capabilityEvidence: "fallback",
+ unverifiedXdMediaKinds: ["image", "video", "embedding"],
catalog: BUNDLED_CATALOG,
authorityCatalog: null,
});
});
- it('dev: reads local path, skips network', async () => {
+ it("dev: reads local path, skips network", async () => {
const fetchText = vi.fn();
- const io: CatalogIO = { readFile: vi.fn(async () => JSON.stringify(MINIMAL)), fetchText };
- const cat = await loadCatalog({ localPath: '/repo/providers.json' }, io);
- expect(io.readFile).toHaveBeenCalledWith('/repo/providers.json');
+ const io: CatalogIO = {
+ readFile: vi.fn(async () => JSON.stringify(MINIMAL)),
+ fetchText,
+ };
+ const cat = await loadCatalog({ localPath: "/repo/providers.json" }, io);
+ expect(io.readFile).toHaveBeenCalledWith("/repo/providers.json");
expect(fetchText).not.toHaveBeenCalled();
- expect(cat.providers.find((p) => p.id === 'anthropic')).toBeTruthy();
+ expect(cat.providers.find((p) => p.id === "anthropic")).toBeTruthy();
});
- it('falls back from public API to legacy OSS before bundled', async () => {
- const writeCache = vi.fn(async (_scope: string, _text: string) => undefined);
- const fetchText = vi.fn()
- .mockRejectedValueOnce(new Error('api unavailable'))
+ it("falls back from public API to legacy OSS before bundled", async () => {
+ const writeCache = vi.fn(
+ async (_scope: string, _text: string) => undefined,
+ );
+ const fetchText = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("api unavailable"))
.mockResolvedValueOnce(
JSON.stringify({
...MINIMAL,
- cindyModelMeta: { version: 1, models: { retired: { contextWindow: 1 } } },
+ cindyModelMeta: {
+ version: 1,
+ models: { retired: { contextWindow: 1 } },
+ },
}),
);
const cat = await loadCatalog(
{
- baseUrl: 'https://model-access.example.com',
- fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ baseUrl: "https://model-access.example.com",
+ fallbackBaseUrl: "https://cdn.example.com/cindy",
now: () => 0,
},
{ fetchText, writeCache },
);
expect(fetchText).toHaveBeenNthCalledWith(
1,
- 'https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=3',
+ "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=4",
15_000,
);
expect(fetchText).toHaveBeenNthCalledWith(
2,
- 'https://cdn.example.com/cindy/cfg/providers.json',
+ "https://cdn.example.com/cindy/cfg/providers.json",
expect.any(Number),
);
- expect(cat.version).toBe('test');
- expect(cat).not.toHaveProperty('cindyModelMeta');
+ expect(cat.version).toBe("test");
+ expect(cat).not.toHaveProperty("cindyModelMeta");
expect(writeCache).toHaveBeenCalledWith(
- 'https://cdn.example.com/cindy/cfg/providers.json',
+ "https://cdn.example.com/cindy/cfg/providers.json",
expect.any(String),
);
- expect(JSON.parse(writeCache.mock.calls[0]![1])).not.toHaveProperty('cindyModelMeta');
+ expect(JSON.parse(writeCache.mock.calls[0]![1])).not.toHaveProperty(
+ "cindyModelMeta",
+ );
});
- it('marks legacy OSS as fallback evidence even when its HTTP request succeeds', async () => {
- const fetchText = vi.fn()
- .mockRejectedValueOnce(new Error('api unavailable'))
+ it("marks legacy OSS as fallback evidence even when its HTTP request succeeds", async () => {
+ const fetchText = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("api unavailable"))
.mockResolvedValueOnce(JSON.stringify(MINIMAL));
const result = await loadCatalogWithSource(
{
- baseUrl: 'https://model-access.example.com',
- fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ baseUrl: "https://model-access.example.com",
+ fallbackBaseUrl: "https://cdn.example.com/cindy",
now: () => 0,
},
{ fetchText },
);
expect(result).toMatchObject({
- source: 'remote',
- capabilityEvidence: 'fallback',
- catalog: { version: 'test' },
+ source: "remote",
+ capabilityEvidence: "fallback",
+ catalog: { version: "test" },
authorityCatalog: null,
});
});
- it('falls back from invalid public API payload to legacy OSS before bundled', async () => {
- const fetchText = vi.fn()
+ it("falls back from invalid public API payload to legacy OSS before bundled", async () => {
+ const fetchText = vi
+ .fn()
.mockResolvedValueOnce(
JSON.stringify({
...MINIMAL,
@@ -923,28 +1094,28 @@ describe('loadCatalog', () => {
.mockResolvedValueOnce(JSON.stringify(MINIMAL));
const cat = await loadCatalog(
{
- baseUrl: 'https://model-access.example.com',
- fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ 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?registrySchemaVersion=3',
+ "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=4",
15_000,
);
expect(fetchText).toHaveBeenNthCalledWith(
2,
- 'https://cdn.example.com/cindy/cfg/providers.json',
+ "https://cdn.example.com/cindy/cfg/providers.json",
expect.any(Number),
);
- expect(cat.version).toBe('test');
+ expect(cat.version).toBe("test");
});
- it('loads a legacy OSS LKG after removing its retired metadata block', async () => {
- const legacyUrl = 'https://cdn.example.com/cindy/cfg/providers.json';
- const fetchText = vi.fn().mockRejectedValue(new Error('offline'));
+ it("loads a legacy OSS LKG after removing its retired metadata block", async () => {
+ const legacyUrl = "https://cdn.example.com/cindy/cfg/providers.json";
+ const fetchText = vi.fn().mockRejectedValue(new Error("offline"));
const readCache = vi.fn(async (scope: string) =>
scope === legacyUrl
? JSON.stringify({
@@ -955,31 +1126,33 @@ describe('loadCatalog', () => {
);
const result = await loadCatalogWithSource(
{
- baseUrl: 'https://model-access.example.com',
- fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ baseUrl: "https://model-access.example.com",
+ fallbackBaseUrl: "https://cdn.example.com/cindy",
now: () => 0,
},
{ fetchText, readCache },
);
- expect(result.source).toBe('cache');
- expect(result.capabilityEvidence).toBe('fallback');
- expect(result.catalog.version).toBe('test');
- expect(result.catalog).not.toHaveProperty('cindyModelMeta');
+ expect(result.source).toBe("cache");
+ expect(result.capabilityEvidence).toBe("fallback");
+ expect(result.catalog.version).toBe("test");
+ expect(result.catalog).not.toHaveProperty("cindyModelMeta");
expect(result.authorityCatalog).toBeNull();
});
- it('shares one remote budget across the public API and legacy OSS fallback', async () => {
- const now = vi.fn()
+ 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'))
+ 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',
+ baseUrl: "https://model-access.example.com",
+ fallbackBaseUrl: "https://cdn.example.com/cindy",
remoteBudgetMs: 15_000,
now,
},
@@ -987,27 +1160,28 @@ describe('loadCatalog', () => {
);
expect(fetchText).toHaveBeenNthCalledWith(
1,
- 'https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=3',
+ "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=4",
15_000,
);
expect(fetchText).toHaveBeenNthCalledWith(
2,
- 'https://cdn.example.com/cindy/cfg/providers.json',
+ "https://cdn.example.com/cindy/cfg/providers.json",
5_000,
);
- expect(cat.version).toBe('test');
+ expect(cat.version).toBe("test");
});
- it('does not start legacy OSS after the shared remote budget is exhausted', async () => {
- const now = vi.fn()
+ 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 fetchText = vi.fn().mockRejectedValueOnce(new Error("api timeout"));
const cat = await loadCatalog(
{
- baseUrl: 'https://model-access.example.com',
- fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ baseUrl: "https://model-access.example.com",
+ fallbackBaseUrl: "https://cdn.example.com/cindy",
remoteBudgetMs: 15_000,
now,
},
@@ -1015,157 +1189,219 @@ describe('loadCatalog', () => {
);
expect(fetchText).toHaveBeenCalledTimes(1);
expect(fetchText).toHaveBeenCalledWith(
- 'https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=3',
+ "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=4",
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'));
+ 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',
+ 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(fetchText).toHaveBeenCalledWith(
+ "https://override.example.com/providers.json",
+ 15_000,
+ );
expect(cat.version).toBe(BUNDLED_CATALOG.version);
});
- it('redacts credentials, query, and hash from remote URL diagnostics', async () => {
- const remoteUrl = 'https://catalog-user:[email protected]/providers.json?token=secret-token#private';
- const log = vi.fn<NonNullable<CatalogIO['log']>>();
+ it("redacts credentials, query, and hash from remote URL diagnostics", async () => {
+ const remoteUrl =
+ "https://catalog-user:[email protected]/providers.json?token=secret-token#private";
+ const log = vi.fn<NonNullable<CatalogIO["log"]>>();
const fetchText = vi.fn(async (url: string) => {
throw new Error(`request failed for ${url}`);
});
- await loadCatalog(
- { url: remoteUrl, now: () => 0 },
- { fetchText, log },
- );
+ await loadCatalog({ url: remoteUrl, now: () => 0 }, { fetchText, log });
expect(fetchText).toHaveBeenCalledWith(remoteUrl, 15_000);
const diagnostics = JSON.stringify(log.mock.calls);
- expect(diagnostics).toContain('https://override.example.com/providers.json');
- expect(diagnostics).not.toContain('catalog-user');
- expect(diagnostics).not.toContain('catalog-pass');
- expect(diagnostics).not.toContain('secret-token');
- expect(diagnostics).not.toContain('#private');
+ expect(diagnostics).toContain(
+ "https://override.example.com/providers.json",
+ );
+ expect(diagnostics).not.toContain("catalog-user");
+ expect(diagnostics).not.toContain("catalog-pass");
+ expect(diagnostics).not.toContain("secret-token");
+ expect(diagnostics).not.toContain("#private");
});
- it('keeps special legacy JSON keys inert and lets strict parsing reject them', async () => {
+ it("keeps special legacy JSON keys inert and lets strict parsing reject them", async () => {
const legacyPayload = JSON.stringify(MINIMAL).replace(
- '{',
+ "{",
'{"__proto__":{"polluted":true},"cindyModelMeta":{"version":1},',
);
- const fetchText = vi.fn()
- .mockRejectedValueOnce(new Error('api unavailable'))
+ const fetchText = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("api unavailable"))
.mockResolvedValueOnce(legacyPayload);
const result = await loadCatalogWithSource(
{
- baseUrl: 'https://model-access.example.com',
- fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ baseUrl: "https://model-access.example.com",
+ fallbackBaseUrl: "https://cdn.example.com/cindy",
now: () => 0,
},
{ fetchText },
);
expect(result).toEqual({
- source: 'bundled',
- capabilityEvidence: 'fallback',
- unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ source: "bundled",
+ capabilityEvidence: "fallback",
+ unverifiedXdMediaKinds: ["image", "video", "embedding"],
catalog: BUNDLED_CATALOG,
authorityCatalog: null,
});
- expect((Object.prototype as { polluted?: unknown }).polluted).toBeUndefined();
+ expect(
+ (Object.prototype as { polluted?: unknown }).polluted,
+ ).toBeUndefined();
});
- it('falls back to bundled when fetch fails', async () => {
+ it("falls back to bundled when fetch fails", async () => {
const io: CatalogIO = {
fetchText: vi.fn(async () => {
- throw new Error('network down');
+ throw new Error("network down");
}),
};
- const cat = await loadCatalog({ url: 'https://x/y.json' }, io);
+ const cat = await loadCatalog({ url: "https://x/y.json" }, io);
expect(cat.version).toBe(BUNDLED_CATALOG.version);
- expect(cat.providers.map((p) => p.id).sort()).toEqual(['anthropic', 'gemini', 'openai', 'xai', 'xd']);
+ expect(cat.providers.map((p) => p.id).sort()).toEqual([
+ "anthropic",
+ "gemini",
+ "openai",
+ "xai",
+ "xd",
+ ]);
});
- it('disableFetch → bundled (no network)', async () => {
+ it("disableFetch → bundled (no network)", async () => {
const fetchText = vi.fn();
- const cat = await loadCatalog({ url: 'https://x/y.json', disableFetch: true }, { fetchText });
+ const cat = await loadCatalog(
+ { url: "https://x/y.json", disableFetch: true },
+ { fetchText },
+ );
expect(fetchText).not.toHaveBeenCalled();
expect(cat.providers.length).toBe(BUNDLED_CATALOG.providers.length);
});
});
-describe('registry visibility & sources(运行时注入 fixture)', () => {
- const views = buildRegistry(runtimeCatalog(), { xd: true, anthropic: false, openai: false });
+describe("registry visibility & sources(运行时注入 fixture)", () => {
+ const views = buildRegistry(runtimeCatalog(), {
+ xd: true,
+ anthropic: false,
+ openai: false,
+ });
- it('providersForAgent ignores connection', () => {
- expect(providersForAgent(views, 'claude-code').map((p) => p.id).sort()).toEqual(['anthropic', 'openai', 'xai', 'xd']);
- expect(providersForAgent(views, 'codex').map((p) => p.id).sort()).toEqual(['anthropic', 'openai', 'xai', 'xd']);
+ it("providersForAgent ignores connection", () => {
+ expect(
+ providersForAgent(views, "claude-code")
+ .map((p) => p.id)
+ .sort(),
+ ).toEqual(["anthropic", "openai", "xai", "xd"]);
+ expect(
+ providersForAgent(views, "codex")
+ .map((p) => p.id)
+ .sort(),
+ ).toEqual(["anthropic", "openai", "xai", "xd"]);
});
- it('connectedProvidersForAgent honors connection', () => {
- expect(connectedProvidersForAgent(views, 'claude-code').map((p) => p.id)).toEqual(['xd']);
- expect(connectedProvidersForAgent(views, 'codex').map((p) => p.id)).toEqual(['xd']);
+ it("connectedProvidersForAgent honors connection", () => {
+ expect(
+ connectedProvidersForAgent(views, "claude-code").map((p) => p.id),
+ ).toEqual(["xd"]);
+ expect(connectedProvidersForAgent(views, "codex").map((p) => p.id)).toEqual(
+ ["xd"],
+ );
});
- it('agent selectors and model sources exclude disabled runtimes', () => {
+ it("agent selectors and model sources exclude disabled runtimes", () => {
const catalog = runtimeCatalog();
- const xd = catalog.providers.find((provider) => provider.id === 'xd')!;
+ const xd = catalog.providers.find((provider) => provider.id === "xd")!;
xd.routing.codex = { ...xd.routing.codex!, disabled: true };
const disabledViews = buildRegistry(catalog, { xd: true });
- expect(providersForAgent(disabledViews, 'codex').map((provider) => provider.id))
- .not.toContain('xd');
- expect(connectedProvidersForAgent(disabledViews, 'codex')).toEqual([]);
- expect(sourcesForModel(disabledViews, 'gpt-5.5', 'codex')).toEqual([]);
- expect(connectedProvidersForAgent(disabledViews, 'claude-code').map((provider) => provider.id))
- .toEqual(['xd']);
+ expect(
+ providersForAgent(disabledViews, "codex").map((provider) => provider.id),
+ ).not.toContain("xd");
+ expect(connectedProvidersForAgent(disabledViews, "codex")).toEqual([]);
+ expect(sourcesForModel(disabledViews, "gpt-5.5", "codex")).toEqual([]);
+ expect(
+ connectedProvidersForAgent(disabledViews, "claude-code").map(
+ (provider) => provider.id,
+ ),
+ ).toEqual(["xd"]);
});
- it('agent selectors and model sources exclude a declared agent with no routing descriptor', () => {
+ it("agent selectors and model sources exclude a declared agent with no routing descriptor", () => {
const catalog = runtimeCatalog();
- const xd = catalog.providers.find((provider) => provider.id === 'xd')!;
+ const xd = catalog.providers.find((provider) => provider.id === "xd")!;
delete xd.routing.codex;
const missingRouteViews = buildRegistry(catalog, { xd: true });
- expect(providersForAgent(missingRouteViews, 'codex').map((provider) => provider.id))
- .not.toContain('xd');
- expect(connectedProvidersForAgent(missingRouteViews, 'codex')).toEqual([]);
- expect(sourcesForModel(missingRouteViews, 'gpt-5.5', 'codex')).toEqual([]);
+ expect(
+ providersForAgent(missingRouteViews, "codex").map(
+ (provider) => provider.id,
+ ),
+ ).not.toContain("xd");
+ expect(connectedProvidersForAgent(missingRouteViews, "codex")).toEqual([]);
+ expect(sourcesForModel(missingRouteViews, "gpt-5.5", "codex")).toEqual([]);
});
- it('providerOffersModel / getModel (agent-scoped)', () => {
- const xd = views.find((p) => p.id === 'xd')!;
- expect(providerOffersModel(xd, 'gpt-5.5', 'codex')).toBe(true);
- expect(providerOffersModel(xd, 'no-such', 'codex')).toBe(false);
- expect(providerOffersModel(xd, 'claude-opus-4-8', 'codex')).toBe(false);
- expect(getModel(xd, 'claude-opus-4-8', 'claude-code')?.name).toBe('Opus 4.8');
+ it("providerOffersModel / getModel (agent-scoped)", () => {
+ const xd = views.find((p) => p.id === "xd")!;
+ expect(providerOffersModel(xd, "gpt-5.5", "codex")).toBe(true);
+ expect(providerOffersModel(xd, "no-such", "codex")).toBe(false);
+ expect(providerOffersModel(xd, "claude-opus-4-8", "codex")).toBe(false);
+ expect(getModel(xd, "claude-opus-4-8", "claude-code")?.name).toBe(
+ "Opus 4.8",
+ );
});
- it('sourcesForModel: only connected providers by default', () => {
- expect(sourcesForModel(views, 'claude-opus-4-8', 'claude-code').map((p) => p.id)).toEqual(['xd']);
- expect(sourcesForModel(views, 'claude-opus-4-8', 'claude-code', { onlyConnected: false }).map((p) => p.id).sort())
- .toEqual(['anthropic', 'xd']);
+ it("sourcesForModel: only connected providers by default", () => {
+ expect(
+ sourcesForModel(views, "claude-opus-4-8", "claude-code").map((p) => p.id),
+ ).toEqual(["xd"]);
+ expect(
+ sourcesForModel(views, "claude-opus-4-8", "claude-code", {
+ onlyConnected: false,
+ })
+ .map((p) => p.id)
+ .sort(),
+ ).toEqual(["anthropic", "xd"]);
});
- it('sourcesForModel: same model two sources when both connected', () => {
- const all = buildRegistry(runtimeCatalog(), { xd: true, anthropic: true, openai: true, xai: true });
- expect(sourcesForModel(all, 'gpt-5.5', 'codex').map((p) => p.id).sort()).toEqual(['openai', 'xd']);
- expect(sourcesForModel(all, 'gpt-5.5', 'claude-code').map((p) => p.id)).toEqual(['xd']);
- expect(sourcesForModel(all, 'xai/grok-4.3', 'codex').map((p) => p.id)).toEqual(['xai']);
+ it("sourcesForModel: same model two sources when both connected", () => {
+ const all = buildRegistry(runtimeCatalog(), {
+ xd: true,
+ anthropic: true,
+ openai: true,
+ xai: true,
+ });
+ expect(
+ sourcesForModel(all, "gpt-5.5", "codex")
+ .map((p) => p.id)
+ .sort(),
+ ).toEqual(["openai", "xd"]);
+ expect(
+ sourcesForModel(all, "gpt-5.5", "claude-code").map((p) => p.id),
+ ).toEqual(["xd"]);
+ expect(
+ sourcesForModel(all, "xai/grok-4.3", "codex").map((p) => p.id),
+ ).toEqual(["xai"]);
});
- it('effectiveSourceIdForModel 只在真正提供当前模型的已连接来源里选默认', () => {
+ it("effectiveSourceIdForModel 只在真正提供当前模型的已连接来源里选默认", () => {
const openaiOnly = buildRegistry(runtimeCatalog(), {
xd: false,
anthropic: false,
@@ -1173,14 +1409,24 @@ describe('registry visibility & sources(运行时注入 fixture)', () => {
xai: false,
});
expect(
- effectiveSourceIdForModel(openaiOnly, null, 'claude-opus-4-8', 'claude-code'),
+ effectiveSourceIdForModel(
+ openaiOnly,
+ null,
+ "claude-opus-4-8",
+ "claude-code",
+ ),
).toBeNull();
expect(
- effectiveSourceIdForModel(openaiOnly, null, 'chatgpt/gpt-5.5', 'claude-code'),
- ).toBe('openai');
+ effectiveSourceIdForModel(
+ openaiOnly,
+ null,
+ "chatgpt/gpt-5.5",
+ "claude-code",
+ ),
+ ).toBe("openai");
});
- it('effectiveSourceIdForModel 保留有效显式来源,失效时回落到同模型默认来源', () => {
+ it("effectiveSourceIdForModel 保留有效显式来源,失效时回落到同模型默认来源", () => {
const all = buildRegistry(runtimeCatalog(), {
xd: true,
anthropic: true,
@@ -1188,145 +1434,200 @@ describe('registry visibility & sources(运行时注入 fixture)', () => {
xai: true,
});
expect(
- effectiveSourceIdForModel(all, 'anthropic', 'claude-opus-4-8', 'claude-code'),
- ).toBe('anthropic');
+ effectiveSourceIdForModel(
+ all,
+ "anthropic",
+ "claude-opus-4-8",
+ "claude-code",
+ ),
+ ).toBe("anthropic");
expect(
- effectiveSourceIdForModel(all, 'openai', 'claude-opus-4-8', 'claude-code'),
- ).toBe('xd');
+ effectiveSourceIdForModel(
+ all,
+ "openai",
+ "claude-opus-4-8",
+ "claude-code",
+ ),
+ ).toBe("xd");
});
- it('effectiveSourceIdForModel 不把请求路由到非聊天来源(issue #882 第 3 点,2026-07 review):同一 id 在不同来源上 mode 不一致时,只信聊天来源', () => {
+ it("effectiveSourceIdForModel 不把请求路由到非聊天来源(issue #882 第 3 点,2026-07 review):同一 id 在不同来源上 mode 不一致时,只信聊天来源", () => {
const mixedModeCatalog: Catalog = {
- version: 'test',
+ version: "test",
providers: [
{
- id: 'xd',
- name: 'XD',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'managed' },
- routing: { 'claude-code': { upstream: 'https://xd.test', authStrategy: 'gateway-key' } },
+ id: "xd",
+ name: "XD",
+ source: "builtin",
+ agents: ["claude-code"],
+ auth: { method: "managed" },
+ routing: {
+ "claude-code": {
+ upstream: "https://xd.test",
+ authStrategy: "gateway-key",
+ },
+ },
models: {
- 'claude-code': [model('shared-id', { mode: 'image_generation' })],
+ "claude-code": [model("shared-id", { mode: "image_generation" })],
},
},
{
- id: 'openai',
- name: 'OpenAI',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: { 'claude-code': { upstream: 'https://api.openai.com', authStrategy: 'oauth-passthrough' } },
+ id: "openai",
+ name: "OpenAI",
+ source: "builtin",
+ agents: ["claude-code"],
+ auth: { method: "oauth" },
+ routing: {
+ "claude-code": {
+ upstream: "https://api.openai.com",
+ authStrategy: "oauth-passthrough",
+ },
+ },
models: {
- 'claude-code': [model('shared-id', { mode: 'chat' })],
+ "claude-code": [model("shared-id", { mode: "chat" })],
},
},
],
};
const views = buildRegistry(mixedModeCatalog, { xd: true, openai: true });
// 显式指定的 providerId 恰好是非聊天来源(xd)时,不接受它——落到真正聊天的来源(openai)。
- expect(effectiveSourceIdForModel(views, 'xd', 'shared-id', 'claude-code')).toBe('openai');
+ expect(
+ effectiveSourceIdForModel(views, "xd", "shared-id", "claude-code"),
+ ).toBe("openai");
// 未显式指定 providerId 时,默认来源同样只能是聊天来源。
- expect(effectiveSourceIdForModel(views, null, 'shared-id', 'claude-code')).toBe('openai');
+ expect(
+ effectiveSourceIdForModel(views, null, "shared-id", "claude-code"),
+ ).toBe("openai");
// chatEligibleSourcesForModel 是这份过滤的共享底层——直接断言它自己的输出,
// 保证 UI 侧的"有没有可发送来源"判断(ChatInput/useConnectedSource/
// isSelectedSourceDisconnected)与路由解析用的是同一份口径,不会互相打架。
- expect(chatEligibleSourcesForModel(views, 'shared-id', 'claude-code').map((p) => p.id)).toEqual([
- 'openai',
- ]);
+ expect(
+ chatEligibleSourcesForModel(views, "shared-id", "claude-code").map(
+ (p) => p.id,
+ ),
+ ).toEqual(["openai"]);
});
- it('chatEligibleSourcesForModel 不误杀用户自定义供应商显式配置的模型(2026-07 review 第 25 轮)', () => {
+ it("chatEligibleSourcesForModel 不误杀用户自定义供应商显式配置的模型(2026-07 review 第 25 轮)", () => {
// flux-image-x 的 id 撞上 /image/ 启发式,但它来自 source:'user' 的自定义供应商且
// group 是未知的 custom:*——isAgentSelectableModel 的 userProvider 例外有意放行
// (用户显式配置的就是聊天模型)。裸 isChatEligible 会把它从路由/发送门禁里删掉,
// 用户配好的模型 UI 显示"没有已连接的来源"、请求发不出去。
const userProviderCatalog: Catalog = {
- version: 'test',
+ version: "test",
providers: [
{
- id: 'custom-p',
- name: 'Custom',
- source: 'user',
- agents: ['claude-code'],
- auth: { method: 'apiKey' },
+ id: "custom-p",
+ name: "Custom",
+ source: "user",
+ agents: ["claude-code"],
+ auth: { method: "apiKey" },
routing: {
- 'claude-code': {
- upstream: 'https://custom.test',
- authStrategy: 'api-key-header',
+ "claude-code": {
+ upstream: "https://custom.test",
+ authStrategy: "api-key-header",
},
},
models: {
- 'claude-code': [model('flux-image-x', { group: 'custom:custom-p' })],
+ "claude-code": [
+ model("flux-image-x", { group: "custom:custom-p" }),
+ ],
},
},
],
};
- const views = buildRegistry(userProviderCatalog, { 'custom-p': true });
+ const views = buildRegistry(userProviderCatalog, { "custom-p": true });
expect(
- chatEligibleSourcesForModel(views, 'flux-image-x', 'claude-code').map((p) => p.id),
- ).toEqual(['custom-p']);
- expect(effectiveSourceIdForModel(views, 'custom-p', 'flux-image-x', 'claude-code')).toBe(
- 'custom-p',
- );
+ chatEligibleSourcesForModel(views, "flux-image-x", "claude-code").map(
+ (p) => p.id,
+ ),
+ ).toEqual(["custom-p"]);
+ expect(
+ effectiveSourceIdForModel(
+ views,
+ "custom-p",
+ "flux-image-x",
+ "claude-code",
+ ),
+ ).toBe("custom-p");
});
});
-describe('resolveRoute(运行时注入 fixture)', () => {
- const views = buildRegistry(runtimeCatalog(), { xd: true, anthropic: true, openai: true, xai: true });
+describe("resolveRoute(运行时注入 fixture)", () => {
+ const views = buildRegistry(runtimeCatalog(), {
+ xd: true,
+ anthropic: true,
+ openai: true,
+ xai: true,
+ });
// xd 网关地址以内置身份卡(builtin.ts,端点单点)为准;门禁校验其与权威源一致
- const xdRouting = BUNDLED_CATALOG.providers.find((prov) => prov.id === 'xd')?.routing;
-
- it('anthropic claude (claude-code) → direct upstream, oauth-passthrough', () => {
- const r = resolveRoute(views, 'anthropic', 'claude-opus-4-8', 'claude-code');
- expect(r?.routing.upstream).toBe('https://api.anthropic.com');
- expect(r?.routing.authStrategy).toBe('oauth-passthrough');
+ const xdRouting = BUNDLED_CATALOG.providers.find(
+ (prov) => prov.id === "xd",
+ )?.routing;
+
+ it("anthropic claude (claude-code) → direct upstream, oauth-passthrough", () => {
+ const r = resolveRoute(
+ views,
+ "anthropic",
+ "claude-opus-4-8",
+ "claude-code",
+ );
+ expect(r?.routing.upstream).toBe("https://api.anthropic.com");
+ expect(r?.routing.authStrategy).toBe("oauth-passthrough");
});
- it('anthropic claude (codex) → Anthropic Messages bridge + host-owned OAuth', () => {
- const r = resolveRoute(views, 'anthropic', 'claude-opus-4-8', 'codex');
+ it("anthropic claude (codex) → Anthropic Messages bridge + host-owned OAuth", () => {
+ const r = resolveRoute(views, "anthropic", "claude-opus-4-8", "codex");
expect(r?.routing).toMatchObject({
- upstream: 'https://api.anthropic.com',
- wireProtocol: 'anthropic-messages',
- authStrategy: 'provider-oauth-header',
+ upstream: "https://api.anthropic.com",
+ wireProtocol: "anthropic-messages",
+ authStrategy: "provider-oauth-header",
headerOverride: {
- 'anthropic-version': '2023-06-01',
- 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20',
+ "anthropic-version": "2023-06-01",
+ "anthropic-beta": "claude-code-20250219,oauth-2025-04-20",
},
});
});
- it('xd claude (claude-code) → gateway, gateway-key, 不删 anthropic-beta(fast 经网关透传)', () => {
- const r = resolveRoute(views, 'xd', 'claude-opus-4-8', 'claude-code');
- expect(r?.routing.upstream).toBe(xdRouting?.['claude-code']?.upstream);
- expect(r?.routing.authStrategy).toBe('gateway-key');
+ it("xd claude (claude-code) → gateway, gateway-key, 不删 anthropic-beta(fast 经网关透传)", () => {
+ const r = resolveRoute(views, "xd", "claude-opus-4-8", "claude-code");
+ expect(r?.routing.upstream).toBe(xdRouting?.["claude-code"]?.upstream);
+ expect(r?.routing.authStrategy).toBe("gateway-key");
expect(r?.routing.headerDelete).toBeUndefined();
});
- it('xd gpt (codex) → gateway/v1; openai gpt (codex) → chatgpt direct', () => {
- expect(resolveRoute(views, 'xd', 'gpt-5.5', 'codex')?.routing.upstream).toBe(xdRouting?.codex?.upstream);
- const oa = resolveRoute(views, 'openai', 'gpt-5.5', 'codex');
- expect(oa?.routing.upstream).toBe('https://chatgpt.com/backend-api/codex');
- expect(oa?.routing.authStrategy).toBe('oauth-passthrough');
+ it("xd gpt (codex) → gateway/v1; openai gpt (codex) → chatgpt direct", () => {
+ expect(
+ resolveRoute(views, "xd", "gpt-5.5", "codex")?.routing.upstream,
+ ).toBe(xdRouting?.codex?.upstream);
+ const oa = resolveRoute(views, "openai", "gpt-5.5", "codex");
+ expect(oa?.routing.upstream).toBe("https://chatgpt.com/backend-api/codex");
+ expect(oa?.routing.authStrategy).toBe("oauth-passthrough");
});
- it('xai grok (codex) → api.x.ai/v1 with provider OAuth token and xai/ model rewrite', () => {
- const r = resolveRoute(views, 'xai', 'xai/grok-4.3', 'codex');
- expect(r?.routing.upstream).toBe('https://api.x.ai/v1');
- expect(r?.routing.authStrategy).toBe('provider-oauth-header');
- expect(r?.routing.modelIdRewrite).toEqual({ stripPrefix: 'xai/' });
+ it("xai grok (codex) → api.x.ai/v1 with provider OAuth token and xai/ model rewrite", () => {
+ const r = resolveRoute(views, "xai", "xai/grok-4.3", "codex");
+ expect(r?.routing.upstream).toBe("https://api.x.ai/v1");
+ expect(r?.routing.authStrategy).toBe("provider-oauth-header");
+ expect(r?.routing.modelIdRewrite).toEqual({ stripPrefix: "xai/" });
});
- it('rejects unsupported (provider, model, agent) combos', () => {
- expect(resolveRoute(views, 'anthropic', 'gpt-5.5', 'claude-code')).toBeNull();
- expect(resolveRoute(views, 'openai', 'claude-opus-4-8', 'codex')).toBeNull();
- expect(resolveRoute(views, 'nope', 'claude-opus-4-8', 'claude-code')).toBeNull();
+ it("rejects unsupported (provider, model, agent) combos", () => {
+ expect(
+ resolveRoute(views, "anthropic", "gpt-5.5", "claude-code"),
+ ).toBeNull();
+ expect(
+ resolveRoute(views, "openai", "claude-opus-4-8", "codex"),
+ ).toBeNull();
+ expect(
+ resolveRoute(views, "nope", "claude-opus-4-8", "claude-code"),
+ ).toBeNull();
});
- it('rejects a disabled route even when provider, model, and agent match', () => {
+ it("rejects a disabled route even when provider, model, and agent match", () => {
const disabledViews = views.map((provider) =>
- provider.id === 'xai'
+ provider.id === "xai"
? {
...provider,
routing: {
@@ -1336,13 +1637,80 @@ describe('resolveRoute(运行时注入 fixture)', () => {
}
: provider,
);
- expect(resolveRoute(disabledViews, 'xai', 'xai/grok-4.3', 'codex')).toBeNull();
+ expect(
+ resolveRoute(disabledViews, "xai", "xai/grok-4.3", "codex"),
+ ).toBeNull();
});
- it('动态供应商未注入清单时不解析路由(无可用性证明不路由)', () => {
- const bare = buildRegistry(BUNDLED_CATALOG, { xd: true, anthropic: true, openai: true, xai: true });
- expect(resolveRoute(bare, 'anthropic', 'claude-opus-4-8', 'claude-code')).toBeNull();
- expect(resolveRoute(bare, 'xd', 'gpt-5.5', 'codex')).toBeNull();
- expect(resolveRoute(bare, 'xai', 'xai/grok-4.3', 'codex')?.routing.upstream).toBe('https://api.x.ai/v1');
+ it("动态供应商未注入清单时不解析路由(无可用性证明不路由)", () => {
+ const bare = buildRegistry(BUNDLED_CATALOG, {
+ xd: true,
+ anthropic: true,
+ openai: true,
+ xai: true,
+ });
+ expect(
+ resolveRoute(bare, "anthropic", "claude-opus-4-8", "claude-code"),
+ ).toBeNull();
+ expect(resolveRoute(bare, "xd", "gpt-5.5", "codex")).toBeNull();
+ expect(
+ resolveRoute(bare, "xai", "xai/grok-4.3", "codex")?.routing.upstream,
+ ).toBe("https://api.x.ai/v1");
+ });
+});
+
+describe("server-delivered local models", () => {
+ it("accepts later V4 updates and preserves an explicit empty recommendation through offline fallback", async () => {
+ const snapshot = {
+ ...MINIMAL,
+ modelRegistry: {
+ schemaVersion: 4,
+ updatedAt: "2099-01-01T00:00:00.000Z",
+ models: [],
+ localModels: { version: 1, models: [], featuredIds: [] },
+ },
+ };
+ let cached: string | null = null;
+ const cfg = { baseUrl: "https://model-access.example.com" };
+ const io: CatalogIO = {
+ fetchText: async () => JSON.stringify(snapshot),
+ readCache: async () => cached,
+ writeCache: async (_scope, text) => {
+ cached = text;
+ },
+ };
+ const remote = await loadCatalogWithSource(cfg, io);
+ expect(remote.catalog.modelRegistry?.localModels).toEqual(
+ snapshot.modelRegistry.localModels,
+ );
+ const offline = await loadCatalogWithSource(cfg, {
+ ...io,
+ fetchText: async () => {
+ throw new Error("offline");
+ },
+ });
+ expect(offline.source).toBe("cache");
+ expect(offline.catalog.modelRegistry?.localModels?.featuredIds).toEqual([]);
+ const invalid = structuredClone(snapshot);
+ invalid.modelRegistry.localModels.featuredIds = ["missing"] as never[];
+ const rejected = await loadCatalogWithSource(cfg, {
+ ...io,
+ fetchText: async () => JSON.stringify(invalid),
+ });
+ expect(rejected.catalog.modelRegistry?.localModels).toEqual(
+ snapshot.modelRegistry.localModels,
+ );
+ expect(JSON.parse(cached!).modelRegistry.localModels.featuredIds).toEqual(
+ [],
+ );
+ const conflict = structuredClone(snapshot);
+ delete (conflict.modelRegistry as { localModels?: unknown }).localModels;
+ const retained = await loadCatalogWithSource(cfg, {
+ ...io,
+ fetchText: async () => JSON.stringify(conflict),
+ });
+ expect(retained.catalog.modelRegistry?.localModels).toEqual(
+ snapshot.modelRegistry.localModels,
+ );
});
});
diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.ts
index ac68271f7d..4356ef96f4 100644
--- a/packages/model-providers/src/__tests__/user-provider.test.ts
+++ b/packages/model-providers/src/__tests__/user-provider.test.ts
@@ -1,3 +1,4 @@
+import { expandedRegistryEntries } from "../modelMetadataLayers.js";
/**
* buildUserProvider —— 用户自定义配置(per-runtime)→ 标准 Provider 的映射。
*
@@ -23,6 +24,14 @@ import type { CustomProviderConfig } from "../types.js";
import type { ModelRegistry } from "../modelAccessBean.js";
import { BUNDLED_CATALOG } from "../catalog.js";
+// Preserve the pre-V4 contract explicitly; layered V4 behavior has independent cases below.
+const LEGACY_REGISTRY: ModelRegistry = {
+ ...BUNDLED_CATALOG.modelRegistry!,
+ schemaVersion: 3,
+ baseModels: undefined,
+ models: expandedRegistryEntries(BUNDLED_CATALOG.modelRegistry!),
+};
+
const codexOnly: CustomProviderConfig = {
id: "openrouter",
name: "OpenRouter",
@@ -64,7 +73,9 @@ describe("buildUserProvider (per-runtime)", () => {
});
it("projects official Imagine models onto the xAI API-key source", () => {
- const source = BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!;
+ const source = BUNDLED_CATALOG.providers.find(
+ (provider) => provider.id === "xai",
+ )!;
const xaiApi = buildUserProvider({
id: XAI_API_CUSTOM_PROVIDER_ID,
name: "xAI API",
@@ -78,12 +89,16 @@ describe("buildUserProvider (per-runtime)", () => {
});
const projected = projectXaiApiImageModels([source, xaiApi]);
- expect(projected.find((provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID)?.imageModels)
- .toEqual(source.imageModels);
+ expect(
+ projected.find((provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID)
+ ?.imageModels,
+ ).toEqual(source.imageModels);
});
it("does not project Imagine models onto a non-official API-key endpoint", () => {
- const source = BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!;
+ const source = BUNDLED_CATALOG.providers.find(
+ (provider) => provider.id === "xai",
+ )!;
const proxy = buildUserProvider({
id: XAI_API_CUSTOM_PROVIDER_ID,
name: "xAI-compatible proxy",
@@ -282,7 +297,7 @@ describe("buildUserProvider (per-runtime)", () => {
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
expect(provider.routing).toMatchObject({
@@ -333,7 +348,7 @@ describe("buildUserProvider (per-runtime)", () => {
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
expect(provider.models.codex?.[0]).toMatchObject({
@@ -347,102 +362,102 @@ describe("buildUserProvider (per-runtime)", () => {
).toBeUndefined();
});
-it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)', () => {
+ it("strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)", () => {
const p = buildUserProvider(
{
- id: 'my-provider',
- name: 'My Provider',
+ id: "my-provider",
+ name: "My Provider",
runtimes: {
codex: {
- baseUrl: 'https://my-provider.example/v1',
- models: [{ id: 'xd/codex/gpt-5.6-sol', name: 'GPT-5.6-Sol' }],
+ baseUrl: "https://my-provider.example/v1",
+ models: [{ id: "xd/codex/gpt-5.6-sol", name: "GPT-5.6-Sol" }],
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
// xd/codex/gpt-5.6-sol → strips to codex/gpt-5.6-sol → no exact match
// → further strips? no, only openai/xd/chatgpt/ are stripped.
// Actually xd/codex/gpt-5.6-sol starts with xd/ → stripped to codex/gpt-5.6-sol
// which matches route.modelId for codex agent.
expect(p.models.codex?.[0]).toMatchObject({
- id: 'xd/codex/gpt-5.6-sol',
- efforts: expect.arrayContaining(['ultra']),
- defaultEffort: 'medium',
+ id: "xd/codex/gpt-5.6-sol",
+ efforts: expect.arrayContaining(["ultra"]),
+ defaultEffort: "medium",
});
});
- it('strips xd/ prefix to match registry effort metadata', () => {
+ it("strips xd/ prefix to match registry effort metadata", () => {
const p = buildUserProvider(
{
- id: 'xd-relay',
- name: 'XD Relay',
+ id: "xd-relay",
+ name: "XD Relay",
runtimes: {
codex: {
- baseUrl: 'https://xd-relay.example/v1',
- models: [{ id: 'xd/gpt-5.6-sol', name: 'GPT-5.6-Sol' }],
+ baseUrl: "https://xd-relay.example/v1",
+ models: [{ id: "xd/gpt-5.6-sol", name: "GPT-5.6-Sol" }],
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
// xd/gpt-5.6-sol → strips to gpt-5.6-sol → matches registry entry
expect(p.models.codex?.[0]).toMatchObject({
- id: 'xd/gpt-5.6-sol',
- efforts: expect.arrayContaining(['ultra']),
- defaultEffort: 'medium',
+ id: "xd/gpt-5.6-sol",
+ efforts: expect.arrayContaining(["ultra"]),
+ defaultEffort: "medium",
});
});
- it('strips openai/ prefix to match registry effort metadata (entry.id ≠ custom id)', () => {
+ it("strips openai/ prefix to match registry effort metadata (entry.id ≠ custom id)", () => {
const p = buildUserProvider(
{
- id: 'openai-relay',
- name: 'OpenAI Relay',
+ id: "openai-relay",
+ name: "OpenAI Relay",
runtimes: {
codex: {
- baseUrl: 'https://openai-relay.example/v1',
- models: [{ id: 'openai/gpt-5.6-sol', name: 'GPT-5.6-Sol' }],
+ baseUrl: "https://openai-relay.example/v1",
+ models: [{ id: "openai/gpt-5.6-sol", name: "GPT-5.6-Sol" }],
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
// openai/gpt-5.6-sol → strips to gpt-5.6-sol → matches registry entry
// entry.id = 'gpt-5.6-sol' ≠ custom id 'openai/gpt-5.6-sol'
expect(p.models.codex?.[0]).toMatchObject({
- id: 'openai/gpt-5.6-sol',
- efforts: expect.arrayContaining(['ultra']),
- defaultEffort: 'medium',
+ id: "openai/gpt-5.6-sol",
+ efforts: expect.arrayContaining(["ultra"]),
+ defaultEffort: "medium",
});
});
- it('unregistered prefix falls back to CUSTOM_EFFORTS', () => {
+ it("unregistered prefix falls back to CUSTOM_EFFORTS", () => {
const p = buildUserProvider(
{
- id: 'unknown-relay',
- name: 'Unknown Relay',
+ id: "unknown-relay",
+ name: "Unknown Relay",
runtimes: {
codex: {
- baseUrl: 'https://unknown.example/v1',
- models: [{ id: 'custom/my-model', name: 'My Model' }],
+ baseUrl: "https://unknown.example/v1",
+ models: [{ id: "custom/my-model", name: "My Model" }],
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
// custom/my-model → no registry match → CUSTOM_EFFORTS for codex
expect(p.models.codex?.[0]).toMatchObject({
- id: 'custom/my-model',
- efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
- defaultEffort: 'medium',
+ id: "custom/my-model",
+ efforts: ["low", "medium", "high", "xhigh", "max"],
+ defaultEffort: "medium",
});
});
it.each(["gpt-5.6-sol", "gpt-5.6-terra"])(
"inherits equivalent Registry effort metadata across matching entries for %s",
(modelId) => {
- const registry = structuredClone(BUNDLED_CATALOG.modelRegistry);
+ const registry = structuredClone(LEGACY_REGISTRY);
if (!registry) throw new Error("missing bundled model registry");
const baseEntry = registry.models.find(
(entry) => entry.id === `openai/${modelId}`,
@@ -477,7 +492,7 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
it.each(["xd/gpt-5.6-sol", "chatgpt/gpt-5.6-sol"])(
"inherits equivalent Registry effort metadata after stripping the prefix from %s",
(modelId) => {
- const registry = structuredClone(BUNDLED_CATALOG.modelRegistry);
+ const registry = structuredClone(LEGACY_REGISTRY);
if (!registry) throw new Error("missing bundled model registry");
const baseEntry = registry.models.find(
(entry) => entry.id === "openai/gpt-5.6-sol",
@@ -514,7 +529,7 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
);
it("rejects conflicting Registry effort metadata after prefix stripping", () => {
- const registry = structuredClone(BUNDLED_CATALOG.modelRegistry);
+ const registry = structuredClone(LEGACY_REGISTRY);
if (!registry) throw new Error("missing bundled model registry");
const baseEntry = registry.models.find(
(entry) => entry.id === "openai/gpt-5.6-sol",
@@ -553,8 +568,8 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
});
});
- it('falls back safely for conflicting matches, missing target routes and invalid defaults', () => {
- const registry = structuredClone(BUNDLED_CATALOG.modelRegistry);
+ it("falls back safely for conflicting matches, missing target routes and invalid defaults", () => {
+ const registry = structuredClone(LEGACY_REGISTRY);
if (!registry) throw new Error("missing bundled model registry");
const baseEntry = registry.models.find(
(entry) => entry.id === "openai/gpt-5.6-sol",
@@ -624,7 +639,7 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
expect(noTargetRoute.models.codex?.[0]).toMatchObject({
efforts: ["low", "medium", "high", "xhigh", "max"],
@@ -852,21 +867,21 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
expect((p.models.pi ?? [])[0]?.defaultEffort).toBeNull();
expect((p.models.pi ?? [])[0]?.group).toBe("custom:localollama");
expect((p.models.pi ?? [])[0]?.supportsImageInput).toBe(true);
- expect(p.routing.pi?.wireProtocol).toBe('openai-chat');
+ expect(p.routing.pi?.wireProtocol).toBe("openai-chat");
});
- it('projects image generation independently from image input', () => {
+ it("projects image generation independently from image input", () => {
const p = buildUserProvider({
- id: 'images',
- name: 'Images',
+ id: "images",
+ name: "Images",
runtimes: {
codex: {
- baseUrl: 'https://images.example/v1',
- wireProtocol: 'openai-responses',
+ baseUrl: "https://images.example/v1",
+ wireProtocol: "openai-responses",
supportsImageGeneration: true,
models: [
- { id: 'generate', name: 'Generate' },
- { id: 'input', name: 'Input', supportsImageInput: true },
+ { id: "generate", name: "Generate" },
+ { id: "input", name: "Input", supportsImageInput: true },
],
},
},
@@ -898,12 +913,16 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
"claude-code": {
baseUrl: "http://127.0.0.1:11434",
wireProtocol: "anthropic-messages",
- models: [{ id: "qwen3.8:27b-mlx", name: "Qwen3.8", reasoning: false }],
+ models: [
+ { id: "qwen3.8:27b-mlx", name: "Qwen3.8", reasoning: false },
+ ],
},
codex: {
baseUrl: "http://127.0.0.1:11434/v1",
wireProtocol: "openai-responses",
- models: [{ id: "qwen3.8:27b-mlx", name: "Qwen3.8", reasoning: false }],
+ models: [
+ { id: "qwen3.8:27b-mlx", name: "Qwen3.8", reasoning: false },
+ ],
},
},
});
@@ -953,7 +972,7 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
expect(p.models.pi?.[0]).toMatchObject({
efforts: [],
@@ -961,62 +980,66 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
});
});
- it('strips xd/ prefix to match registry effort metadata for claude-code', () => {
+ it("strips xd/ prefix to match registry effort metadata for claude-code", () => {
const p = buildUserProvider(
{
- id: 'my-provider',
- name: 'My Provider',
+ id: "my-provider",
+ name: "My Provider",
runtimes: {
- 'claude-code': {
- baseUrl: 'https://my-provider.example/v1',
- models: [{ id: 'xd/codex/gpt-5.6-sol', name: 'GPT-5.6-Sol' }],
+ "claude-code": {
+ baseUrl: "https://my-provider.example/v1",
+ models: [{ id: "xd/codex/gpt-5.6-sol", name: "GPT-5.6-Sol" }],
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
// xd/codex/gpt-5.6-sol → strips xd/ → codex/gpt-5.6-sol → matches route for claude-code
// without prefix-stripping, the model ID wouldn't match any registry entry
// and efforts would fall back to CUSTOM_EFFORTS (no 'xhigh' from registry).
- const model = p.models['claude-code']?.[0];
+ const model = p.models["claude-code"]?.[0];
expect(model?.efforts?.length).toBeGreaterThan(0);
- expect(model?.efforts).toContain('xhigh');
+ expect(model?.efforts).toContain("xhigh");
});
- it('strips xd/ prefix to match registry effort metadata for codex', () => {
+ it("strips xd/ prefix to match registry effort metadata for codex", () => {
const p = buildUserProvider(
{
- id: 'xd-relay',
- name: 'XD Relay',
+ id: "xd-relay",
+ name: "XD Relay",
runtimes: {
codex: {
- baseUrl: 'https://xd-relay.example/v1',
- models: [{ id: 'xd/gpt-5.6-sol', name: 'GPT-5.6-Sol' }],
+ baseUrl: "https://xd-relay.example/v1",
+ models: [{ id: "xd/gpt-5.6-sol", name: "GPT-5.6-Sol" }],
},
},
},
- { modelRegistry: BUNDLED_CATALOG.modelRegistry },
+ { modelRegistry: LEGACY_REGISTRY },
);
const model = p.models.codex?.[0];
expect(model?.efforts?.length).toBeGreaterThan(0);
- expect(model?.efforts).toContain('xhigh');
+ expect(model?.efforts).toContain("xhigh");
});
- it('synthetic registry: prefix stripping is required for openai/xd/chatgpt/ prefixes', () => {
+ it("synthetic registry: prefix stripping is required for openai/xd/chatgpt/ prefixes", () => {
// Synthetic registry where entry id = 'synthetic-gpt' with 'ultra' effort.
// Custom model id = 'openai/synthetic-gpt' can only match via prefix stripping.
// If strip-prefix code is removed, efforts would remain empty.
const syntheticRegistry: ModelRegistry = {
- updatedAt: '2026-01-01T00:00:00Z',
+ updatedAt: "2026-01-01T00:00:00Z",
schemaVersion: 2,
models: [
{
- id: 'synthetic-gpt',
- name: 'Synthetic GPT',
- efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
- defaultEffort: 'high',
+ id: "synthetic-gpt",
+ name: "Synthetic GPT",
+ efforts: ["low", "medium", "high", "xhigh", "max", "ultra"],
+ defaultEffort: "high",
routes: [
- { providerId: 'test-provider', modelId: 'synthetic-gpt', agents: ['claude-code', 'codex'] },
+ {
+ providerId: "test-provider",
+ modelId: "synthetic-gpt",
+ agents: ["claude-code", "codex"],
+ },
],
},
],
@@ -1024,41 +1047,86 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
// openai/ prefix: should strip and match synthetic-gpt
const pOpenai = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { 'claude-code': { baseUrl: 'https://x/v1', models: [{ id: 'openai/synthetic-gpt', name: 'G' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ "claude-code": {
+ baseUrl: "https://x/v1",
+ models: [{ id: "openai/synthetic-gpt", name: "G" }],
+ },
+ },
+ },
{ modelRegistry: syntheticRegistry },
);
- expect(pOpenai.models['claude-code']?.[0]?.efforts).toContain('ultra');
+ expect(pOpenai.models["claude-code"]?.[0]?.efforts).toContain("ultra");
// xd/ prefix: should strip and match
const pXd = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { codex: { baseUrl: 'https://x/v1', models: [{ id: 'xd/synthetic-gpt', name: 'G' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ codex: {
+ baseUrl: "https://x/v1",
+ models: [{ id: "xd/synthetic-gpt", name: "G" }],
+ },
+ },
+ },
{ modelRegistry: syntheticRegistry },
);
- expect(pXd.models.codex?.[0]?.efforts).toContain('ultra');
+ expect(pXd.models.codex?.[0]?.efforts).toContain("ultra");
// chatgpt/ prefix: should strip and match
const pChatgpt = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { 'claude-code': { baseUrl: 'https://x/v1', models: [{ id: 'chatgpt/synthetic-gpt', name: 'G' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ "claude-code": {
+ baseUrl: "https://x/v1",
+ models: [{ id: "chatgpt/synthetic-gpt", name: "G" }],
+ },
+ },
+ },
{ modelRegistry: syntheticRegistry },
);
- expect(pChatgpt.models['claude-code']?.[0]?.efforts).toContain('ultra');
+ expect(pChatgpt.models["claude-code"]?.[0]?.efforts).toContain("ultra");
// unknown prefix: should NOT match registry, gets default CUSTOM_EFFORTS (no 'ultra')
const pUnknown = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { 'claude-code': { baseUrl: 'https://x/v1', models: [{ id: 'unknown/synthetic-gpt', name: 'G' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ "claude-code": {
+ baseUrl: "https://x/v1",
+ models: [{ id: "unknown/synthetic-gpt", name: "G" }],
+ },
+ },
+ },
{ modelRegistry: syntheticRegistry },
);
- expect(pUnknown.models['claude-code']?.[0]?.efforts).not.toContain('ultra');
+ expect(pUnknown.models["claude-code"]?.[0]?.efforts).not.toContain("ultra");
// no prefix: should match directly
const pDirect = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { 'claude-code': { baseUrl: 'https://x/v1', models: [{ id: 'synthetic-gpt', name: 'G' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ "claude-code": {
+ baseUrl: "https://x/v1",
+ models: [{ id: "synthetic-gpt", name: "G" }],
+ },
+ },
+ },
{ modelRegistry: syntheticRegistry },
);
- expect(pDirect.models['claude-code']?.[0]?.efforts).toContain('ultra');
+ expect(pDirect.models["claude-code"]?.[0]?.efforts).toContain("ultra");
});
- it('Case A: exact match takes priority over prefix-stripped match (no ambiguity)', () => {
+ it("Case A: exact match takes priority over prefix-stripped match (no ambiguity)", () => {
// Registry has two entries:
// A: id='openai/foo', route.modelId='openai/foo', efforts=['ultra']
// B: id='other', route.modelId='foo', efforts=['low']
@@ -1066,84 +1134,120 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
// Stage 1 exact: matches A (entry.id='openai/foo') → unique → use A's efforts
// Without two-stage: both A and B match → ambiguous → fallback
const reg: ModelRegistry = {
- updatedAt: '2026-01-01T00:00:00Z',
+ updatedAt: "2026-01-01T00:00:00Z",
schemaVersion: 2,
models: [
{
- id: 'openai/foo', name: 'OpenAI Foo',
- efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
- defaultEffort: 'high',
- routes: [{ providerId: 'openai', modelId: 'openai/foo', agents: ['codex'] }],
+ id: "openai/foo",
+ name: "OpenAI Foo",
+ efforts: ["low", "medium", "high", "xhigh", "max", "ultra"],
+ defaultEffort: "high",
+ routes: [
+ { providerId: "openai", modelId: "openai/foo", agents: ["codex"] },
+ ],
},
{
- id: 'other', name: 'Other Foo',
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'low',
- routes: [{ providerId: 'other', modelId: 'foo', agents: ['codex'] }],
+ id: "other",
+ name: "Other Foo",
+ efforts: ["low", "medium", "high"],
+ defaultEffort: "low",
+ routes: [{ providerId: "other", modelId: "foo", agents: ["codex"] }],
},
],
};
const p = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { codex: { baseUrl: 'https://x/v1', models: [{ id: 'openai/foo', name: 'F' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ codex: {
+ baseUrl: "https://x/v1",
+ models: [{ id: "openai/foo", name: "F" }],
+ },
+ },
+ },
{ modelRegistry: reg },
);
// Must select entry A (exact match), not ambiguous fallback
- expect(p.models.codex?.[0]?.efforts).toContain('ultra');
- expect(p.models.codex?.[0]?.defaultEffort).toBe('high');
+ expect(p.models.codex?.[0]?.efforts).toContain("ultra");
+ expect(p.models.codex?.[0]?.defaultEffort).toBe("high");
});
- it('Case B: no exact match → prefix fallback finds unique entry', () => {
+ it("Case B: no exact match → prefix fallback finds unique entry", () => {
// No entry with id='openai/bar' or route.modelId='openai/bar'
// But route.modelId='bar' exists → strip openai/ to find it
const reg: ModelRegistry = {
- updatedAt: '2026-01-01T00:00:00Z',
+ updatedAt: "2026-01-01T00:00:00Z",
schemaVersion: 2,
models: [
{
- id: 'registry-bar', name: 'Registry Bar',
- efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
- defaultEffort: 'max',
- routes: [{ providerId: 'test', modelId: 'bar', agents: ['claude-code'] }],
+ id: "registry-bar",
+ name: "Registry Bar",
+ efforts: ["low", "medium", "high", "xhigh", "max", "ultra"],
+ defaultEffort: "max",
+ routes: [
+ { providerId: "test", modelId: "bar", agents: ["claude-code"] },
+ ],
},
],
};
const p = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { 'claude-code': { baseUrl: 'https://x/v1', models: [{ id: 'openai/bar', name: 'B' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ "claude-code": {
+ baseUrl: "https://x/v1",
+ models: [{ id: "openai/bar", name: "B" }],
+ },
+ },
+ },
{ modelRegistry: reg },
);
// Stage 1: no exact match for 'openai/bar'
// Stage 2: strip openai/ → 'bar' → matches route.modelId → unique
- expect(p.models['claude-code']?.[0]?.efforts).toContain('ultra');
- expect(p.models['claude-code']?.[0]?.defaultEffort).toBe('max');
+ expect(p.models["claude-code"]?.[0]?.efforts).toContain("ultra");
+ expect(p.models["claude-code"]?.[0]?.defaultEffort).toBe("max");
});
- it('Case C: no exact match → prefix fallback yields ambiguity → CUSTOM_EFFORTS', () => {
+ it("Case C: no exact match → prefix fallback yields ambiguity → CUSTOM_EFFORTS", () => {
// Two entries both have route.modelId='baz' after stripping openai/
const reg: ModelRegistry = {
- updatedAt: '2026-01-01T00:00:00Z',
+ updatedAt: "2026-01-01T00:00:00Z",
schemaVersion: 2,
models: [
{
- id: 'entry-1', name: 'E1',
- efforts: ['low', 'ultra'],
- routes: [{ providerId: 'p1', modelId: 'baz', agents: ['codex'] }],
+ id: "entry-1",
+ name: "E1",
+ efforts: ["low", "ultra"],
+ routes: [{ providerId: "p1", modelId: "baz", agents: ["codex"] }],
},
{
- id: 'entry-2', name: 'E2',
- efforts: ['low', 'high'],
- routes: [{ providerId: 'p2', modelId: 'baz', agents: ['codex'] }],
+ id: "entry-2",
+ name: "E2",
+ efforts: ["low", "high"],
+ routes: [{ providerId: "p2", modelId: "baz", agents: ["codex"] }],
},
],
};
const p = buildUserProvider(
- { id: 'relay', name: 'R', runtimes: { codex: { baseUrl: 'https://x/v1', models: [{ id: 'openai/baz', name: 'B' }] } } },
+ {
+ id: "relay",
+ name: "R",
+ runtimes: {
+ codex: {
+ baseUrl: "https://x/v1",
+ models: [{ id: "openai/baz", name: "B" }],
+ },
+ },
+ },
{ modelRegistry: reg },
);
// Ambiguous → falls back to CUSTOM_EFFORTS (no 'ultra')
- expect(p.models.codex?.[0]?.efforts).not.toContain('ultra');
+ expect(p.models.codex?.[0]?.efforts).not.toContain("ultra");
});
- it('exports only the explicitly supported effort levels for a Pi reasoning model', () => {
+ it("exports only the explicitly supported effort levels for a Pi reasoning model", () => {
const p = buildUserProvider({
id: "reasoning-pi",
name: "Reasoning Pi",
@@ -1223,36 +1327,134 @@ it('strips xd/ prefix to match registry effort metadata (entry.id ≠ custom id)
});
});
-
-describe('custom model defaults with partial registry metadata', () => {
+describe("custom model defaults with partial registry metadata", () => {
it.each([
- [undefined, 'medium'],
+ [undefined, "medium"],
[null, null],
- ['max', 'high'],
- ] as const)('keeps the route usable with declared default %s', (declared, expected) => {
- const modelRegistry: ModelRegistry = {
- schemaVersion: 2,
- updatedAt: '2026-09-05T00:00:00Z',
- models: [{
- id: 'sparse-model', name: 'Sparse model',
- efforts: ['low', 'medium', 'high'],
- routes: [{ providerId: 'relay', modelId: 'sparse-model', agents: ['codex'] }],
- }],
+ ["max", "high"],
+ ] as const)(
+ "keeps the route usable with declared default %s",
+ (declared, expected) => {
+ const modelRegistry: ModelRegistry = {
+ schemaVersion: 2,
+ updatedAt: "2026-09-05T00:00:00Z",
+ models: [
+ {
+ id: "sparse-model",
+ name: "Sparse model",
+ efforts: ["low", "medium", "high"],
+ routes: [
+ {
+ providerId: "relay",
+ modelId: "sparse-model",
+ agents: ["codex"],
+ },
+ ],
+ },
+ ],
+ };
+ if (declared === null) {
+ modelRegistry.models[0].defaultEffort = declared;
+ } else if (declared !== undefined) {
+ modelRegistry.models[0].defaultEffort = declared;
+ }
+ const provider = buildUserProvider(
+ {
+ id: "relay",
+ name: "Custom relay",
+ runtimes: {
+ codex: {
+ baseUrl: "https://relay.example/v1",
+ models: [{ id: "sparse-model", name: "My model" }],
+ },
+ },
+ },
+ { modelRegistry },
+ );
+ expect(provider.models.codex).toHaveLength(1);
+ expect(provider.models.codex?.[0]).toMatchObject({
+ id: "sparse-model",
+ name: "My model",
+ efforts: ["low", "medium", "high"],
+ defaultEffort: expected,
+ });
+ expect(provider.routing.codex?.upstream).toBe("https://relay.example/v1");
+ },
+ );
+});
+
+describe("live preset defaults and discovery provenance", () => {
+ it("follows changed preset defaults, lets discovery/user values win and detaches on endpoint edits", () => {
+ const config: CustomProviderConfig = {
+ id: "my-connection",
+ name: "My connection",
+ runtimes: {
+ pi: {
+ catalogPresetId: "supplier",
+ baseUrl: "https://supplier.example/v1",
+ wireProtocol: "openai-chat",
+ models: [{ id: "model", name: "Model", discoveredMetadata: {} }],
+ },
+ },
};
- if (declared === null) {
- // @ts-expect-error Exercise malformed registry metadata outside the wire contract.
- modelRegistry.models[0].defaultEffort = declared;
- } else if (declared !== undefined) {
- modelRegistry.models[0].defaultEffort = declared;
- }
- const provider = buildUserProvider({
- id: 'relay', name: 'Custom relay',
- runtimes: { codex: { baseUrl: 'https://relay.example/v1', models: [{ id: 'sparse-model', name: 'My model' }] } },
- }, { modelRegistry });
- expect(provider.models.codex).toHaveLength(1);
- expect(provider.models.codex?.[0]).toMatchObject({
- id: 'sparse-model', name: 'My model', efforts: ['low', 'medium', 'high'], defaultEffort: expected,
+ const presets = [
+ {
+ id: "supplier",
+ name: "Supplier",
+ runtimes: {
+ pi: {
+ baseUrl: "https://supplier.example/v1",
+ wireProtocol: "openai-chat" as const,
+ models: [
+ {
+ id: "model",
+ name: "Current default",
+ contextWindow: 1000,
+ supportsImageInput: true,
+ },
+ ],
+ },
+ },
+ },
+ ];
+ const current = () =>
+ buildUserProvider(config, {
+ presets,
+ modelRegistry: {
+ schemaVersion: 4,
+ updatedAt: "2026-09-08T07:00:00.000Z",
+ models: [],
+ },
+ }).models.pi![0];
+ expect(current()).toMatchObject({
+ contextWindow: 1000,
+ name: "Current default",
+ supportsImageInput: true,
+ contextWindowVerified: true,
+ });
+ expect(current().contextWindowExplicit).toBeUndefined();
+ config.runtimes.pi!.baseUrl += "/".repeat(100_000);
+ presets[0].runtimes.pi.baseUrl += "/";
+ expect(current().contextWindow).toBe(1000);
+ presets[0].runtimes.pi.models[0].contextWindow = 2000;
+ expect(current().contextWindow).toBe(2000);
+ config.runtimes.pi!.models[0].discoveredMetadata = {
+ contextWindow: 3000,
+ supportsImageInput: false,
+ };
+ expect(current()).toMatchObject({
+ contextWindow: 3000,
+ supportsImageInput: false,
+ });
+ config.runtimes.pi!.models[0].contextWindow = 4000;
+ expect(current()).toMatchObject({
+ contextWindow: 4000,
+ contextWindowExplicit: true,
});
- expect(provider.routing.codex?.upstream).toBe('https://relay.example/v1');
+ delete config.runtimes.pi!.models[0].contextWindow;
+ config.runtimes.pi!.models[0].discoveredMetadata = {};
+ config.runtimes.pi!.baseUrl = "https://different.example/v1";
+ expect(current().contextWindow).toBe(DEFAULT_CUSTOM_CONTEXT_WINDOW);
+ expect(current().supportsImageInput).toBeUndefined();
});
});
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index ead306829b..af4a0a82f9 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -35,22 +35,29 @@ export type {
OAuthAuthorizationCodeDescriptor,
OAuthDeviceCodeDescriptor,
OAuthProviderDescriptor,
-} from './types.js';
+} from "./types.js";
-export { PI_MODEL_APIS, PI_REASONING_EFFORTS } from './types.js';
+export { PI_MODEL_APIS, PI_REASONING_EFFORTS } from "./types.js";
export {
effectivePiWireProtocol,
preservesPiCatalogModels,
resolvePiModelRoute,
resolvePiModelWireProtocol,
-} from './pi-catalog-marker.js';
-export type { ResolvedPiModelRoute } from './pi-catalog-marker.js';
+} from "./pi-catalog-marker.js";
+export type { ResolvedPiModelRoute } from "./pi-catalog-marker.js";
-export { resolveCodexCompatibilityWireProtocol } from './codexCompatibility.js';
-export { modelProtocolComparison } from './modelProtocol.js';
+export { resolveCodexCompatibilityWireProtocol } from "./codexCompatibility.js";
+export { modelProtocolComparison } from "./modelProtocol.js";
-export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForRegion } from './catalog.js';
+export {
+ BUNDLED_CATALOG,
+ BUILTIN_PROVIDERS,
+ parseCatalog,
+ presetDisplayName,
+ sanitizePresets,
+ sortPresetsForRegion,
+} from "./catalog.js";
export {
buildUserProvider,
@@ -61,13 +68,13 @@ export {
storedCustomProviderId,
xaiApiOfficialRuntimeAgents,
XAI_API_CUSTOM_PROVIDER_ID,
-} from './user-provider.js';
+} from "./user-provider.js";
export {
appendProviderRequestPath,
isLoopbackProviderUrl,
isProviderRequestPath,
-} from './provider-url.js';
-export { findReservedOAuthExtraParam } from './provider-oauth.js';
+} from "./provider-url.js";
+export { findReservedOAuthExtraParam } from "./provider-oauth.js";
export {
CATALOG_API_PATH,
@@ -78,7 +85,7 @@ export {
mergeWithBundled,
loadCatalog,
loadCatalogWithSource,
-} from './source.js';
+} from "./source.js";
export {
compareModelRegistryRevisions,
@@ -86,20 +93,20 @@ export {
findModelRegistryRoute,
resolveModelNativeApi,
resolveModelReferencePrice,
-} from './modelRegistry.js';
-export { modelRegistryCanonicalJson } from './modelRegistryCanonical.js';
+} from "./modelRegistry.js";
+export { modelRegistryCanonicalJson } from "./modelRegistryCanonical.js";
export {
isModelCurrency,
parseListModelsResponse,
parseModelRegistry,
-} from './modelAccessValidator.js';
+} from "./modelAccessValidator.js";
export type {
ResolvedModelReferencePrice,
ResolveModelReferencePriceOptions,
ModelRegistryRevisionRelation,
ModelRegistrySnapshotDecision,
-} from './modelRegistry.js';
-export * from './modelAccessBean.js';
+} from "./modelRegistry.js";
+export * from "./modelAccessBean.js";
export type {
CatalogSourceConfig,
CatalogIO,
@@ -107,7 +114,7 @@ export type {
CatalogXdMediaKind,
CatalogLoadResult,
CatalogLoadSource,
-} from './source.js';
+} from "./source.js";
export {
buildRegistry,
@@ -123,7 +130,7 @@ export {
resolveRoute,
modelSupportsFastMode,
sessionModelSupportsFastMode,
-} from './registry.js';
+} from "./registry.js";
export type {
ConnectionState,
ModelDiscoveryFailureState,
@@ -131,18 +138,27 @@ export type {
ProviderModelDiscoveryFailureView,
ProviderView,
ResolvedRoute,
-} from './registry.js';
+} from "./registry.js";
export {
modelDisableKey,
isModelDisabled,
isModelDisabledWithUniqueLegacyBasename,
isProviderDisabled,
-} from './disableOverrides.js';
-export type { ModelDisableOverrides } from './disableOverrides.js';
+} from "./disableOverrides.js";
+export type { ModelDisableOverrides } from "./disableOverrides.js";
-export { isModelVisible, buildProviderSections, visibleModelUnion, resolveModelIconKind } from './sections.js';
-export type { SectionModel, ProviderSection, ModelIconKind } from './sections.js';
+export {
+ isModelVisible,
+ buildProviderSections,
+ visibleModelUnion,
+ resolveModelIconKind,
+} from "./sections.js";
+export type {
+ SectionModel,
+ ProviderSection,
+ ModelIconKind,
+} from "./sections.js";
export {
modelDefaultEffort,
@@ -158,20 +174,20 @@ export {
lowestEffort,
nearestSupportedEffort,
reconcileInvocationEffort,
-} from './effortResolution.js';
-export { piSupportedEfforts } from './piThinkingLevels.mjs';
+} from "./effortResolution.js";
+export { piSupportedEfforts } from "./piThinkingLevels.mjs";
// ── 模型调用标准(2026-07 统一层)─────────────────────────────────────────────
// 清单派生 / 分类徽章 / 调用合成的单点语义,desktop renderer+main 与 mobile 的全部
// 模型消费面分期收口到这里(见 modelList.ts / classification.ts / invocation.ts 头注)。
-export { deriveModelList, deriveModelSections } from './modelList.js';
+export { deriveModelList, deriveModelSections } from "./modelList.js";
export type {
ModelSourceMeta,
ModelListEntry,
ModelListSection,
DeriveModelListOptions,
ProviderScope,
-} from './modelList.js';
+} from "./modelList.js";
export {
CHATGPT_MODEL_PREFIX,
@@ -193,8 +209,12 @@ export {
isBudgetModel,
modelBadges,
formatContextWindow,
-} from './classification.js';
-export type { ModelCategory, DisplayModel, ModelBadges } from './classification.js';
+} from "./classification.js";
+export type {
+ ModelCategory,
+ DisplayModel,
+ ModelBadges,
+} from "./classification.js";
// 统一模型选择器(模型优先)M1:推荐引擎推导 + 跨引擎联合列表(纯逻辑)。
// 规格 docs/product-rules/model-selector-unified.md §2.1 / §2.2 / §4。
@@ -213,27 +233,58 @@ export {
unifiedModelEntries,
partitionEntriesByNativeAgent,
sortEntriesForAgent,
-} from './unifiedSelection.js';
+} from "./unifiedSelection.js";
export type {
SourceResolutionScope,
CandidateAgentsOptions,
UnifiedAgentCapability,
UnifiedModelEntry,
UnifiedModelEntriesOptions,
-} from './unifiedSelection.js';
+} from "./unifiedSelection.js";
-export { resolveModelInvocation } from './invocation.js';
+export { resolveModelInvocation } from "./invocation.js";
export type {
InvocationPreferences,
ScenarioDefaults,
InvocationCatalogContext,
ResolvedInvocation,
-} from './invocation.js';
+} from "./invocation.js";
export {
classifyVisionCapability,
isKnownNoVisionModel,
isKnownVisionModel,
normalizeVisionModelId,
-} from './visionCapability.js';
-export type { VisionCapability } from './visionCapability.js';
+} from "./visionCapability.js";
+export type { VisionCapability } from "./visionCapability.js";
+
+export {
+ parseLocalModelCatalog,
+ isLocalModelLibraryName,
+} from "./localModelCatalog.js";
+export type {
+ LocalModelCatalog,
+ LocalCatalogModel,
+ LocalModelVariant,
+} from "./localModelCatalog.js";
+
+export {
+ resolveModelMetadata,
+ findBaseModel,
+ registryEntryDefaults,
+ expandedRegistryEntries,
+ pickModelMetadata,
+ validModelMetadata,
+ mergeModelMetadata,
+} from "./modelMetadataLayers.js";
+export type { ModelMetadata, BaseModel } from "./modelMetadataLayers.js";
+
+export {
+ catalogModelMetadata,
+ applyModelMetadata,
+} from "./modelMetadataLayers.js";
+
+export { mergeDiscoveredRuntimeModels } from "./modelMetadataLayers.js";
+export type { DiscoveredModel } from "./modelMetadataLayers.js";
+
+export { runtimeUserModelMetadata } from "./modelMetadataLayers.js";
diff --git a/packages/model-providers/src/localModelCatalog.ts b/packages/model-providers/src/localModelCatalog.ts
new file mode 100644
index 0000000000..1cad9081b9
--- /dev/null
+++ b/packages/model-providers/src/localModelCatalog.ts
@@ -0,0 +1,172 @@
+/** Registry V4 local-model curation. Data only; execution stays in the client. */
+export interface LocalModelVariant {
+ libraryName: string;
+ sizeBytes: number;
+ minUnifiedMemoryGb: number;
+ appleSiliconOnly?: boolean;
+}
+export interface LocalCatalogModel {
+ modelRef?: string;
+ id: string;
+ name: string;
+ aliases: string[];
+ variants: LocalModelVariant[];
+ descriptions?: Partial<
+ Record<"en" | "zh-CN" | "zh-TW" | "ja" | "ko", string>
+ >;
+ /** Existing client implementation, never executable server instructions. */
+ runtimeProfile?: "plain" | "qwen-xhigh";
+ evidence?: {
+ url: string;
+ verifiedAt: string;
+ status: "measured" | "estimated" | "pending";
+ }[];
+}
+export interface LocalModelCatalog {
+ version: 1;
+ models: LocalCatalogModel[];
+ /** Ordered capability/speed picks; empty explicitly withdraws recommendations. */
+ featuredIds: string[];
+}
+const object = (v: unknown): v is Record<string, unknown> =>
+ Boolean(v) && typeof v === "object" && !Array.isArray(v);
+const fields = (v: Record<string, unknown>, keys: string[]) =>
+ Object.keys(v).every((key) => keys.includes(key));
+const string = (v: unknown, max: number): v is string =>
+ typeof v === "string" && v.trim().length > 0 && v.length <= max;
+const id = (v: unknown): v is string =>
+ typeof v === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(v);
+const https = (v: unknown) => {
+ if (!string(v, 2048)) return false;
+ try {
+ const url = new URL(v);
+ return url.protocol === "https:" && !url.username && !url.password;
+ } catch {
+ return false;
+ }
+};
+export function isLocalModelLibraryName(v: unknown): v is string {
+ return (
+ typeof v === "string" &&
+ v.length <= 256 &&
+ /^(?:[a-zA-Z0-9][a-zA-Z0-9._-]*\/)?[a-zA-Z0-9][a-zA-Z0-9._-]*:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(
+ v,
+ )
+ );
+}
+/** Reject the entire invalid snapshot so it can never replace a good cached catalog. */
+export function parseLocalModelCatalog(v: unknown): LocalModelCatalog | null {
+ if (
+ !object(v) ||
+ !fields(v, ["version", "models", "featuredIds"]) ||
+ v.version !== 1 ||
+ !Array.isArray(v.models) ||
+ v.models.length > 32 ||
+ !Array.isArray(v.featuredIds) ||
+ v.featuredIds.length > 8 ||
+ !v.featuredIds.every(id)
+ )
+ return null;
+ const ids = new Set<string>();
+ const tags = new Set<string>();
+ for (const m of v.models) {
+ if (
+ !object(m) ||
+ !fields(m, [
+ "id",
+ "modelRef",
+ "name",
+ "aliases",
+ "variants",
+ "descriptions",
+ "runtimeProfile",
+ "evidence",
+ ]) ||
+ !id(m.id) ||
+ (m.modelRef !== undefined && !string(m.modelRef, 256)) ||
+ ids.has(m.id) ||
+ !string(m.name, 80) ||
+ !Array.isArray(m.aliases) ||
+ m.aliases.length > 16 ||
+ !m.aliases.every((a) => string(a, 40)) ||
+ !Array.isArray(m.variants) ||
+ m.variants.length < 1 ||
+ m.variants.length > 8
+ )
+ return null;
+ ids.add(m.id);
+ for (const tag of m.variants) {
+ if (
+ !object(tag) ||
+ !fields(tag, [
+ "libraryName",
+ "sizeBytes",
+ "minUnifiedMemoryGb",
+ "appleSiliconOnly",
+ ]) ||
+ !isLocalModelLibraryName(tag.libraryName) ||
+ tags.has(tag.libraryName) ||
+ typeof tag.sizeBytes !== "number" ||
+ !Number.isSafeInteger(tag.sizeBytes) ||
+ tag.sizeBytes < 1024 ** 3 ||
+ tag.sizeBytes > 512 * 1024 ** 3 ||
+ typeof tag.minUnifiedMemoryGb !== "number" ||
+ !Number.isInteger(tag.minUnifiedMemoryGb) ||
+ tag.minUnifiedMemoryGb < 4 ||
+ tag.minUnifiedMemoryGb > 1024 ||
+ (tag.appleSiliconOnly !== undefined &&
+ typeof tag.appleSiliconOnly !== "boolean")
+ )
+ return null;
+ if (
+ /(?:^|[-_.])mlx(?:$|[-_.])/.test(tag.libraryName.split(":")[1] ?? "") &&
+ tag.appleSiliconOnly !== true
+ )
+ return null;
+ tags.add(tag.libraryName);
+ }
+ if (
+ m.runtimeProfile !== undefined &&
+ !["plain", "qwen-xhigh"].includes(m.runtimeProfile as string)
+ )
+ return null;
+ if (
+ m.runtimeProfile === "qwen-xhigh" &&
+ !m.variants.every((tag) =>
+ ["qwen3.8:27b", "qwen3.8:27b-mlx", "qwen3.8:27b-mxfp8"].includes(
+ tag.libraryName,
+ ),
+ )
+ )
+ return null;
+ if (
+ m.descriptions !== undefined &&
+ (!object(m.descriptions) ||
+ !fields(m.descriptions, ["en", "zh-CN", "zh-TW", "ja", "ko"]) ||
+ !Object.values(m.descriptions).every((s) => string(s, 500)))
+ )
+ return null;
+ if (m.evidence !== undefined) {
+ if (!Array.isArray(m.evidence) || m.evidence.length > 8) return null;
+ for (const e of m.evidence) {
+ if (
+ !object(e) ||
+ !fields(e, ["url", "verifiedAt", "status"]) ||
+ !https(e.url) ||
+ typeof e.verifiedAt !== "string" ||
+ !/^\d{4}-\d{2}-\d{2}$/.test(e.verifiedAt) ||
+ !Number.isFinite(Date.parse(e.verifiedAt)) ||
+ new Date(e.verifiedAt).toISOString().slice(0, 10) !== e.verifiedAt ||
+ !["measured", "estimated", "pending"].includes(e.status as string)
+ )
+ return null;
+ }
+ }
+ }
+ if (
+ new Set(v.featuredIds).size !== v.featuredIds.length ||
+ !v.featuredIds.every((key) => ids.has(key))
+ )
+ return null;
+ return v as unknown as LocalModelCatalog;
+}
diff --git a/packages/model-providers/src/modelAccessBean.ts b/packages/model-providers/src/modelAccessBean.ts
index 98baf45321..83cb3d30d1 100644
--- a/packages/model-providers/src/modelAccessBean.ts
+++ b/packages/model-providers/src/modelAccessBean.ts
@@ -1,3 +1,5 @@
+import type { BaseModel, ModelMetadata } from "./modelMetadataLayers.js";
+import type { LocalModelCatalog } from "./localModelCatalog.js";
/**
* Client-owned DTOs for the Model Access HTTP/catalog boundary.
*
@@ -12,61 +14,73 @@ export const MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION = 2 as const;
export const MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION = 3 as const;
export const MODEL_ACCESS_CATALOG_SCHEMA_VERSION = 4 as const;
export const MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION = 5 as const;
-export const MODEL_ACCESS_MODELS_PATH = '/api/model-access/models' as const;
+export const MODEL_ACCESS_MODELS_PATH = "/api/model-access/models" as const;
-export const MODEL_ACCESS_CURRENCIES = ['CNY', 'USD'] as const;
+export const MODEL_ACCESS_CURRENCIES = ["CNY", "USD"] as const;
export type ModelCurrency = (typeof MODEL_ACCESS_CURRENCIES)[number];
-export const MODEL_ACCESS_V2_AGENTS = ['claude-code', 'codex'] as const;
-export const MODEL_ACCESS_AGENTS = ['claude-code', 'codex', 'pi'] as const;
+export const MODEL_ACCESS_V2_AGENTS = ["claude-code", "codex"] as const;
+export const MODEL_ACCESS_AGENTS = ["claude-code", "codex", "pi"] as const;
export type ModelAgent = (typeof MODEL_ACCESS_AGENTS)[number];
export type ModelAccessV2Agent = (typeof MODEL_ACCESS_V2_AGENTS)[number];
export const MODEL_ACCESS_WIRE_PROTOCOLS = [
- 'anthropic-messages',
- 'openai-responses',
- 'openai-completions',
- 'google-generative-ai',
+ "anthropic-messages",
+ "openai-responses",
+ "openai-completions",
+ "google-generative-ai",
] as const;
-export type ModelAccessWireProtocol = (typeof MODEL_ACCESS_WIRE_PROTOCOLS)[number];
+export type ModelAccessWireProtocol =
+ (typeof MODEL_ACCESS_WIRE_PROTOCOLS)[number];
export const MODEL_ACCESS_MEDIA_CAPABILITIES = [
- 'image.generate',
- 'image.edit',
- 'video.generate',
- 'video.image_to_video',
+ "image.generate",
+ "image.edit",
+ "video.generate",
+ "video.image_to_video",
] as const;
export type MediaCapability = (typeof MODEL_ACCESS_MEDIA_CAPABILITIES)[number];
export const MODEL_ACCESS_EFFORTS = [
- 'minimal',
- 'low',
- 'medium',
- 'high',
- 'xhigh',
- 'max',
- 'ultra',
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
] as const;
export type ModelEffort = (typeof MODEL_ACCESS_EFFORTS)[number];
export const MODEL_REGISTRY_LEGACY_SCHEMA_VERSION = 1 as const;
export const MODEL_REGISTRY_SCHEMA_VERSION = 2 as const;
export const MODEL_REGISTRY_V3_SCHEMA_VERSION = 3 as const;
+export const MODEL_REGISTRY_V4_SCHEMA_VERSION = 4 as const;
export const MODEL_NATIVE_APIS = [
- 'anthropic-messages',
- 'openai-responses',
- 'openai-completions',
- 'google-generative-ai',
+ "anthropic-messages",
+ "openai-responses",
+ "openai-completions",
+ "google-generative-ai",
] as const;
export type ModelNativeApi = (typeof MODEL_NATIVE_APIS)[number];
-export const MODEL_REGISTRY_STATUSES = ['preview', 'active', 'deprecated', 'retired'] as const;
+export const MODEL_REGISTRY_STATUSES = [
+ "preview",
+ "active",
+ "deprecated",
+ "retired",
+] as const;
export type ModelRegistryStatus = (typeof MODEL_REGISTRY_STATUSES)[number];
-export const MODEL_PRICE_VARIANTS = ['standard', 'priority', 'batch', 'fast'] as const;
+export const MODEL_PRICE_VARIANTS = [
+ "standard",
+ "priority",
+ "batch",
+ "fast",
+] as const;
export type ModelPriceVariant = (typeof MODEL_PRICE_VARIANTS)[number];
export interface ModelReferencePriceSource {
- kind: 'provider-official';
+ kind: "provider-official";
url: string;
verifiedAt: string;
}
@@ -87,6 +101,10 @@ export interface ModelReferencePrice {
}
export interface ModelRegistryRoute {
+ defaults?: ModelMetadata;
+ forceOverrides?: ModelMetadata;
+ overrideReason?: string;
+ overrideVerifiedAt?: string;
providerId: string;
modelId: string;
agents: ModelAccessV2Agent[];
@@ -103,6 +121,7 @@ export interface ModelAgentOverride {
}
interface ModelRegistryEntryBase {
+ modelRef?: string;
id: string;
name: string;
routes: ModelRegistryRoute[];
@@ -123,7 +142,22 @@ export interface ModelRegistryEntryV1 extends ModelRegistryEntryBase {
newSessionDefault?: never;
}
-export interface ModelRegistryEntry extends ModelRegistryEntryBase {
+export interface ModelRegistryAgentOverride extends Omit<
+ ModelAgentOverride,
+ "defaultEffort"
+> {
+ defaultEffort?: ModelEffort | null;
+}
+
+export interface ModelRegistryEntry extends Omit<
+ ModelRegistryEntryBase,
+ "defaultEffort" | "perAgent"
+> {
+ /** V4 entry-level image capability default. */
+ supportsImageInput?: boolean;
+ /** V4 only: null explicitly clears an inherited default. */
+ defaultEffort?: ModelEffort | null;
+ perAgent?: Partial<Record<ModelAgent, ModelRegistryAgentOverride>>;
newSessionDefault?: ModelAccessV2Agent[];
/** V3: model's canonical API, independent of any harness. Null explicitly means unverified. */
nativeApi?: ModelNativeApi | null;
@@ -143,7 +177,10 @@ export interface ModelRegistry extends ModelRegistryBase {
schemaVersion:
| typeof MODEL_REGISTRY_LEGACY_SCHEMA_VERSION
| typeof MODEL_REGISTRY_SCHEMA_VERSION
- | typeof MODEL_REGISTRY_V3_SCHEMA_VERSION;
+ | typeof MODEL_REGISTRY_V3_SCHEMA_VERSION
+ | typeof MODEL_REGISTRY_V4_SCHEMA_VERSION;
+ baseModels?: BaseModel[];
+ localModels?: LocalModelCatalog;
models: ModelRegistryEntry[];
/** V3: route-scoped rules for new members of established model families. */
nativeApiRules?: ModelNativeApiRule[];
@@ -210,7 +247,10 @@ export interface ModelModalities {
output: string[];
}
-interface ModelCatalogAgentOverride extends Omit<ModelAgentOverride, 'defaultEffort'> {
+interface ModelCatalogAgentOverride extends Omit<
+ ModelAgentOverride,
+ "defaultEffort"
+> {
/** Older Model Access responses use null to mean that no effort is preferred. */
defaultEffort?: ModelEffort | null;
}
@@ -245,8 +285,8 @@ export interface ModelCatalogEntry extends ModelCatalogEntryBase {
newSessionDefault?: ModelAgent[];
}
-export type ModelAccessAvailability = 'available' | 'requires_payment';
-export type ModelAccessAccountTier = 'free' | 'paid' | 'not_applicable';
+export type ModelAccessAvailability = "available" | "requires_payment";
+export type ModelAccessAccountTier = "free" | "paid" | "not_applicable";
export interface ModelCatalogEntryV5 extends ModelCatalogEntry {
availability: ModelAccessAvailability;
@@ -289,4 +329,5 @@ export interface ListModelsResponseV5 extends ListModelsResponse {
}
/** Result returned by local Model Access boundary parsers. */
-export type ModelAccessParseResult<T> = { ok: true; value: T } | { ok: false; error: string };
+export type ModelAccessParseResult<T> =
+ { ok: true; value: T } | { ok: false; error: string };
diff --git a/packages/model-providers/src/modelAccessValidator.ts b/packages/model-providers/src/modelAccessValidator.ts
index c0a5ead4af..924f4f7765 100644
--- a/packages/model-providers/src/modelAccessValidator.ts
+++ b/packages/model-providers/src/modelAccessValidator.ts
@@ -1,3 +1,8 @@
+import {
+ validModelMetadata,
+ expandedRegistryEntries,
+} from "./modelMetadataLayers.js";
+import { parseLocalModelCatalog } from "./localModelCatalog.js";
import {
MODEL_ACCESS_AGENTS,
MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
@@ -13,6 +18,7 @@ import {
MODEL_REGISTRY_LEGACY_SCHEMA_VERSION,
MODEL_REGISTRY_SCHEMA_VERSION,
MODEL_REGISTRY_V3_SCHEMA_VERSION,
+ MODEL_REGISTRY_V4_SCHEMA_VERSION,
MODEL_NATIVE_APIS,
MODEL_REGISTRY_STATUSES,
type ListModelsResponse,
@@ -23,135 +29,148 @@ import {
type ModelEffort,
type ModelPriceVariant,
type ModelRegistry,
+ type ModelRegistryEntry,
type ModelRegistryStatus,
-} from './modelAccessBean.js';
+} from "./modelAccessBean.js";
/** Local strict validator for untrusted Model Access catalog and Registry payloads. */
type PlainObject = Record<string, unknown>;
const PRICING_FIELDS = [
- 'costDiscount',
- 'inputCostPerToken',
- 'outputCostPerToken',
- 'inputCostPerTokenPriority',
- 'outputCostPerTokenPriority',
- 'cacheReadInputTokenCost',
- 'cacheReadInputTokenCostPriority',
- 'cacheCreationInputTokenCost',
- 'inputCostPerTokenAbove200kTokens',
- 'outputCostPerTokenAbove200kTokens',
- 'cacheReadInputTokenCostAbove200kTokens',
- 'inputCostPerTokenAbove200kTokensPriority',
- 'outputCostPerTokenAbove200kTokensPriority',
- 'cacheReadInputTokenCostAbove200kTokensPriority',
- 'inputCostPerTokenAbove272kTokens',
- 'outputCostPerTokenAbove272kTokens',
- 'cacheReadInputTokenCostAbove272kTokens',
- 'inputCostPerTokenAbove272kTokensPriority',
- 'outputCostPerTokenAbove272kTokensPriority',
- 'cacheReadInputTokenCostAbove272kTokensPriority',
- 'inputCostPerCharacter',
- 'outputCostPerCharacter',
- 'inputCostPerSecond',
- 'outputCostPerSecond',
- 'inputCostPerAudioToken',
- 'outputCostPerAudioToken',
- 'inputCostPerAudioPerSecond',
- 'outputCostPerAudioPerSecond',
- 'inputCostPerImage',
- 'outputCostPerImage',
- 'inputCostPerImageToken',
- 'outputCostPerImageToken',
- 'cacheReadInputImageTokenCost',
- 'inputCostPerVideoPerSecond',
- 'outputCostPerVideoPerSecond',
+ "costDiscount",
+ "inputCostPerToken",
+ "outputCostPerToken",
+ "inputCostPerTokenPriority",
+ "outputCostPerTokenPriority",
+ "cacheReadInputTokenCost",
+ "cacheReadInputTokenCostPriority",
+ "cacheCreationInputTokenCost",
+ "inputCostPerTokenAbove200kTokens",
+ "outputCostPerTokenAbove200kTokens",
+ "cacheReadInputTokenCostAbove200kTokens",
+ "inputCostPerTokenAbove200kTokensPriority",
+ "outputCostPerTokenAbove200kTokensPriority",
+ "cacheReadInputTokenCostAbove200kTokensPriority",
+ "inputCostPerTokenAbove272kTokens",
+ "outputCostPerTokenAbove272kTokens",
+ "cacheReadInputTokenCostAbove272kTokens",
+ "inputCostPerTokenAbove272kTokensPriority",
+ "outputCostPerTokenAbove272kTokensPriority",
+ "cacheReadInputTokenCostAbove272kTokensPriority",
+ "inputCostPerCharacter",
+ "outputCostPerCharacter",
+ "inputCostPerSecond",
+ "outputCostPerSecond",
+ "inputCostPerAudioToken",
+ "outputCostPerAudioToken",
+ "inputCostPerAudioPerSecond",
+ "outputCostPerAudioPerSecond",
+ "inputCostPerImage",
+ "outputCostPerImage",
+ "inputCostPerImageToken",
+ "outputCostPerImageToken",
+ "cacheReadInputImageTokenCost",
+ "inputCostPerVideoPerSecond",
+ "outputCostPerVideoPerSecond",
] as const;
-const LIST_MODELS_RESPONSE_FIELDS = ['schemaVersion', 'models'] as const;
+const LIST_MODELS_RESPONSE_FIELDS = ["schemaVersion", "models"] as const;
// v1 is frozen at its deployed wire shape. `mode` and `modalities` predate this
// shared parser and are listed explicitly so strict dual-reading does not reject
// current producers while still preventing fields from a different schema from
// being accepted under version 1.
const MODEL_CATALOG_ENTRY_V1_FIELDS = [
- 'id',
- 'mode',
- 'currency',
- 'agents',
- 'name',
- 'group',
- 'description',
- 'icon',
- 'contextWindow',
- 'maxOutputTokens',
- 'modalities',
- 'efforts',
- 'defaultEffort',
- 'sortOrder',
- 'supportsFastMode',
- 'defaultEnabled',
- 'perAgent',
+ "id",
+ "mode",
+ "currency",
+ "agents",
+ "name",
+ "group",
+ "description",
+ "icon",
+ "contextWindow",
+ "maxOutputTokens",
+ "modalities",
+ "efforts",
+ "defaultEffort",
+ "sortOrder",
+ "supportsFastMode",
+ "defaultEnabled",
+ "perAgent",
...PRICING_FIELDS,
- 'tieredPricing',
+ "tieredPricing",
] as const;
const MODEL_CATALOG_ENTRY_V2_FIELDS = [
...MODEL_CATALOG_ENTRY_V1_FIELDS,
- 'newSessionDefault',
+ "newSessionDefault",
] as const;
const MODEL_CATALOG_ENTRY_V3_FIELDS = MODEL_CATALOG_ENTRY_V2_FIELDS;
const MODEL_AGENT_OVERRIDE_FIELDS = [
- 'contextWindow',
- 'efforts',
- 'defaultEffort',
- 'supportsFastMode',
- 'defaultEnabled',
+ "contextWindow",
+ "efforts",
+ "defaultEffort",
+ "supportsFastMode",
+ "defaultEnabled",
+] as const;
+const MODEL_AGENT_OVERRIDE_V3_FIELDS = [
+ ...MODEL_AGENT_OVERRIDE_FIELDS,
+ "wireProtocol",
] as const;
-const MODEL_AGENT_OVERRIDE_V3_FIELDS = [...MODEL_AGENT_OVERRIDE_FIELDS, 'wireProtocol'] as const;
const MODEL_TIERED_PRICING_FIELDS = [
- 'range',
- 'inputCostPerToken',
- 'outputCostPerToken',
- 'cacheReadInputTokenCost',
- 'cacheCreationInputTokenCost',
+ "range",
+ "inputCostPerToken",
+ "outputCostPerToken",
+ "cacheReadInputTokenCost",
+ "cacheCreationInputTokenCost",
] as const;
-const MODEL_MODALITIES_FIELDS = ['input', 'output'] as const;
+const MODEL_MODALITIES_FIELDS = ["input", "output"] as const;
-const MODEL_REGISTRY_FIELDS = ['schemaVersion', 'updatedAt', 'models'] as const;
+const MODEL_REGISTRY_FIELDS = ["schemaVersion", "updatedAt", "models"] as const;
const MODEL_REGISTRY_ENTRY_V1_FIELDS = [
- 'id',
- 'name',
- 'routes',
- 'status',
- 'group',
- 'description',
- 'contextWindow',
- 'maxOutputTokens',
- 'efforts',
- 'defaultEffort',
- 'sortOrder',
- 'supportsFastMode',
- 'defaultEnabled',
- 'perAgent',
+ "id",
+ "name",
+ "routes",
+ "status",
+ "group",
+ "description",
+ "contextWindow",
+ "maxOutputTokens",
+ "efforts",
+ "defaultEffort",
+ "sortOrder",
+ "supportsFastMode",
+ "defaultEnabled",
+ "perAgent",
] as const;
const MODEL_REGISTRY_ENTRY_V2_FIELDS = [
...MODEL_REGISTRY_ENTRY_V1_FIELDS,
- 'newSessionDefault',
+ "newSessionDefault",
+] as const;
+const MODEL_REGISTRY_ROUTE_FIELDS = [
+ "providerId",
+ "modelId",
+ "agents",
+ "referencePrices",
] as const;
-const MODEL_REGISTRY_ROUTE_FIELDS = ['providerId', 'modelId', 'agents', 'referencePrices'] as const;
const MODEL_REFERENCE_PRICE_FIELDS = [
- 'currency',
- 'variant',
- 'inputPerMtok',
- 'outputPerMtok',
- 'cacheReadPerMtok',
- 'cacheWritePerMtok',
- 'cacheWrite1hPerMtok',
- 'minInputTokens',
- 'maxInputTokens',
- 'effectiveFrom',
- 'effectiveUntil',
- 'source',
+ "currency",
+ "variant",
+ "inputPerMtok",
+ "outputPerMtok",
+ "cacheReadPerMtok",
+ "cacheWritePerMtok",
+ "cacheWrite1hPerMtok",
+ "minInputTokens",
+ "maxInputTokens",
+ "effectiveFrom",
+ "effectiveUntil",
+ "source",
+] as const;
+const MODEL_REFERENCE_PRICE_SOURCE_FIELDS = [
+ "kind",
+ "url",
+ "verifiedAt",
] as const;
-const MODEL_REFERENCE_PRICE_SOURCE_FIELDS = ['kind', 'url', 'verifiedAt'] as const;
function ok<T>(value: T): ModelAccessParseResult<T> {
return { ok: true, value };
@@ -162,7 +181,7 @@ function fail<T>(error: string): ModelAccessParseResult<T> {
}
function isPlainObject(value: unknown): value is PlainObject {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
+ return typeof value === "object" && value !== null && !Array.isArray(value);
}
function unknownFieldError(
@@ -172,53 +191,82 @@ function unknownFieldError(
): string | null {
const allowed = new Set(allowedFields);
const unknown = Object.keys(value).find((field) => !allowed.has(field));
- return unknown ? `${path}.${unknown} is not allowed by this schema version` : null;
+ return unknown
+ ? `${path}.${unknown} is not allowed by this schema version`
+ : null;
}
export function isModelCurrency(value: unknown): value is ModelCurrency {
- return typeof value === 'string' && MODEL_ACCESS_CURRENCIES.includes(value as ModelCurrency);
+ return (
+ typeof value === "string" &&
+ MODEL_ACCESS_CURRENCIES.includes(value as ModelCurrency)
+ );
}
function isModelAgent(value: unknown): value is ModelAgent {
- return typeof value === 'string' && MODEL_ACCESS_AGENTS.includes(value as ModelAgent);
+ return (
+ typeof value === "string" &&
+ MODEL_ACCESS_AGENTS.includes(value as ModelAgent)
+ );
}
function isV2ModelAgent(value: unknown): value is ModelAccessV2Agent {
- return typeof value === 'string' && MODEL_ACCESS_V2_AGENTS.includes(value as never);
+ return (
+ typeof value === "string" && MODEL_ACCESS_V2_AGENTS.includes(value as never)
+ );
}
function isModelAccessWireProtocol(value: unknown): boolean {
- return typeof value === 'string' && MODEL_ACCESS_WIRE_PROTOCOLS.includes(value as never);
+ return (
+ typeof value === "string" &&
+ MODEL_ACCESS_WIRE_PROTOCOLS.includes(value as never)
+ );
}
function acceptsWireProtocol(agent: ModelAgent, protocol: unknown): boolean {
if (!isModelAccessWireProtocol(protocol)) return false;
- if (agent === 'pi') return true;
- return protocol === (agent === 'claude-code' ? 'anthropic-messages' : 'openai-responses');
+ if (agent === "pi") return true;
+ return (
+ protocol ===
+ (agent === "claude-code" ? "anthropic-messages" : "openai-responses")
+ );
}
function isModelEffort(value: unknown): value is ModelEffort {
- return typeof value === 'string' && MODEL_ACCESS_EFFORTS.includes(value as ModelEffort);
+ return (
+ typeof value === "string" &&
+ MODEL_ACCESS_EFFORTS.includes(value as ModelEffort)
+ );
}
function isModelRegistryStatus(value: unknown): value is ModelRegistryStatus {
return (
- typeof value === 'string' && MODEL_REGISTRY_STATUSES.includes(value as ModelRegistryStatus)
+ typeof value === "string" &&
+ MODEL_REGISTRY_STATUSES.includes(value as ModelRegistryStatus)
);
}
function isModelPriceVariant(value: unknown): value is ModelPriceVariant {
- return typeof value === 'string' && MODEL_PRICE_VARIANTS.includes(value as ModelPriceVariant);
+ return (
+ typeof value === "string" &&
+ MODEL_PRICE_VARIANTS.includes(value as ModelPriceVariant)
+ );
}
function isIsoDate(value: unknown): value is string {
- if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
+ return false;
const parsed = new Date(`${value}T00:00:00.000Z`);
- return Number.isFinite(parsed.getTime()) && parsed.toISOString().startsWith(value);
+ return (
+ Number.isFinite(parsed.getTime()) && parsed.toISOString().startsWith(value)
+ );
}
function isIsoTimestamp(value: unknown): value is string {
- if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) {
+ if (
+ typeof value !== "string" ||
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
+ ) {
return false;
}
const parsed = new Date(value);
@@ -227,13 +275,19 @@ function isIsoTimestamp(value: unknown): value is string {
function referencePriceRangesOverlap(a: PlainObject, b: PlainObject): boolean {
if (a.currency !== b.currency || a.variant !== b.variant) return false;
- const aMin = typeof a.minInputTokens === 'number' ? a.minInputTokens : 0;
- const bMin = typeof b.minInputTokens === 'number' ? b.minInputTokens : 0;
- const aMax = typeof a.maxInputTokens === 'number' ? a.maxInputTokens : Number.POSITIVE_INFINITY;
- const bMax = typeof b.maxInputTokens === 'number' ? b.maxInputTokens : Number.POSITIVE_INFINITY;
+ const aMin = typeof a.minInputTokens === "number" ? a.minInputTokens : 0;
+ const bMin = typeof b.minInputTokens === "number" ? b.minInputTokens : 0;
+ const aMax =
+ typeof a.maxInputTokens === "number"
+ ? a.maxInputTokens
+ : Number.POSITIVE_INFINITY;
+ const bMax =
+ typeof b.maxInputTokens === "number"
+ ? b.maxInputTokens
+ : Number.POSITIVE_INFINITY;
const tokenRangesOverlap = aMin < bMax && bMin < aMax;
- const aUntil = typeof a.effectiveUntil === 'string' ? a.effectiveUntil : null;
- const bUntil = typeof b.effectiveUntil === 'string' ? b.effectiveUntil : null;
+ const aUntil = typeof a.effectiveUntil === "string" ? a.effectiveUntil : null;
+ const bUntil = typeof b.effectiveUntil === "string" ? b.effectiveUntil : null;
const dateRangesOverlap =
(bUntil === null || String(a.effectiveFrom) < bUntil) &&
(aUntil === null || String(b.effectiveFrom) < aUntil);
@@ -241,27 +295,35 @@ function referencePriceRangesOverlap(a: PlainObject, b: PlainObject): boolean {
}
function isSafeSlug(value: unknown): value is string {
- return typeof value === 'string' && /^[a-zA-Z0-9_-]+$/.test(value);
+ return typeof value === "string" && /^[a-zA-Z0-9_-]+$/.test(value);
}
function isHttpsUrl(value: unknown): value is string {
- if (typeof value !== 'string') return false;
+ if (typeof value !== "string") return false;
try {
const url = new URL(value);
- return url.protocol === 'https:' && !url.username && !url.password;
+ return url.protocol === "https:" && !url.username && !url.password;
} catch {
return false;
}
}
-function optionalStringError(value: unknown, path: string, max: number): string | null {
+function optionalStringError(
+ value: unknown,
+ path: string,
+ max: number,
+): string | null {
if (value === undefined) return null;
- if (typeof value !== 'string') return `${path} must be a string when present`;
- if (value.length > max) return `${path} must contain at most ${max} characters`;
+ if (typeof value !== "string") return `${path} must be a string when present`;
+ if (value.length > max)
+ return `${path} must contain at most ${max} characters`;
return null;
}
-function optionalPositiveIntegerError(value: unknown, path: string): string | null {
+function optionalPositiveIntegerError(
+ value: unknown,
+ path: string,
+): string | null {
if (value === undefined) return null;
if (!Number.isInteger(value) || (value as number) <= 0) {
return `${path} must be a positive integer when present`;
@@ -275,7 +337,7 @@ function optionalFiniteNumberError(
options: { nonNegative?: boolean } = {},
): string | null {
if (value === undefined) return null;
- if (typeof value !== 'number' || !Number.isFinite(value)) {
+ if (typeof value !== "number" || !Number.isFinite(value)) {
return `${path} must be a finite number when present`;
}
if (options.nonNegative && value < 0) {
@@ -300,7 +362,7 @@ function modelModalitiesError(value: unknown, path: string): string | null {
for (const direction of MODEL_MODALITIES_FIELDS) {
if (
!Array.isArray(value[direction]) ||
- value[direction].some((item) => typeof item !== 'string')
+ value[direction].some((item) => typeof item !== "string")
) {
return `${path}.${direction} must be an array of strings`;
}
@@ -315,11 +377,17 @@ function overrideError(
allowedFields?: readonly string[],
allowNullDefaultEffort = false,
baseDefaultEffort?: ModelEffort | null,
+ validateDependencies = true,
): string | null {
if (!isPlainObject(value)) return `${path} must be an object`;
- let error = allowedFields ? unknownFieldError(value, allowedFields, path) : null;
+ let error = allowedFields
+ ? unknownFieldError(value, allowedFields, path)
+ : null;
if (error) return error;
- error = optionalPositiveIntegerError(value.contextWindow, `${path}.contextWindow`);
+ error = optionalPositiveIntegerError(
+ value.contextWindow,
+ `${path}.contextWindow`,
+ );
if (error) return error;
error = effortListError(value.efforts, `${path}.efforts`);
if (error) return error;
@@ -338,6 +406,7 @@ function overrideError(
? (value.efforts as ModelEffort[])
: baseEfforts;
if (
+ validateDependencies &&
isModelEffort(value.defaultEffort) &&
effectiveEfforts !== undefined &&
!effectiveEfforts.includes(value.defaultEffort)
@@ -345,6 +414,7 @@ function overrideError(
return `${path}.defaultEffort must be included in ${path}.efforts or the base efforts`;
}
if (
+ validateDependencies &&
value.defaultEffort === undefined &&
isModelEffort(baseDefaultEffort) &&
effectiveEfforts !== undefined &&
@@ -352,8 +422,8 @@ function overrideError(
) {
return `${path}.efforts must include the inherited base defaultEffort`;
}
- for (const key of ['supportsFastMode', 'defaultEnabled'] as const) {
- if (value[key] !== undefined && typeof value[key] !== 'boolean') {
+ for (const key of ["supportsFastMode", "defaultEnabled"] as const) {
+ if (value[key] !== undefined && typeof value[key] !== "boolean") {
return `${path}.${key} must be a boolean when present`;
}
}
@@ -366,26 +436,36 @@ function tieredPricingError(value: unknown, path: string): string | null {
for (const [index, tier] of value.entries()) {
const tierPath = `${path}[${index}]`;
if (!isPlainObject(tier)) return `${tierPath} must be an object`;
- const unknownField = unknownFieldError(tier, MODEL_TIERED_PRICING_FIELDS, tierPath);
+ const unknownField = unknownFieldError(
+ tier,
+ MODEL_TIERED_PRICING_FIELDS,
+ tierPath,
+ );
if (unknownField) return unknownField;
if (
!Array.isArray(tier.range) ||
tier.range.length !== 2 ||
- tier.range.some((bound) => typeof bound !== 'number' || !Number.isFinite(bound)) ||
+ tier.range.some(
+ (bound) => typeof bound !== "number" || !Number.isFinite(bound),
+ ) ||
tier.range[0] < 0 ||
tier.range[1] < tier.range[0]
) {
return `${tierPath}.range must be an ascending pair of non-negative finite numbers`;
}
for (const field of [
- 'inputCostPerToken',
- 'outputCostPerToken',
- 'cacheReadInputTokenCost',
- 'cacheCreationInputTokenCost',
+ "inputCostPerToken",
+ "outputCostPerToken",
+ "cacheReadInputTokenCost",
+ "cacheCreationInputTokenCost",
] as const) {
- const error = optionalFiniteNumberError(tier[field], `${tierPath}.${field}`, {
- nonNegative: true,
- });
+ const error = optionalFiniteNumberError(
+ tier[field],
+ `${tierPath}.${field}`,
+ {
+ nonNegative: true,
+ },
+ );
if (error) return error;
}
}
@@ -403,7 +483,8 @@ function newSessionDefaultError(
}
const seen = new Set<ModelAgent>();
for (const agent of value) {
- if (!isModelAgent(agent)) return `${path} must contain only supported agents`;
+ if (!isModelAgent(agent))
+ return `${path} must contain only supported agents`;
if (seen.has(agent)) return `${path} must not contain duplicates`;
seen.add(agent);
if (!supportedAgents.has(agent)) {
@@ -433,7 +514,11 @@ function modelEntryError(
path,
);
if (error) return error;
- if (typeof value.id !== 'string' || value.id.length === 0 || value.id.length > 256) {
+ if (
+ typeof value.id !== "string" ||
+ value.id.length === 0 ||
+ value.id.length > 256
+ ) {
return `${path}.id must be a non-empty string of at most 256 characters`;
}
error = optionalStringError(value.mode, `${path}.mode`, 128);
@@ -460,7 +545,9 @@ function modelEntryError(
) {
return `${path}.agents must be an array of supported agents when present`;
}
- const supportedAgents = Array.isArray(value.agents) ? (value.agents as ModelAgent[]) : [];
+ const supportedAgents = Array.isArray(value.agents)
+ ? (value.agents as ModelAgent[])
+ : [];
if (schemaVersion !== MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION) {
const defaultError = newSessionDefaultError(
value.newSessionDefault,
@@ -471,9 +558,9 @@ function modelEntryError(
}
const isV4StandaloneModel =
schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION &&
- (value.mode === 'image_generation' ||
- value.mode === 'video_generation' ||
- value.mode === 'embedding');
+ (value.mode === "image_generation" ||
+ value.mode === "video_generation" ||
+ value.mode === "embedding");
if (isV4StandaloneModel && supportedAgents.length > 0) {
return `${path}.agents must be empty for a v4 Gateway standalone capability mode`;
}
@@ -487,9 +574,9 @@ function modelEntryError(
}
for (const [key, max] of [
- ['name', 256],
- ['group', 128],
- ['description', 2_000],
+ ["name", 256],
+ ["group", 128],
+ ["description", 2_000],
] as const) {
const error = optionalStringError(value[key], `${path}.${key}`, max);
if (error) return error;
@@ -497,23 +584,24 @@ function modelEntryError(
if (
(schemaVersion === MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION ||
schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION) &&
- (typeof value.name !== 'string' || value.name.trim().length === 0)
+ (typeof value.name !== "string" || value.name.trim().length === 0)
) {
return `${path}.name must be a non-empty string in schema version 3 or 4`;
}
if (
value.icon !== undefined &&
- (typeof value.icon !== 'string' || value.icon.trim().length === 0)
+ (typeof value.icon !== "string" || value.icon.trim().length === 0)
) {
return `${path}.icon must be a non-empty string when present`;
}
- for (const key of ['contextWindow', 'maxOutputTokens'] as const) {
+ for (const key of ["contextWindow", "maxOutputTokens"] as const) {
const error = optionalPositiveIntegerError(value[key], `${path}.${key}`);
if (error) return error;
}
if (
(schemaVersion === MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION ||
- (schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION && !isV4StandaloneModel)) &&
+ (schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION &&
+ !isV4StandaloneModel)) &&
value.contextWindow === undefined
) {
return `${path}.contextWindow is required for schema version 3 and v4 chat models`;
@@ -542,15 +630,15 @@ function modelEntryError(
}
error = optionalFiniteNumberError(value.sortOrder, `${path}.sortOrder`);
if (error) return error;
- for (const key of ['supportsFastMode', 'defaultEnabled'] as const) {
- if (value[key] !== undefined && typeof value[key] !== 'boolean') {
+ for (const key of ["supportsFastMode", "defaultEnabled"] as const) {
+ if (value[key] !== undefined && typeof value[key] !== "boolean") {
return `${path}.${key} must be a boolean when present`;
}
}
for (const field of PRICING_FIELDS) {
error = optionalFiniteNumberError(value[field], `${path}.${field}`, {
- nonNegative: field !== 'costDiscount',
+ nonNegative: field !== "costDiscount",
});
if (error) return error;
}
@@ -558,14 +646,16 @@ function modelEntryError(
if (error) return error;
if (value.perAgent !== undefined) {
- if (!isPlainObject(value.perAgent)) return `${path}.perAgent must be an object when present`;
+ if (!isPlainObject(value.perAgent))
+ return `${path}.perAgent must be an object when present`;
for (const [agent, override] of Object.entries(value.perAgent)) {
const supportedAgent =
schemaVersion === MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION ||
schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION
? isModelAgent(agent)
: isV2ModelAgent(agent);
- if (!supportedAgent) return `${path}.perAgent.${agent} is not a supported agent`;
+ if (!supportedAgent)
+ return `${path}.perAgent.${agent} is not a supported agent`;
if (!supportedAgents.includes(agent as ModelAgent)) {
return `${path}.perAgent.${agent} must be included in ${path}.agents`;
}
@@ -582,19 +672,25 @@ function modelEntryError(
);
if (error) return error;
if (
- agent === 'pi' &&
+ agent === "pi" &&
isPlainObject(override) &&
override.wireProtocol !== undefined &&
- (typeof override.wireProtocol !== 'string' || override.wireProtocol.trim().length === 0)
+ (typeof override.wireProtocol !== "string" ||
+ override.wireProtocol.trim().length === 0)
) {
return `${path}.perAgent.pi.wireProtocol must be a non-empty string when present`;
}
- if (agent !== 'pi' && isPlainObject(override) && override.wireProtocol !== undefined) {
+ if (
+ agent !== "pi" &&
+ isPlainObject(override) &&
+ override.wireProtocol !== undefined
+ ) {
if (!isModelAccessWireProtocol(override.wireProtocol)) {
return `${path}.perAgent.${agent}.wireProtocol must be a supported wire protocol`;
}
if (!acceptsWireProtocol(agent as ModelAgent, override.wireProtocol)) {
- const expected = agent === 'claude-code' ? 'anthropic-messages' : 'openai-responses';
+ const expected =
+ agent === "claude-code" ? "anthropic-messages" : "openai-responses";
return `${path}.perAgent.${agent}.wireProtocol must be ${expected}`;
}
}
@@ -608,9 +704,14 @@ function modelEntryError(
// Pi accepts a missing/future string here because Cindy Server and the local Pi catalog are
// higher authorities; an unsupported last-priority Gateway hint only closes that model route.
// Claude and Codex have no such fallback and remain strict contract requirements.
- if (agent === 'pi') continue;
- const override = isPlainObject(value.perAgent) ? value.perAgent[agent] : undefined;
- if (!isPlainObject(override) || !isModelAccessWireProtocol(override.wireProtocol)) {
+ if (agent === "pi") continue;
+ const override = isPlainObject(value.perAgent)
+ ? value.perAgent[agent]
+ : undefined;
+ if (
+ !isPlainObject(override) ||
+ !isModelAccessWireProtocol(override.wireProtocol)
+ ) {
return `${path}.perAgent.${agent}.wireProtocol is required when ${path}.agents includes ${agent}`;
}
}
@@ -624,7 +725,10 @@ type ModelCatalogSchemaVersion =
| typeof MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION
| typeof MODEL_ACCESS_CATALOG_SCHEMA_VERSION;
-function isKnownAgentForVersion(agent: string, schemaVersion: ModelCatalogSchemaVersion): boolean {
+function isKnownAgentForVersion(
+ agent: string,
+ schemaVersion: ModelCatalogSchemaVersion,
+): boolean {
return schemaVersion === MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION ||
schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION
? isModelAgent(agent)
@@ -641,7 +745,8 @@ function filterUnknownAgentStrings(
): unknown {
if (!Array.isArray(value)) return value;
return value.filter(
- (agent) => typeof agent !== 'string' || isKnownAgentForVersion(agent, schemaVersion),
+ (agent) =>
+ typeof agent !== "string" || isKnownAgentForVersion(agent, schemaVersion),
);
}
@@ -651,15 +756,21 @@ function sanitizeModelEntryAgents(
): unknown {
if (!isPlainObject(value)) return value;
const sanitized: PlainObject = { ...value };
- if ('agents' in sanitized) {
- sanitized.agents = filterUnknownAgentStrings(sanitized.agents, schemaVersion);
+ if ("agents" in sanitized) {
+ sanitized.agents = filterUnknownAgentStrings(
+ sanitized.agents,
+ schemaVersion,
+ );
}
if (
schemaVersion !== MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION &&
- 'newSessionDefault' in sanitized
+ "newSessionDefault" in sanitized
) {
const original = sanitized.newSessionDefault;
- const filtered = filterUnknownAgentStrings(sanitized.newSessionDefault, schemaVersion);
+ const filtered = filterUnknownAgentStrings(
+ sanitized.newSessionDefault,
+ schemaVersion,
+ );
if (
Array.isArray(original) &&
original.length > 0 &&
@@ -682,7 +793,7 @@ function sanitizeModelEntryAgents(
export function parseListModelsResponse(
value: unknown,
): ModelAccessParseResult<ListModelsResponse> {
- if (!isPlainObject(value)) return fail('response must be an object');
+ if (!isPlainObject(value)) return fail("response must be an object");
if (
value.schemaVersion !== MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION &&
value.schemaVersion !== MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION &&
@@ -697,24 +808,36 @@ export function parseListModelsResponse(
if (value.schemaVersion === MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION) {
const unknownField = unknownFieldError(
value,
- ['schemaVersion', 'accountTier', 'models'],
- 'response',
+ ["schemaVersion", "accountTier", "models"],
+ "response",
);
if (unknownField) return fail(unknownField);
- if (!['free', 'paid', 'not_applicable'].includes(String(value.accountTier))) {
- return fail('response.accountTier must be free, paid, or not_applicable');
+ if (
+ !["free", "paid", "not_applicable"].includes(String(value.accountTier))
+ ) {
+ return fail("response.accountTier must be free, paid, or not_applicable");
}
- if (!Array.isArray(value.models)) return fail('response.models must be an array');
+ if (!Array.isArray(value.models))
+ return fail("response.models must be an array");
const modelIds = new Set<string>();
const models: unknown[] = [];
for (const [index, raw] of value.models.entries()) {
- if (!isPlainObject(raw)) return fail(`response.models[${index}] must be an object`);
- if (raw.availability !== 'available' && raw.availability !== 'requires_payment') {
- return fail(`response.models[${index}].availability must be available or requires_payment`);
+ if (!isPlainObject(raw))
+ return fail(`response.models[${index}] must be an object`);
+ if (
+ raw.availability !== "available" &&
+ raw.availability !== "requires_payment"
+ ) {
+ return fail(
+ `response.models[${index}].availability must be available or requires_payment`,
+ );
}
const { availability, ...legacyShape } = raw;
- const sanitized = sanitizeModelEntryAgents(legacyShape, MODEL_ACCESS_CATALOG_SCHEMA_VERSION);
- if (isPlainObject(sanitized) && typeof sanitized.id === 'string') {
+ const sanitized = sanitizeModelEntryAgents(
+ legacyShape,
+ MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ );
+ if (isPlainObject(sanitized) && typeof sanitized.id === "string") {
if (modelIds.has(sanitized.id)) {
return fail(`response.models[${index}].id must be unique`);
}
@@ -734,20 +857,31 @@ export function parseListModelsResponse(
models,
} as ListModelsResponse);
}
- const unknownField = unknownFieldError(value, LIST_MODELS_RESPONSE_FIELDS, 'response');
+ const unknownField = unknownFieldError(
+ value,
+ LIST_MODELS_RESPONSE_FIELDS,
+ "response",
+ );
if (unknownField) return fail(unknownField);
const schemaVersion = value.schemaVersion as ModelCatalogSchemaVersion;
- if (!Array.isArray(value.models)) return fail('response.models must be an array');
- const models = value.models.map((model) => sanitizeModelEntryAgents(model, schemaVersion));
+ if (!Array.isArray(value.models))
+ return fail("response.models must be an array");
+ const models = value.models.map((model) =>
+ sanitizeModelEntryAgents(model, schemaVersion),
+ );
const modelIds = new Set<string>();
for (const [index, model] of models.entries()) {
- if (isPlainObject(model) && typeof model.id === 'string') {
+ if (isPlainObject(model) && typeof model.id === "string") {
if (modelIds.has(model.id)) {
return fail(`response.models[${index}].id must be unique`);
}
modelIds.add(model.id);
}
- const error = modelEntryError(model, `response.models[${index}]`, schemaVersion);
+ const error = modelEntryError(
+ model,
+ `response.models[${index}]`,
+ schemaVersion,
+ );
if (error) return fail(error);
}
return ok({ schemaVersion, models } as ListModelsResponse);
@@ -757,16 +891,17 @@ function referencePriceError(value: unknown, path: string): string | null {
if (!isPlainObject(value)) return `${path} must be an object`;
let error = unknownFieldError(value, MODEL_REFERENCE_PRICE_FIELDS, path);
if (error) return error;
- if (!isModelCurrency(value.currency)) return `${path}.currency must be CNY or USD`;
+ if (!isModelCurrency(value.currency))
+ return `${path}.currency must be CNY or USD`;
if (!isModelPriceVariant(value.variant)) {
return `${path}.variant must be a supported price variant`;
}
for (const field of [
- 'inputPerMtok',
- 'outputPerMtok',
- 'cacheReadPerMtok',
- 'cacheWritePerMtok',
- 'cacheWrite1hPerMtok',
+ "inputPerMtok",
+ "outputPerMtok",
+ "cacheReadPerMtok",
+ "cacheWritePerMtok",
+ "cacheWrite1hPerMtok",
] as const) {
error = optionalFiniteNumberError(value[field], `${path}.${field}`, {
nonNegative: true,
@@ -776,7 +911,7 @@ function referencePriceError(value: unknown, path: string): string | null {
if (value.inputPerMtok === undefined || value.outputPerMtok === undefined) {
return `${path} must declare inputPerMtok and outputPerMtok`;
}
- for (const field of ['minInputTokens', 'maxInputTokens'] as const) {
+ for (const field of ["minInputTokens", "maxInputTokens"] as const) {
if (
value[field] !== undefined &&
(!Number.isInteger(value[field]) || (value[field] as number) < 0)
@@ -784,8 +919,9 @@ function referencePriceError(value: unknown, path: string): string | null {
return `${path}.${field} must be a non-negative integer when present`;
}
}
- const min = typeof value.minInputTokens === 'number' ? value.minInputTokens : 0;
- if (typeof value.maxInputTokens === 'number' && value.maxInputTokens <= min) {
+ const min =
+ typeof value.minInputTokens === "number" ? value.minInputTokens : 0;
+ if (typeof value.maxInputTokens === "number" && value.maxInputTokens <= min) {
return `${path}.maxInputTokens must be greater than minInputTokens`;
}
if (!isIsoDate(value.effectiveFrom)) {
@@ -800,27 +936,76 @@ function referencePriceError(value: unknown, path: string): string | null {
}
}
if (!isPlainObject(value.source)) return `${path}.source must be an object`;
- error = unknownFieldError(value.source, MODEL_REFERENCE_PRICE_SOURCE_FIELDS, `${path}.source`);
+ error = unknownFieldError(
+ value.source,
+ MODEL_REFERENCE_PRICE_SOURCE_FIELDS,
+ `${path}.source`,
+ );
if (error) return error;
- if (value.source.kind !== 'provider-official') {
+ if (value.source.kind !== "provider-official") {
return `${path}.source.kind must be provider-official`;
}
- if (!isHttpsUrl(value.source.url)) return `${path}.source.url must be an HTTPS URL`;
+ if (!isHttpsUrl(value.source.url))
+ return `${path}.source.url must be an HTTPS URL`;
if (!isIsoDate(value.source.verifiedAt)) {
return `${path}.source.verifiedAt must be an ISO calendar date`;
}
return null;
}
-function registryRouteError(value: unknown, path: string): string | null {
+function registryRouteError(
+ value: unknown,
+ path: string,
+ schemaVersion = 2,
+): string | null {
if (!isPlainObject(value)) return `${path} must be an object`;
- let error = unknownFieldError(value, MODEL_REGISTRY_ROUTE_FIELDS, path);
+ let error = unknownFieldError(
+ value,
+ schemaVersion >= 4
+ ? [
+ ...MODEL_REGISTRY_ROUTE_FIELDS,
+ "defaults",
+ "forceOverrides",
+ "overrideReason",
+ "overrideVerifiedAt",
+ ]
+ : MODEL_REGISTRY_ROUTE_FIELDS,
+ path,
+ );
if (error) return error;
+ for (const field of ["defaults", "forceOverrides"] as const) {
+ if (value[field] !== undefined && !validModelMetadata(value[field]))
+ return `${path}.${field} is invalid`;
+ }
+ if (
+ value.overrideReason !== undefined &&
+ (typeof value.overrideReason !== "string" ||
+ !value.overrideReason.trim() ||
+ value.overrideReason.length > 1000)
+ )
+ return `${path}.overrideReason is invalid`;
+ if (
+ value.forceOverrides !== undefined &&
+ (typeof value.overrideReason !== "string" ||
+ !value.overrideReason.trim() ||
+ value.overrideReason.length > 1000)
+ )
+ return `${path}.overrideReason is required for forceOverrides`;
+ if (
+ value.overrideVerifiedAt !== undefined &&
+ (typeof value.overrideVerifiedAt !== "string" ||
+ !/^\d{4}-\d{2}-\d{2}$/.test(value.overrideVerifiedAt) ||
+ !Number.isFinite(Date.parse(value.overrideVerifiedAt)) ||
+ new Date(value.overrideVerifiedAt).toISOString().slice(0, 10) !==
+ value.overrideVerifiedAt)
+ )
+ return `${path}.overrideVerifiedAt is invalid`;
+
if (!isSafeSlug(value.providerId)) {
return `${path}.providerId must use letters, numbers, underscores, or hyphens`;
}
if (
- typeof value.modelId !== 'string' ||
+ typeof value.modelId !== "string" ||
value.modelId.length === 0 ||
value.modelId.length > 256
) {
@@ -859,15 +1044,20 @@ function registryRouteError(value: unknown, path: string): string | null {
function registryEntryError(
value: unknown,
path: string,
- schemaVersion: ModelRegistry['schemaVersion'],
+ schemaVersion: ModelRegistry["schemaVersion"],
+ validateDependencies = true,
): string | null {
if (!isPlainObject(value)) return `${path} must be an object`;
let error = unknownFieldError(
value,
schemaVersion === MODEL_REGISTRY_LEGACY_SCHEMA_VERSION
? MODEL_REGISTRY_ENTRY_V1_FIELDS
- : schemaVersion === MODEL_REGISTRY_V3_SCHEMA_VERSION
- ? [...MODEL_REGISTRY_ENTRY_V2_FIELDS, 'nativeApi']
+ : schemaVersion >= MODEL_REGISTRY_V3_SCHEMA_VERSION
+ ? [
+ ...MODEL_REGISTRY_ENTRY_V2_FIELDS,
+ "nativeApi",
+ ...(schemaVersion >= 4 ? ["modelRef", "supportsImageInput"] : []),
+ ]
: MODEL_REGISTRY_ENTRY_V2_FIELDS,
path,
);
@@ -879,29 +1069,41 @@ function registryEntryError(
) {
return `${path}.nativeApi must be a supported API or null`;
}
- if (typeof value.id !== 'string' || value.id.length === 0 || value.id.length > 256) {
+ if (
+ typeof value.id !== "string" ||
+ value.id.length === 0 ||
+ value.id.length > 256
+ ) {
return `${path}.id must be a non-empty string of at most 256 characters`;
}
- if (typeof value.name !== 'string' || value.name.length === 0 || value.name.length > 256) {
+ if (
+ typeof value.name !== "string" ||
+ value.name.length === 0 ||
+ value.name.length > 256
+ ) {
return `${path}.name must be a non-empty string of at most 256 characters`;
}
if (value.status !== undefined && !isModelRegistryStatus(value.status)) {
return `${path}.status must be a supported registry status`;
}
for (const [key, max] of [
- ['group', 128],
- ['description', 2_000],
+ ["group", 128],
+ ["description", 2_000],
] as const) {
error = optionalStringError(value[key], `${path}.${key}`, max);
if (error) return error;
}
- for (const key of ['contextWindow', 'maxOutputTokens'] as const) {
+ for (const key of ["contextWindow", "maxOutputTokens"] as const) {
error = optionalPositiveIntegerError(value[key], `${path}.${key}`);
if (error) return error;
}
error = effortListError(value.efforts, `${path}.efforts`);
if (error) return error;
- if (value.defaultEffort !== undefined && !isModelEffort(value.defaultEffort)) {
+ if (
+ value.defaultEffort !== undefined &&
+ !(schemaVersion >= 4 && value.defaultEffort === null) &&
+ !isModelEffort(value.defaultEffort)
+ ) {
return `${path}.defaultEffort must be a supported effort value when present`;
}
const efforts =
@@ -909,7 +1111,8 @@ function registryEntryError(
? (value.efforts as ModelEffort[])
: undefined;
if (
- value.defaultEffort !== undefined &&
+ validateDependencies &&
+ value.defaultEffort != null &&
efforts !== undefined &&
!efforts.includes(value.defaultEffort as ModelEffort)
) {
@@ -917,8 +1120,14 @@ function registryEntryError(
}
error = optionalFiniteNumberError(value.sortOrder, `${path}.sortOrder`);
if (error) return error;
- for (const key of ['supportsFastMode', 'defaultEnabled'] as const) {
- if (value[key] !== undefined && typeof value[key] !== 'boolean') {
+ if (
+ value.supportsImageInput !== undefined &&
+ typeof value.supportsImageInput !== "boolean"
+ ) {
+ return `${path}.supportsImageInput must be a boolean when present`;
+ }
+ for (const key of ["supportsFastMode", "defaultEnabled"] as const) {
+ if (value[key] !== undefined && typeof value[key] !== "boolean") {
return `${path}.${key} must be a boolean when present`;
}
}
@@ -928,7 +1137,11 @@ function registryEntryError(
const routeKeys = new Set<string>();
const supportedAgents = new Set<ModelAgent>();
for (const [index, route] of value.routes.entries()) {
- error = registryRouteError(route, `${path}.routes[${index}]`);
+ error = registryRouteError(
+ route,
+ `${path}.routes[${index}]`,
+ schemaVersion,
+ );
if (error) return error;
const typedRoute = route as {
providerId: string;
@@ -936,14 +1149,17 @@ function registryEntryError(
agents: ModelAgent[];
};
const routeKey = `${typedRoute.providerId}\u0000${typedRoute.modelId}`;
- if (routeKeys.has(routeKey)) return `${path}.routes[${index}] must be unique`;
+ if (routeKeys.has(routeKey))
+ return `${path}.routes[${index}] must be unique`;
routeKeys.add(routeKey);
for (const agent of typedRoute.agents) supportedAgents.add(agent);
}
if (value.perAgent !== undefined) {
- if (!isPlainObject(value.perAgent)) return `${path}.perAgent must be an object when present`;
+ if (!isPlainObject(value.perAgent))
+ return `${path}.perAgent must be an object when present`;
for (const [agent, override] of Object.entries(value.perAgent)) {
- if (!isV2ModelAgent(agent)) return `${path}.perAgent.${agent} is not a supported agent`;
+ if (!isV2ModelAgent(agent))
+ return `${path}.perAgent.${agent} is not a supported agent`;
if (!supportedAgents.has(agent)) {
return `${path}.perAgent.${agent} must be supported by at least one route`;
}
@@ -952,14 +1168,15 @@ function registryEntryError(
`${path}.perAgent.${agent}`,
efforts,
MODEL_AGENT_OVERRIDE_FIELDS,
- false,
+ schemaVersion >= 4,
isModelEffort(value.defaultEffort) ? value.defaultEffort : null,
+ validateDependencies,
);
if (error) return error;
}
}
if (schemaVersion >= MODEL_REGISTRY_SCHEMA_VERSION) {
- if (value.status === 'retired' && value.newSessionDefault !== undefined) {
+ if (value.status === "retired" && value.newSessionDefault !== undefined) {
return `${path}.newSessionDefault is not allowed when ${path}.status is retired`;
}
const defaultError = newSessionDefaultError(
@@ -972,60 +1189,152 @@ function registryEntryError(
return null;
}
-export function parseModelRegistry(value: unknown): ModelAccessParseResult<ModelRegistry> {
- if (!isPlainObject(value)) return fail('modelRegistry must be an object');
+export function parseModelRegistry(
+ value: unknown,
+): ModelAccessParseResult<ModelRegistry> {
+ if (!isPlainObject(value)) return fail("modelRegistry must be an object");
const unknownField = unknownFieldError(
value,
- value.schemaVersion === MODEL_REGISTRY_V3_SCHEMA_VERSION
- ? [...MODEL_REGISTRY_FIELDS, 'nativeApiRules']
- : MODEL_REGISTRY_FIELDS,
- 'modelRegistry',
+ value.schemaVersion === MODEL_REGISTRY_V4_SCHEMA_VERSION
+ ? [
+ ...MODEL_REGISTRY_FIELDS,
+ "nativeApiRules",
+ "localModels",
+ "baseModels",
+ ]
+ : value.schemaVersion === MODEL_REGISTRY_V3_SCHEMA_VERSION
+ ? [...MODEL_REGISTRY_FIELDS, "nativeApiRules"]
+ : MODEL_REGISTRY_FIELDS,
+ "modelRegistry",
);
if (unknownField) return fail(unknownField);
if (
value.schemaVersion !== MODEL_REGISTRY_LEGACY_SCHEMA_VERSION &&
value.schemaVersion !== MODEL_REGISTRY_SCHEMA_VERSION &&
- value.schemaVersion !== MODEL_REGISTRY_V3_SCHEMA_VERSION
+ value.schemaVersion !== MODEL_REGISTRY_V3_SCHEMA_VERSION &&
+ value.schemaVersion !== MODEL_REGISTRY_V4_SCHEMA_VERSION
) {
- return fail('modelRegistry.schemaVersion must be 1, 2 or 3');
+ return fail("modelRegistry.schemaVersion must be 1, 2, 3 or 4");
}
if (!isIsoTimestamp(value.updatedAt)) {
- return fail('modelRegistry.updatedAt must be an ISO timestamp');
+ return fail("modelRegistry.updatedAt must be an ISO timestamp");
+ }
+ if (
+ value.localModels !== undefined &&
+ !parseLocalModelCatalog(value.localModels)
+ ) {
+ return fail("modelRegistry.localModels is invalid");
}
- if (!Array.isArray(value.models)) return fail('modelRegistry.models must be an array');
+ if (!Array.isArray(value.models))
+ return fail("modelRegistry.models must be an array");
if (value.nativeApiRules !== undefined) {
if (!Array.isArray(value.nativeApiRules))
- return fail('modelRegistry.nativeApiRules must be an array');
+ return fail("modelRegistry.nativeApiRules must be an array");
const identities = new Set<string>();
for (const rule of value.nativeApiRules) {
if (
!isPlainObject(rule) ||
- unknownFieldError(rule, ['providerId', 'modelIdPrefix', 'nativeApi'], 'nativeApiRule') ||
- typeof rule.providerId !== 'string' ||
+ unknownFieldError(
+ rule,
+ ["providerId", "modelIdPrefix", "nativeApi"],
+ "nativeApiRule",
+ ) ||
+ typeof rule.providerId !== "string" ||
!rule.providerId ||
rule.providerId.length > 128 ||
- typeof rule.modelIdPrefix !== 'string' ||
+ typeof rule.modelIdPrefix !== "string" ||
!rule.modelIdPrefix ||
rule.modelIdPrefix.length > 256 ||
!MODEL_NATIVE_APIS.includes(rule.nativeApi as never)
)
- return fail('modelRegistry.nativeApiRules contains an invalid rule');
+ return fail("modelRegistry.nativeApiRules contains an invalid rule");
const key = `${rule.providerId}\u0000${rule.modelIdPrefix}`;
if (identities.has(key))
- return fail('modelRegistry.nativeApiRules must have unique provider/prefix pairs');
+ return fail(
+ "modelRegistry.nativeApiRules must have unique provider/prefix pairs",
+ );
identities.add(key);
}
}
+ const baseIds = new Set<string>();
+ const identities = new Set<string>();
+ if (value.baseModels !== undefined) {
+ if (!Array.isArray(value.baseModels) || value.baseModels.length > 2000)
+ return fail("modelRegistry.baseModels is invalid");
+ for (const base of value.baseModels) {
+ if (
+ !isPlainObject(base) ||
+ unknownFieldError(base, ["id", "aliases", "defaults"], "baseModel") ||
+ typeof base.id !== "string" ||
+ !base.id ||
+ base.id.length > 256 ||
+ !Array.isArray(base.aliases) ||
+ base.aliases.length > 32 ||
+ !base.aliases.every(
+ (a) => typeof a === "string" && a.length > 0 && a.length <= 256,
+ ) ||
+ !validModelMetadata(base.defaults)
+ )
+ return fail("modelRegistry.baseModels contains invalid data");
+ baseIds.add(base.id);
+ if (
+ base.defaults.efforts !== undefined &&
+ base.defaults.defaultEffort != null &&
+ !base.defaults.efforts.includes(base.defaults.defaultEffort)
+ ) {
+ return fail("modelRegistry.baseModels defaultEffort must be supported");
+ }
+ for (const identity of [base.id, ...base.aliases]) {
+ if (identities.has(identity))
+ return fail("modelRegistry.baseModels identity is ambiguous");
+ identities.add(identity);
+ }
+ }
+ }
+ for (const model of value.models) {
+ if (
+ isPlainObject(model) &&
+ model.modelRef !== undefined &&
+ !baseIds.has(model.modelRef as string)
+ )
+ return fail("modelRegistry.modelRef is unresolved");
+ }
+ const localModels = value.localModels as
+ { models?: { modelRef?: string }[] } | undefined;
+ if (
+ localModels?.models?.some(
+ (model) => model.modelRef !== undefined && !baseIds.has(model.modelRef),
+ )
+ )
+ return fail("modelRegistry.localModels.modelRef is unresolved");
const modelIds = new Set<string>();
for (const [index, model] of value.models.entries()) {
- if (isPlainObject(model) && typeof model.id === 'string') {
+ if (isPlainObject(model) && typeof model.id === "string") {
if (modelIds.has(model.id)) {
return fail(`modelRegistry.models[${index}].id must be unique`);
}
modelIds.add(model.id);
}
- const error = registryEntryError(model, `modelRegistry.models[${index}]`, value.schemaVersion);
+ // V4 dependencies are checked below after public, route and force layers are applied.
+ const error = registryEntryError(
+ model,
+ `modelRegistry.models[${index}]`,
+ value.schemaVersion,
+ value.schemaVersion < 4,
+ );
if (error) return fail(error);
+ const typed = model as ModelRegistryEntry;
+ for (const effective of expandedRegistryEntries({
+ ...(value as unknown as ModelRegistry),
+ models: [typed],
+ })) {
+ const mergedError = registryEntryError(
+ effective,
+ `modelRegistry.models[${index}]`,
+ value.schemaVersion,
+ );
+ if (mergedError) return fail(mergedError);
+ }
}
return ok(value as unknown as ModelRegistry);
}
diff --git a/packages/model-providers/src/modelMetadataLayers.ts b/packages/model-providers/src/modelMetadataLayers.ts
new file mode 100644
index 0000000000..a1b288ec2c
--- /dev/null
+++ b/packages/model-providers/src/modelMetadataLayers.ts
@@ -0,0 +1,393 @@
+import type { CatalogModel } from "./types.js";
+import type {
+ ModelRegistry,
+ ModelRegistryEntry,
+ ModelRegistryRoute,
+ ModelEffort,
+} from "./modelAccessBean.js";
+
+/** Data only. Membership, credentials, routing and billed prices never inherit. */
+export interface ModelMetadata {
+ name?: string;
+ description?: string;
+ group?: string;
+ contextWindow?: number;
+ maxOutputTokens?: number;
+ efforts?: ModelEffort[];
+ defaultEffort?: ModelEffort | null;
+ supportsFastMode?: boolean;
+ supportsImageInput?: boolean;
+}
+export interface BaseModel {
+ id: string;
+ aliases: string[];
+ defaults: ModelMetadata;
+}
+export const MODEL_METADATA_FIELDS = [
+ "name",
+ "description",
+ "group",
+ "contextWindow",
+ "maxOutputTokens",
+ "efforts",
+ "defaultEffort",
+ "supportsFastMode",
+ "supportsImageInput",
+] as const;
+const efforts = new Set([
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+]);
+export function validModelMetadata(value: unknown): value is ModelMetadata {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ return Object.entries(value).every(([key, v]) => {
+ if (!(MODEL_METADATA_FIELDS as readonly string[]).includes(key))
+ return false;
+ if (["name", "description", "group"].includes(key)) {
+ const maxLength = key === "name" ? 256 : key === "group" ? 128 : 2000;
+ return (
+ typeof v === "string" && v.trim().length > 0 && v.length <= maxLength
+ );
+ }
+ if (["contextWindow", "maxOutputTokens"].includes(key))
+ return typeof v === "number" && Number.isSafeInteger(v) && v > 0;
+ if (key === "efforts")
+ return (
+ Array.isArray(v) &&
+ v.every((e) => efforts.has(e)) &&
+ new Set(v).size === v.length
+ );
+ if (key === "defaultEffort") return v === null || efforts.has(v as string);
+ return typeof v === "boolean";
+ });
+}
+export function pickModelMetadata(value: object | undefined): ModelMetadata {
+ const result: Record<string, unknown> = {};
+ for (const key of MODEL_METADATA_FIELDS) {
+ const v = (value as Record<string, unknown> | undefined)?.[key];
+ if (v !== undefined && validModelMetadata({ [key]: v })) result[key] = v;
+ }
+ return result as ModelMetadata;
+}
+/** Undefined inherits; false, null and [] remain explicit values. Arrays replace. */
+export function mergeModelMetadata(
+ ...layers: (ModelMetadata | undefined)[]
+): ModelMetadata {
+ return Object.assign({}, ...layers.map(pickModelMetadata));
+}
+export function findBaseModel(
+ registry: ModelRegistry | undefined,
+ identity: string,
+): BaseModel | undefined {
+ const matches =
+ registry?.baseModels?.filter(
+ (m) => m.id === identity || m.aliases.includes(identity),
+ ) ?? [];
+ return matches.length === 1 ? matches[0] : undefined;
+}
+export function registryEntryDefaults(
+ registry: ModelRegistry,
+ entry: ModelRegistryEntry,
+ route?: ModelRegistryRoute,
+ agent?: string,
+ providerDefaults?: ModelMetadata,
+): ModelMetadata {
+ return mergeModelMetadata(
+ entry.modelRef
+ ? findBaseModel(registry, entry.modelRef)?.defaults
+ : undefined,
+ providerDefaults,
+ pickModelMetadata(entry),
+ route?.defaults,
+ agent
+ ? pickModelMetadata(
+ entry.perAgent?.[agent as keyof NonNullable<typeof entry.perAgent>],
+ )
+ : undefined,
+ );
+}
+export function resolveModelMetadata(
+ registry: ModelRegistry | undefined,
+ providerId: string,
+ modelId: string,
+ live?: ModelMetadata,
+ user?: ModelMetadata,
+ agent?: string,
+ providerDefaults?: ModelMetadata,
+): ModelMetadata {
+ const ids = [modelId];
+ if (providerId === "openai" && modelId.startsWith("chatgpt/"))
+ ids.push(modelId.slice(8));
+ if (providerId === "xai" && !modelId.startsWith("xai/"))
+ ids.push(`xai/${modelId}`);
+ if (providerId === "anthropic") ids.push(modelId.replace(/-\d{8}$/, ""));
+ for (const id of [...ids]) if (id.endsWith("[1m]")) ids.push(id.slice(0, -4));
+ const matched = ids.flatMap(
+ (id) =>
+ registry?.models.flatMap((entry) =>
+ entry.routes
+ .filter(
+ (route) =>
+ route.providerId === providerId &&
+ route.modelId === id &&
+ (!agent ||
+ agent === "pi" ||
+ route.agents.includes(agent as never)),
+ )
+ .map((route) => ({ entry, route })),
+ ) ?? [],
+ )[0];
+ const defaults =
+ matched && registry
+ ? registryEntryDefaults(
+ registry,
+ matched.entry,
+ matched.route,
+ agent,
+ providerDefaults,
+ )
+ : mergeModelMetadata(
+ findBaseModel(registry, modelId)?.defaults,
+ providerDefaults,
+ );
+ const result = mergeModelMetadata(
+ defaults,
+ live,
+ matched?.route.forceOverrides,
+ user,
+ );
+ if (result.efforts?.length === 0) result.defaultEffort = null;
+ else if (
+ result.defaultEffort != null &&
+ result.efforts &&
+ !result.efforts.includes(result.defaultEffort)
+ ) {
+ const order = [...efforts];
+ const supported = [...result.efforts].sort(
+ (a, b) => order.indexOf(a) - order.indexOf(b),
+ );
+ result.defaultEffort =
+ supported
+ .filter(
+ (value) =>
+ order.indexOf(value) <= order.indexOf(result.defaultEffort!),
+ )
+ .at(-1) ??
+ supported[0] ??
+ null;
+ }
+ return result;
+}
+
+/** Legacy consumers receive fully expanded entries without losing saved IDs or routes. */
+export function expandedRegistryEntries(
+ registry: ModelRegistry,
+): ModelRegistryEntry[] {
+ if (registry.schemaVersion < 4) return registry.models;
+ const usedIds = new Set(registry.models.map((entry) => entry.id));
+ return registry.models.flatMap((entry) => {
+ const groups = new Map<string, ModelRegistryEntry>();
+ for (const route of entry.routes) {
+ const metadata = mergeModelMetadata(
+ registryEntryDefaults(registry, entry, route),
+ route.forceOverrides,
+ );
+ // Legacy schemas cannot encode a runtime clear against a group default.
+ // Move that default to the other runtimes so omission remains an actual clear.
+ const runtimeClear =
+ metadata.defaultEffort != null &&
+ route.agents.some(
+ (agent) =>
+ mergeModelMetadata(
+ registryEntryDefaults(registry, entry, route, agent),
+ route.forceOverrides,
+ ).defaultEffort === null,
+ );
+ const overrides = runtimeClear
+ ? Object.fromEntries(
+ route.agents.map((agent) => [agent, entry.perAgent?.[agent] ?? {}]),
+ )
+ : entry.perAgent;
+ const perAgent = overrides
+ ? Object.fromEntries(
+ Object.entries(overrides).map(([agent, override]) => {
+ const effective = mergeModelMetadata(
+ registryEntryDefaults(registry, entry, route, agent),
+ route.forceOverrides,
+ );
+ // Older wire schemas cannot express a null default. Omission preserves their contract.
+ const { defaultEffort, ...fields } = effective;
+ const { defaultEffort: _oldDefault, ...remainingOverride } =
+ override ?? {};
+ return [
+ agent,
+ {
+ ...remainingOverride,
+ ...Object.fromEntries(
+ Object.entries(fields).filter(([key]) =>
+ ["contextWindow", "efforts", "supportsFastMode"].includes(
+ key,
+ ),
+ ),
+ ),
+ ...(defaultEffort != null ? { defaultEffort } : {}),
+ },
+ ];
+ }),
+ )
+ : undefined;
+ const { defaultEffort, supportsImageInput, ...fields } = metadata;
+ const expanded = {
+ ...entry,
+ ...fields,
+ perAgent,
+ ...(defaultEffort != null ? { defaultEffort } : {}),
+ };
+ if (defaultEffort === null || runtimeClear) delete expanded.defaultEffort;
+ delete expanded.supportsImageInput;
+ const key = JSON.stringify(
+ { ...expanded, routes: undefined },
+ (_key, value) =>
+ value && typeof value === "object" && !Array.isArray(value)
+ ? Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map((key) => [key, value[key]]),
+ )
+ : value,
+ );
+ const previous = groups.get(key);
+ if (previous) previous.routes.push(route);
+ else groups.set(key, { ...expanded, routes: [route] });
+ }
+ // Old schemas have entry-level metadata. Split only divergent routes; upstream IDs stay intact.
+ return [...groups.values()].map((value, index) => {
+ let id = entry.id;
+ if (index > 0) {
+ let collision = 0;
+ do {
+ const suffix = `::route-${index + 1}${collision ? `~${collision}` : ""}`;
+ id = `${entry.id.slice(0, 256 - suffix.length)}${suffix}`;
+ collision += 1;
+ } while (usedIds.has(id));
+ usedIds.add(id);
+ }
+ const agents = new Set(value.routes.flatMap((route) => route.agents));
+ const perAgent = Object.fromEntries(
+ Object.entries(value.perAgent ?? {}).filter(([agent]) =>
+ agents.has(agent as never),
+ ),
+ );
+ const next = {
+ ...value,
+ id,
+ ...(value.newSessionDefault
+ ? {
+ newSessionDefault: value.newSessionDefault.filter((agent) =>
+ agents.has(agent),
+ ),
+ }
+ : {}),
+ };
+ if (Object.keys(perAgent).length) next.perAgent = perAgent;
+ else delete next.perAgent;
+ if (!next.newSessionDefault?.length) delete next.newSessionDefault;
+ return next;
+ });
+ });
+}
+
+export function catalogModelMetadata(
+ model: Partial<CatalogModel>,
+): ModelMetadata {
+ return {
+ ...pickModelMetadata(model),
+ ...(model.maxOutput !== undefined
+ ? { maxOutputTokens: model.maxOutput }
+ : {}),
+ };
+}
+export function applyModelMetadata(
+ model: CatalogModel,
+ metadata: ModelMetadata,
+): CatalogModel {
+ const { maxOutputTokens, ...fields } = metadata;
+ const result = {
+ ...model,
+ ...fields,
+ ...(metadata.contextWindow !== undefined
+ ? { contextWindowVerified: true }
+ : {}),
+ ...(maxOutputTokens !== undefined ? { maxOutput: maxOutputTokens } : {}),
+ };
+ if (
+ result.efforts.length === 0 ||
+ (result.defaultEffort != null &&
+ !result.efforts.includes(result.defaultEffort))
+ )
+ result.defaultEffort = null;
+ return result;
+}
+
+export interface DiscoveredModel {
+ id: string;
+ name: string;
+ contextWindow?: number;
+ discoveredMetadata?: ModelMetadata;
+}
+export function mergeDiscoveredRuntimeModels(
+ existing: readonly import("./types.js").ProviderRuntimeModelConfig[],
+ discovered: readonly DiscoveredModel[],
+ hideNew = false,
+) {
+ const models = existing.map((model) => ({ ...model }));
+ const seen = new Set<string>();
+ for (const model of discovered) {
+ if (!model.id || !model.name || seen.has(model.id)) continue;
+ seen.add(model.id);
+ const discoveredMetadata = pickModelMetadata(
+ model.discoveredMetadata ?? model,
+ );
+ const index = models.findIndex((m) => m.id === model.id);
+ if (index < 0)
+ models.push({
+ id: model.id,
+ name: model.name,
+ discoveredMetadata,
+ ...(hideNew ? { defaultEnabled: false } : {}),
+ });
+ else
+ models[index] = {
+ ...models[index],
+ ...(!models[index].discoveredMetadata ? { nameExplicit: true } : {}),
+ discoveredMetadata,
+ };
+ }
+ return models;
+}
+
+/** Explicit runtime user fields, shared by initial construction and local public overlays. */
+export function runtimeUserModelMetadata(
+ m: import("./types.js").ProviderRuntimeModelConfig,
+): ModelMetadata {
+ return pickModelMetadata({
+ ...(!m.discoveredMetadata || m.nameExplicit ? { name: m.name } : {}),
+ ...(m.contextWindow !== undefined
+ ? { contextWindow: m.contextWindow }
+ : {}),
+ ...(m.supportsImageInput !== undefined
+ ? { supportsImageInput: m.supportsImageInput }
+ : {}),
+ ...(m.reasoning !== undefined
+ ? { efforts: m.reasoning ? (m.reasoningEfforts ?? []) : [] }
+ : {}),
+ ...(m.reasoningDefaultEffort !== undefined
+ ? { defaultEffort: m.reasoningDefaultEffort }
+ : {}),
+ });
+}
diff --git a/packages/model-providers/src/modelRegistry.ts b/packages/model-providers/src/modelRegistry.ts
index 2182271cea..a7520a36b8 100644
--- a/packages/model-providers/src/modelRegistry.ts
+++ b/packages/model-providers/src/modelRegistry.ts
@@ -1,3 +1,4 @@
+import { registryEntryDefaults } from "./modelMetadataLayers.js";
import { modelRegistryCanonicalJson } from "./modelRegistryCanonical.js";
import type {
ModelAccessV2Agent,
@@ -193,7 +194,21 @@ export function findModelRegistryRoute(
modelId: string,
agent?: ModelAccessV2Agent,
): { entry: ModelRegistryEntry; route: ModelRegistryRoute } | undefined {
- return matchingModelRegistryRoutes(registry, providerId, modelId, agent)[0];
+ const matched = matchingModelRegistryRoutes(
+ registry,
+ providerId,
+ modelId,
+ agent,
+ )[0];
+ if (!matched || registry?.schemaVersion !== 4) return matched;
+ return {
+ route: matched.route,
+ entry: {
+ ...matched.entry,
+ ...registryEntryDefaults(registry, matched.entry, matched.route),
+ ...matched.route.forceOverrides,
+ } as ModelRegistryEntry,
+ };
}
/**
diff --git a/packages/model-providers/src/piNativeCatalog.ts b/packages/model-providers/src/piNativeCatalog.ts
index c8a28dceca..9629a07232 100644
--- a/packages/model-providers/src/piNativeCatalog.ts
+++ b/packages/model-providers/src/piNativeCatalog.ts
@@ -1,8 +1,8 @@
-import piModelCatalogJson from '../catalog/pi-model-catalog.json' with { type: 'json' };
+import piModelCatalogJson from "../catalog/pi-model-catalog.json" with { type: "json" };
-import { defaultEffortForCapabilities } from './effortResolution.js';
-import { piSupportedEfforts } from './piThinkingLevels.mjs';
-import type { CatalogModel, ModelCost, PiModelApi } from './types.js';
+import { defaultEffortForCapabilities } from "./effortResolution.js";
+import { piSupportedEfforts } from "./piThinkingLevels.mjs";
+import type { CatalogModel, ModelCost, PiModelApi } from "./types.js";
interface PiCatalogRow {
id: string;
@@ -25,12 +25,12 @@ const PI_CATALOG = piModelCatalogJson as unknown as {
function portablePiApi(api: string | undefined): PiModelApi | undefined {
switch (api) {
// Same Responses wire family; pi-host retains the specialized subscription adapter.
- case 'openai-codex-responses':
- return 'openai-responses';
- case 'anthropic-messages':
- case 'openai-responses':
- case 'openai-completions':
- case 'google-generative-ai':
+ case "openai-codex-responses":
+ return "openai-responses";
+ case "anthropic-messages":
+ case "openai-responses":
+ case "openai-completions":
+ case "google-generative-ai":
return api;
default:
return undefined;
@@ -49,7 +49,9 @@ export function piNativeCatalogModels(
): CatalogModel[] {
const rows = PI_CATALOG.providers[piProviderId];
if (!rows) {
- throw new Error(`[model-providers] Pi catalog missing provider '${piProviderId}'`);
+ throw new Error(
+ `[model-providers] Pi catalog missing provider '${piProviderId}'`,
+ );
}
return rows.map((row, index) => {
if (
@@ -57,22 +59,35 @@ export function piNativeCatalogModels(
!Number.isFinite(row.contextWindow) ||
row.contextWindow <= 0
) {
- throw new Error(`[model-providers] invalid Pi catalog row '${piProviderId}/${row.id}'`);
+ throw new Error(
+ `[model-providers] invalid Pi catalog row '${piProviderId}/${row.id}'`,
+ );
}
const efforts = piSupportedEfforts(row);
const piApi = portablePiApi(row.api);
return {
- id: `${options.idPrefix ?? ''}${row.id}`,
+ id: `${options.idPrefix ?? ""}${row.id}`,
name: row.name ?? row.id,
...(options.group ? { group: options.group } : {}),
sortOrder: index,
contextWindow: row.contextWindow,
contextWindowVerified: true,
- ...(Number.isFinite(row.maxTokens) && row.maxTokens! > 0 ? { maxOutput: row.maxTokens } : {}),
+ ...(Number.isFinite(row.maxTokens) && row.maxTokens! > 0
+ ? { maxOutput: row.maxTokens }
+ : {}),
efforts,
+ discoveredMetadata: {
+ ...(row.name ? { name: row.name } : {}),
+ contextWindow: row.contextWindow,
+ efforts,
+ ...(row.maxTokens ? { maxOutputTokens: row.maxTokens } : {}),
+ ...(row.input
+ ? { supportsImageInput: row.input.includes("image") }
+ : {}),
+ },
defaultEffort: defaultEffortForCapabilities(efforts),
- status: 'active',
- ...(row.input?.includes('image') ? { supportsImageInput: true } : {}),
+ status: "active",
+ ...(row.input?.includes("image") ? { supportsImageInput: true } : {}),
...(row.cost ? { cost: row.cost } : {}),
...(piApi ? { piApi } : {}),
};
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index a1f7befb4d..baffbf81c2 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -13,17 +13,18 @@
* 保证包可独立单测,也保证跨平台路径 / CORS 等细节留在 host。
*/
-import { BUNDLED_CATALOG, parseCatalog } from './catalog.js';
+import { BUNDLED_CATALOG, parseCatalog } from "./catalog.js";
import {
compareModelRegistryRevisions,
decideModelRegistrySnapshot,
-} from './modelRegistry.js';
-import type { AgentKind, Catalog, Provider, ProviderPreset } from './types.js';
+} from "./modelRegistry.js";
+import type { AgentKind, Catalog, Provider, ProviderPreset } from "./types.js";
/** 公共模型目录 API 路径。发布版由 model-access-server 匿名提供完整 Catalog。 */
-export const CATALOG_API_PATH = '/api/model-catalog/catalog?registrySchemaVersion=3';
+export const CATALOG_API_PATH =
+ "/api/model-catalog/catalog?registrySchemaVersion=4";
/** 旧客户端目录的 OSS 相对路径。迁移期作为公共 API 失败后的兼容回退。 */
-export const CATALOG_CFG_PATH = '/cfg/providers.json';
+export const CATALOG_CFG_PATH = "/cfg/providers.json";
/** 整条远端 Catalog fallback 链共享的默认启动等待预算。 */
export const DEFAULT_REMOTE_CATALOG_BUDGET_MS = 15_000;
@@ -61,17 +62,21 @@ export interface CatalogIO {
*/
writeCache?: (scope: string, text: string) => Promise<string | void>;
/** 诊断日志(可选)。 */
- log?: (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void;
+ log?: (
+ level: "info" | "warn" | "error",
+ msg: string,
+ meta?: Record<string, unknown>,
+ ) => void;
}
-export type CatalogLoadSource = 'local' | 'remote' | 'cache' | 'bundled';
-export type CatalogCapabilityEvidence = 'current' | 'fallback';
-export type CatalogXdMediaKind = 'image' | 'video' | 'embedding';
+export type CatalogLoadSource = "local" | "remote" | "cache" | "bundled";
+export type CatalogCapabilityEvidence = "current" | "fallback";
+export type CatalogXdMediaKind = "image" | "video" | "embedding";
const ALL_XD_MEDIA_KINDS: readonly CatalogXdMediaKind[] = [
- 'image',
- 'video',
- 'embedding',
+ "image",
+ "video",
+ "embedding",
];
export interface CatalogLoadResult {
@@ -97,10 +102,12 @@ export interface CatalogLoadResult {
unverifiedXdMediaKinds: readonly CatalogXdMediaKind[];
}
-function unverifiedXdMediaKindsForPrimary(primary: Catalog): readonly CatalogXdMediaKind[] {
- const xd = primary.providers.find((provider) => provider.id === 'xd');
+function unverifiedXdMediaKindsForPrimary(
+ primary: Catalog,
+): readonly CatalogXdMediaKind[] {
+ const xd = primary.providers.find((provider) => provider.id === "xd");
if (!xd) return ALL_XD_MEDIA_KINDS;
- return xd.embeddingModels === undefined ? ['embedding'] : [];
+ return xd.embeddingModels === undefined ? ["embedding"] : [];
}
// 去尾部斜杠。不用 /\/+$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。
@@ -116,8 +123,8 @@ export function resolveCatalogUrl(cfg: CatalogSourceConfig): string | null {
const explicit = cfg.url.trim();
try {
const url = new URL(explicit);
- if (url.pathname.endsWith('/api/model-catalog/catalog')) {
- url.searchParams.set('registrySchemaVersion', '3');
+ if (url.pathname.endsWith("/api/model-catalog/catalog")) {
+ url.searchParams.set("registrySchemaVersion", "4");
return url.toString();
}
} catch {
@@ -132,7 +139,9 @@ export function resolveCatalogUrl(cfg: CatalogSourceConfig): string | null {
}
/** 解析迁移期旧 OSS 回退 URL。 */
-export function resolveFallbackCatalogUrl(cfg: CatalogSourceConfig): string | null {
+export function resolveFallbackCatalogUrl(
+ cfg: CatalogSourceConfig,
+): string | null {
if (!cfg.fallbackBaseUrl?.trim()) return null;
return trimTrailingSlashes(cfg.fallbackBaseUrl.trim()) + CATALOG_CFG_PATH;
}
@@ -142,16 +151,20 @@ export function resolveFallbackCatalogUrl(cfg: CatalogSourceConfig): string | nu
* catalog. Strip that one retired block only at the legacy source boundary; canonical
* API, local dev files, and parseCatalog itself remain strict about unknown fields.
*/
-function parseRemoteCatalog(input: string, allowLegacyModelMeta: boolean): Catalog {
+function parseRemoteCatalog(
+ input: string,
+ allowLegacyModelMeta: boolean,
+): Catalog {
if (!allowLegacyModelMeta) return parseCatalog(input);
const raw: unknown = JSON.parse(input);
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return parseCatalog(raw);
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
+ return parseCatalog(raw);
// Keep every unknown field so parseCatalog can reject it; only the retired legacy block is
// exempt. A null-prototype destination makes special JSON keys such as `__proto__` ordinary
// own properties instead of invoking an inherited setter during the compatibility copy.
const migrated = Object.create(null) as Record<string, unknown>;
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
- if (key !== 'cindyModelMeta') migrated[key] = value;
+ if (key !== "cindyModelMeta") migrated[key] = value;
}
return parseCatalog(migrated);
}
@@ -160,17 +173,21 @@ function parseRemoteCatalog(input: string, allowLegacyModelMeta: boolean): Catal
function catalogUrlForLog(value: string): string {
try {
const parsed = new URL(value);
- parsed.username = '';
- parsed.password = '';
- parsed.search = '';
- parsed.hash = '';
+ parsed.username = "";
+ parsed.password = "";
+ parsed.search = "";
+ parsed.hash = "";
return parsed.toString();
} catch {
- return '[redacted invalid catalog URL]';
+ return "[redacted invalid catalog URL]";
}
}
-function remoteErrorForLog(error: unknown, remoteUrl: string, logUrl: string): string {
+function remoteErrorForLog(
+ error: unknown,
+ remoteUrl: string,
+ logUrl: string,
+): string {
return String(error).split(remoteUrl).join(logUrl);
}
@@ -185,21 +202,29 @@ function allowsLegacyPiRuntimeBackfill(primary: Catalog): boolean {
/** 只给仍保持 bundled 鉴权与上游路由形状的旧条目迁移 access,不能仅凭 provider id 猜计费。 */
function allowsBundledAccessInheritance(
- primaryAccess: Provider['access'],
- bundledAccess: Provider['access'],
+ primaryAccess: Provider["access"],
+ bundledAccess: Provider["access"],
): boolean {
if (primaryAccess === undefined) return true;
- if (bundledAccess === undefined || primaryAccess.kind !== bundledAccess.kind) return false;
+ if (bundledAccess === undefined || primaryAccess.kind !== bundledAccess.kind)
+ return false;
return (
- primaryAccess.kind !== 'subscription' ||
- (bundledAccess.kind === 'subscription' && primaryAccess.product === bundledAccess.product)
+ primaryAccess.kind !== "subscription" ||
+ (bundledAccess.kind === "subscription" &&
+ primaryAccess.product === bundledAccess.product)
);
}
-function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access'] {
+function legacyAccessFor(
+ primary: Provider,
+ bundled: Provider,
+): Provider["access"] {
if (primary.auth.method !== bundled.auth.method) return undefined;
- if (!allowsBundledAccessInheritance(primary.access, bundled.access)) return undefined;
- const sharedAgents = primary.agents.filter((agent) => bundled.agents.includes(agent));
+ if (!allowsBundledAccessInheritance(primary.access, bundled.access))
+ return undefined;
+ const sharedAgents = primary.agents.filter((agent) =>
+ bundled.agents.includes(agent),
+ );
if (sharedAgents.length === 0) return undefined;
const sameRoutes = sharedAgents.every((agent) => {
const current = primary.routing[agent];
@@ -226,13 +251,13 @@ function bundledResponsesCustomToolCapabilityFor(
const current = primary.routing.codex;
const baseline = bundled.routing.codex;
if (
- current === undefined
- || baseline === undefined
- || current.supportsResponsesCustomTools !== undefined
- || baseline.supportsResponsesCustomTools === undefined
- || primary.auth.method !== bundled.auth.method
- || current.upstream !== baseline.upstream
- || current.authStrategy !== baseline.authStrategy
+ current === undefined ||
+ baseline === undefined ||
+ current.supportsResponsesCustomTools !== undefined ||
+ baseline.supportsResponsesCustomTools === undefined ||
+ primary.auth.method !== bundled.auth.method ||
+ current.upstream !== baseline.upstream ||
+ current.authStrategy !== baseline.authStrategy
) {
return undefined;
}
@@ -241,14 +266,16 @@ function bundledResponsesCustomToolCapabilityFor(
/** 图片能力只可沿用到未声明 access,或仍明确属于同一 bundled 订阅的旧条目。 */
function allowsBundledImageInheritance(
- primaryAccess: Provider['access'],
- bundledAccess: Provider['access'],
+ primaryAccess: Provider["access"],
+ bundledAccess: Provider["access"],
): boolean {
if (primaryAccess === undefined) return true;
- if (bundledAccess === undefined || primaryAccess.kind !== bundledAccess.kind) return false;
+ if (bundledAccess === undefined || primaryAccess.kind !== bundledAccess.kind)
+ return false;
return (
- primaryAccess.kind !== 'subscription' ||
- (bundledAccess.kind === 'subscription' && primaryAccess.product === bundledAccess.product)
+ primaryAccess.kind !== "subscription" ||
+ (bundledAccess.kind === "subscription" &&
+ primaryAccess.product === bundledAccess.product)
);
}
@@ -262,22 +289,29 @@ function backfillPresetMetadata(
bundled: ProviderPreset,
allowLegacyPiBackfill: boolean,
): ProviderPreset {
- let changed = primary.nameZhTW === undefined && bundled.nameZhTW !== undefined;
- const runtimes: ProviderPreset['runtimes'] = { ...primary.runtimes };
+ let changed =
+ primary.nameZhTW === undefined && bundled.nameZhTW !== undefined;
+ const runtimes: ProviderPreset["runtimes"] = { ...primary.runtimes };
for (const [agent, runtime] of Object.entries(primary.runtimes) as [
AgentKind,
- NonNullable<ProviderPreset['runtimes'][AgentKind]>,
+ NonNullable<ProviderPreset["runtimes"][AgentKind]>,
][]) {
const bundledRuntime = bundled.runtimes[agent];
if (!bundledRuntime) {
runtimes[agent] = runtime;
continue;
}
- const bundledModels = new Map(bundledRuntime.models.map((model) => [model.id, model]));
+ const bundledModels = new Map(
+ bundledRuntime.models.map((model) => [model.id, model]),
+ );
let runtimeChanged = false;
const models = runtime.models.map((model) => {
const bundledContextWindow = bundledModels.get(model.id)?.contextWindow;
- if (model.contextWindow !== undefined || bundledContextWindow === undefined) return model;
+ if (
+ model.contextWindow !== undefined ||
+ bundledContextWindow === undefined
+ )
+ return model;
runtimeChanged = true;
changed = true;
return { ...model, contextWindow: bundledContextWindow };
@@ -288,9 +322,9 @@ function backfillPresetMetadata(
// 字段,缺席只代表旧 schema;对随包已核实的官方预设回填整段,避免远端 LKG 把
// DeepSeek/Kimi 的推理档位与视觉能力遮掉。远端一旦自行提供 Pi,仍完整优先。
if (
- allowLegacyPiBackfill
- && primary.runtimes.pi === undefined
- && bundled.runtimes.pi !== undefined
+ allowLegacyPiBackfill &&
+ primary.runtimes.pi === undefined &&
+ bundled.runtimes.pi !== undefined
) {
runtimes.pi = bundled.runtimes.pi;
changed = true;
@@ -332,22 +366,22 @@ export function mergeWithBundled(primary: Catalog): Catalog {
// declaration or changed auth/upstream remains authoritative and is never guessed through.
const inheritPiRuntime =
allowLegacyPiBackfill &&
- p.id === 'xai' &&
+ p.id === "xai" &&
bundledAccess !== undefined &&
- !p.agents.includes('pi') &&
+ !p.agents.includes("pi") &&
p.routing.pi === undefined &&
p.models.pi === undefined &&
- bundled.agents.includes('pi') &&
+ bundled.agents.includes("pi") &&
bundled.routing.pi !== undefined &&
bundled.models.pi !== undefined;
const inheritImage =
- p.id === 'xai' &&
+ p.id === "xai" &&
p.imageModels === undefined &&
bundled.imageModels !== undefined &&
bundledAccess !== undefined &&
allowsBundledImageInheritance(p.access, bundledAccess);
const inheritVideo =
- p.id === 'xai' &&
+ p.id === "xai" &&
p.videoModels === undefined &&
bundled.videoModels !== undefined &&
bundledAccess !== undefined &&
@@ -361,7 +395,7 @@ export function mergeWithBundled(primary: Catalog): Catalog {
// 只在字段**缺席**时补,显式 `[]` 仍然是"这个供应商不提供向量"的停用语义,
// 与图像清单的既有契约一致。
const inheritEmbedding =
- p.id === 'xd' &&
+ p.id === "xd" &&
p.embeddingModels === undefined &&
bundled.embeddingModels !== undefined &&
bundledAccess !== undefined &&
@@ -380,10 +414,12 @@ export function mergeWithBundled(primary: Catalog): Catalog {
}
return {
...p,
- ...(p.access === undefined && bundledAccess !== undefined ? { access: bundledAccess } : {}),
+ ...(p.access === undefined && bundledAccess !== undefined
+ ? { access: bundledAccess }
+ : {}),
...(inheritPiRuntime
? {
- agents: [...p.agents, 'pi' as const],
+ agents: [...p.agents, "pi" as const],
models: { ...p.models, pi: bundled.models.pi },
}
: {}),
@@ -396,7 +432,8 @@ export function mergeWithBundled(primary: Catalog): Catalog {
? {
codex: {
...p.routing.codex!,
- supportsResponsesCustomTools: bundledResponsesCustomToolCapability,
+ supportsResponsesCustomTools:
+ bundledResponsesCustomToolCapability,
},
}
: {}),
@@ -406,7 +443,8 @@ export function mergeWithBundled(primary: Catalog): Catalog {
...(inheritImage
? {
imageModels: bundled.imageModels,
- ...(p.imageDefaults === undefined && bundled.imageDefaults !== undefined
+ ...(p.imageDefaults === undefined &&
+ bundled.imageDefaults !== undefined
? { imageDefaults: bundled.imageDefaults }
: {}),
}
@@ -414,7 +452,8 @@ export function mergeWithBundled(primary: Catalog): Catalog {
...(inheritVideo
? {
videoModels: bundled.videoModels,
- ...(p.videoDefaults === undefined && bundled.videoDefaults !== undefined
+ ...(p.videoDefaults === undefined &&
+ bundled.videoDefaults !== undefined
? { videoDefaults: bundled.videoDefaults }
: {}),
}
@@ -422,7 +461,8 @@ export function mergeWithBundled(primary: Catalog): Catalog {
...(inheritEmbedding
? {
embeddingModels: bundled.embeddingModels,
- ...(p.embeddingDefaults === undefined && bundled.embeddingDefaults !== undefined
+ ...(p.embeddingDefaults === undefined &&
+ bundled.embeddingDefaults !== undefined
? { embeddingDefaults: bundled.embeddingDefaults }
: {}),
}
@@ -441,11 +481,15 @@ export function mergeWithBundled(primary: Catalog): Catalog {
// 远端独有项按远端原序追加。避免旧远端的非空 presets 整段遮掉新版客户端内置条目。
const primaryPresets = primary.presets ?? [];
const bundledPresets = BUNDLED_CATALOG.presets ?? [];
- const primaryPresetsById = new Map(primaryPresets.map((preset) => [preset.id, preset]));
+ const primaryPresetsById = new Map(
+ primaryPresets.map((preset) => [preset.id, preset]),
+ );
const bundledPresetIds = new Set(bundledPresets.map((preset) => preset.id));
const presets = bundledPresets.map((bundled) => {
const remote = primaryPresetsById.get(bundled.id);
- return remote ? backfillPresetMetadata(remote, bundled, allowLegacyPiBackfill) : bundled;
+ return remote
+ ? backfillPresetMetadata(remote, bundled, allowLegacyPiBackfill)
+ : bundled;
});
for (const preset of primaryPresets) {
if (!bundledPresetIds.has(preset.id)) presets.push(preset);
@@ -458,11 +502,18 @@ export function mergeWithBundled(primary: Catalog): Catalog {
version: primary.version,
providers: merged,
...(presets && presets.length > 0 ? { presets } : {}),
- ...(selectedRegistry.modelRegistry ? { modelRegistry: selectedRegistry.modelRegistry } : {}),
+ ...(selectedRegistry.modelRegistry
+ ? { modelRegistry: selectedRegistry.modelRegistry }
+ : {}),
};
}
-function log(io: CatalogIO, level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>): void {
+function log(
+ io: CatalogIO,
+ level: "info" | "warn" | "error",
+ msg: string,
+ meta?: Record<string, unknown>,
+): void {
io.log?.(level, `[model-providers] ${msg}`, meta);
}
@@ -476,10 +527,17 @@ function registryUpdatedAt(catalog: Catalog): number | null {
function selectNewerModelRegistry(
primary: Catalog,
fallback: Catalog,
-): { modelRegistry: Catalog['modelRegistry']; fromFallback: boolean } {
+): { modelRegistry: Catalog["modelRegistry"]; fromFallback: boolean } {
if (primary.modelRegistry && fallback.modelRegistry) {
- const relation = compareModelRegistryRevisions(primary.modelRegistry, fallback.modelRegistry);
- if (relation === 'older' || relation === 'conflict' || relation === 'invalid-incoming') {
+ const relation = compareModelRegistryRevisions(
+ primary.modelRegistry,
+ fallback.modelRegistry,
+ );
+ if (
+ relation === "older" ||
+ relation === "conflict" ||
+ relation === "invalid-incoming"
+ ) {
// 同 revision 异内容是非法重发;fallback 是已经随客户端发布/缓存验证过的
// LKG,启动期也必须保它,不能只在在线 refresh 路径防守。
return { modelRegistry: fallback.modelRegistry, fromFallback: true };
@@ -489,7 +547,10 @@ function selectNewerModelRegistry(
if (primary.modelRegistry) {
return { modelRegistry: primary.modelRegistry, fromFallback: false };
}
- return { modelRegistry: fallback.modelRegistry, fromFallback: fallback.modelRegistry !== undefined };
+ return {
+ modelRegistry: fallback.modelRegistry,
+ fromFallback: fallback.modelRegistry !== undefined,
+ };
}
/**
@@ -506,11 +567,14 @@ function preserveNewerCachedCatalog(
remote: Catalog,
cached: Catalog,
): { catalog: Catalog; tieConflict: boolean } {
- const decision = decideModelRegistrySnapshot(remote.modelRegistry, cached.modelRegistry);
- if (decision === 'preserve-current-conflict') {
+ const decision = decideModelRegistrySnapshot(
+ remote.modelRegistry,
+ cached.modelRegistry,
+ );
+ if (decision === "preserve-current-conflict") {
return { catalog: cached, tieConflict: true };
}
- if (decision === 'preserve-current') {
+ if (decision === "preserve-current") {
return { catalog: cached, tieConflict: false };
}
return { catalog: remote, tieConflict: false };
@@ -536,17 +600,21 @@ export async function loadCatalogWithSource(
const text = await io.readFile(cfg.localPath);
if (text != null) {
const parsed = parseCatalog(text);
- log(io, 'info', 'loaded catalog from local path', { path: cfg.localPath });
+ log(io, "info", "loaded catalog from local path", {
+ path: cfg.localPath,
+ });
return {
catalog: mergeWithBundled(parsed),
authorityCatalog: parsed,
- source: 'local',
- capabilityEvidence: 'current',
+ source: "local",
+ capabilityEvidence: "current",
unverifiedXdMediaKinds: unverifiedXdMediaKindsForPrimary(parsed),
};
}
} catch (err) {
- log(io, 'warn', 'local catalog read/parse failed, falling back', { err: String(err) });
+ log(io, "warn", "local catalog read/parse failed, falling back", {
+ err: String(err),
+ });
}
}
@@ -560,11 +628,16 @@ export async function loadCatalogWithSource(
: []
: [
...(url ? [{ url, allowLegacyModelMeta: false }] : []),
- ...(fallbackUrl ? [{ url: fallbackUrl, allowLegacyModelMeta: true }] : []),
+ ...(fallbackUrl
+ ? [{ url: fallbackUrl, allowLegacyModelMeta: true }]
+ : []),
];
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 configuredBudget =
+ cfg.remoteBudgetMs ?? DEFAULT_REMOTE_CATALOG_BUDGET_MS;
+ const budgetMs = Number.isFinite(configuredBudget)
+ ? Math.max(0, configuredBudget)
+ : 0;
const deadline = now() + budgetMs;
for (const { url: remoteUrl, allowLegacyModelMeta } of remoteSources) {
const logUrl = catalogUrlForLog(remoteUrl);
@@ -573,9 +646,8 @@ export async function loadCatalogWithSource(
try {
const text = await io.fetchText(remoteUrl, remainingMs);
let parsed = parseRemoteCatalog(text, allowLegacyModelMeta);
- let capabilityEvidence: CatalogCapabilityEvidence = allowLegacyModelMeta
- ? 'fallback'
- : 'current';
+ let capabilityEvidence: CatalogCapabilityEvidence =
+ allowLegacyModelMeta ? "fallback" : "current";
// Never propagate the retired compatibility block into a newly written LKG.
let cacheText = allowLegacyModelMeta ? JSON.stringify(parsed) : text;
const remoteRegistryUpdatedAt = registryUpdatedAt(parsed);
@@ -583,18 +655,21 @@ export async function loadCatalogWithSource(
try {
const cachedText = await io.readCache(remoteUrl);
if (cachedText !== null) {
- const cached = parseRemoteCatalog(cachedText, allowLegacyModelMeta);
+ const cached = parseRemoteCatalog(
+ cachedText,
+ allowLegacyModelMeta,
+ );
const selected = preserveNewerCachedCatalog(parsed, cached);
if (selected.catalog !== parsed) {
parsed = selected.catalog;
cacheText = JSON.stringify(selected.catalog);
- capabilityEvidence = 'fallback';
+ capabilityEvidence = "fallback";
log(
io,
- 'warn',
+ "warn",
selected.tieConflict
- ? 'remote registry republished the same updatedAt with different content; keeping LKG'
- : 'remote catalog registry is older than LKG; preserving complete newer snapshot',
+ ? "remote registry republished the same updatedAt with different content; keeping LKG"
+ : "remote catalog registry is older than LKG; preserving complete newer snapshot",
{
url: logUrl,
remoteUpdatedAt: remoteRegistryUpdatedAt,
@@ -604,75 +679,103 @@ export async function loadCatalogWithSource(
}
}
} catch (err) {
- log(io, 'warn', 'cached catalog could not be compared with remote snapshot', {
- url: logUrl,
- err: remoteErrorForLog(err, remoteUrl, logUrl),
- });
+ log(
+ io,
+ "warn",
+ "cached catalog could not be compared with remote snapshot",
+ {
+ url: logUrl,
+ err: remoteErrorForLog(err, remoteUrl, logUrl),
+ },
+ );
}
}
if (io.writeCache) {
try {
const committedText = await io.writeCache(remoteUrl, cacheText);
- if (typeof committedText === 'string') {
- const committed = parseRemoteCatalog(committedText, allowLegacyModelMeta);
- const selected = preserveNewerCachedCatalog(parsed, committed).catalog;
+ if (typeof committedText === "string") {
+ const committed = parseRemoteCatalog(
+ committedText,
+ allowLegacyModelMeta,
+ );
+ const selected = preserveNewerCachedCatalog(
+ parsed,
+ committed,
+ ).catalog;
if (selected !== parsed) {
parsed = selected;
- capabilityEvidence = 'fallback';
- log(io, 'warn', 'serialized LKG commit preserved a newer catalog snapshot', {
- url: logUrl,
- remoteUpdatedAt: remoteRegistryUpdatedAt,
- committedUpdatedAt: registryUpdatedAt(committed),
- });
+ capabilityEvidence = "fallback";
+ log(
+ io,
+ "warn",
+ "serialized LKG commit preserved a newer catalog snapshot",
+ {
+ url: logUrl,
+ remoteUpdatedAt: remoteRegistryUpdatedAt,
+ committedUpdatedAt: registryUpdatedAt(committed),
+ },
+ );
}
}
} catch (err) {
- log(io, 'warn', 'valid remote catalog loaded but LKG write failed', {
- url: logUrl,
- err: remoteErrorForLog(err, remoteUrl, logUrl),
- });
+ log(
+ io,
+ "warn",
+ "valid remote catalog loaded but LKG write failed",
+ {
+ url: logUrl,
+ err: remoteErrorForLog(err, remoteUrl, logUrl),
+ },
+ );
}
}
- log(io, 'info', 'loaded catalog from remote', { url: logUrl });
+ log(io, "info", "loaded catalog from remote", { url: logUrl });
return {
catalog: mergeWithBundled(parsed),
// The migration OSS fallback is compatibility data, not the daily Cindy Server source.
authorityCatalog: allowLegacyModelMeta ? null : parsed,
- source: 'remote',
+ source: "remote",
capabilityEvidence,
unverifiedXdMediaKinds:
- capabilityEvidence === 'current'
+ capabilityEvidence === "current"
? unverifiedXdMediaKindsForPrimary(parsed)
: ALL_XD_MEDIA_KINDS,
};
} catch (err) {
- log(io, 'warn', 'remote catalog read/parse failed, trying fallback', {
+ log(io, "warn", "remote catalog read/parse failed, trying fallback", {
url: logUrl,
err: remoteErrorForLog(err, remoteUrl, logUrl),
});
}
} else {
- log(io, 'warn', 'remote catalog fallback budget exhausted, trying cache', {
- url: logUrl,
- });
+ log(
+ io,
+ "warn",
+ "remote catalog fallback budget exhausted, trying cache",
+ {
+ url: logUrl,
+ },
+ );
}
if (io.readCache) {
try {
const cached = await io.readCache(remoteUrl);
if (cached !== null) {
const parsed = parseRemoteCatalog(cached, allowLegacyModelMeta);
- log(io, 'info', 'loaded last-known-good catalog snapshot', { url: logUrl });
+ log(io, "info", "loaded last-known-good catalog snapshot", {
+ url: logUrl,
+ });
return {
catalog: mergeWithBundled(parsed),
// A cached legacy OSS snapshot stays below the local Pi protocol authorities.
authorityCatalog: allowLegacyModelMeta ? null : parsed,
- source: 'cache',
- capabilityEvidence: 'fallback',
+ source: "cache",
+ capabilityEvidence: "fallback",
unverifiedXdMediaKinds: ALL_XD_MEDIA_KINDS,
};
}
} catch (err) {
- log(io, 'warn', 'cached catalog read/parse failed, trying fallback', {
+ log(io, "warn", "cached catalog read/parse failed, trying fallback", {
url: logUrl,
err: remoteErrorForLog(err, remoteUrl, logUrl),
});
@@ -682,12 +785,12 @@ export async function loadCatalogWithSource(
}
// 3) 兜底:内置 bundled。
- log(io, 'info', 'using bundled catalog');
+ log(io, "info", "using bundled catalog");
return {
catalog: BUNDLED_CATALOG,
authorityCatalog: null,
- source: 'bundled',
- capabilityEvidence: 'fallback',
+ source: "bundled",
+ capabilityEvidence: "fallback",
unverifiedXdMediaKinds: ALL_XD_MEDIA_KINDS,
};
}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index dea3501fcc..9c302316ad 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -1,3 +1,4 @@
+import type { ModelMetadata } from "./modelMetadataLayers.js";
/**
* @cindy/model-providers — 类型定义。
*
@@ -17,16 +18,24 @@
* 本包零运行时依赖:`AgentKind` / `Effort` 在此就地定义(与 maker-core 的同名
* 联合保持一致),不 import maker-core,保证可作为独立能力复用。
*/
-import type { ModelRegistry } from './modelAccessBean.js';
+import type { ModelRegistry } from "./modelAccessBean.js";
/** 承载模型的 agent runtime —— 与 maker-core AgentKind 对齐。 */
-export type AgentKind = 'claude-code' | 'codex' | 'pi';
+export type AgentKind = "claude-code" | "codex" | "pi";
/** 推理强度档位 —— 与 maker-core Effort 对齐。 */
-export type Effort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
+export type Effort =
+ "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "ultra";
/** Pi 原生支持的 reasoning/thinking 档位(Pi 不支持 Cindy 的 ultra 档)。 */
-export const PI_REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
+export const PI_REASONING_EFFORTS = [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+] as const;
export type PiReasoningEffort = (typeof PI_REASONING_EFFORTS)[number];
/**
@@ -35,27 +44,25 @@ export type PiReasoningEffort = (typeof PI_REASONING_EFFORTS)[number];
* sparse per-model override for newly released models or protocol corrections.
*/
export const PI_MODEL_APIS = [
- 'anthropic-messages',
- 'openai-responses',
- 'openai-completions',
- 'google-generative-ai',
+ "anthropic-messages",
+ "openai-responses",
+ "openai-completions",
+ "google-generative-ai",
] as const;
export type PiModelApi = (typeof PI_MODEL_APIS)[number];
/** Provider runtime 上游实际接受的推理 wire protocol。 */
export type ProviderWireProtocol =
- | 'anthropic-messages'
- | 'openai-responses'
- | 'openai-chat';
+ "anthropic-messages" | "openai-responses" | "openai-chat";
/** Codex 通过本地 bridge 兼容的两种非原生 Responses wire protocol。 */
export type CodexCompatibilityWireProtocol = Extract<
ProviderWireProtocol,
- 'anthropic-messages' | 'openai-chat'
+ "anthropic-messages" | "openai-chat"
>;
/** 供应商来源:内置 vs 用户自定义(自定义本轮不实现,类型先留位)。 */
-export type ProviderSource = 'builtin' | 'user';
+export type ProviderSource = "builtin" | "user";
/** 用户连接该供应商的鉴权方式(决定设置页的连接 UI)。
* - oauth : 走 OAuth 登录(Claude.ai 订阅 / Codex 订阅)
@@ -63,16 +70,16 @@ export type ProviderSource = 'builtin' | 'user';
* - managed : 由平台托管 / 自动下发(XD 网关 key 登录后自动同步)
* - none : 上游不要求客户端鉴权(本机 LiteLLM / Ollama 等受信代理)
*/
-export type AuthMethod = 'oauth' | 'apiKey' | 'managed' | 'none';
+export type AuthMethod = "oauth" | "apiKey" | "managed" | "none";
/**
* 模型额度的来源(展示 / 产品语义),与 `auth` 的连接协议刻意分开:
* OAuth 不必然代表订阅,API key 也不应靠模型名或图标推断。
*/
export type ProviderAccess =
- | { kind: 'subscription'; product: string }
- | { kind: 'api' }
- | { kind: 'managed' };
+ | { kind: "subscription"; product: string }
+ | { kind: "api" }
+ | { kind: "managed" };
/**
* 通用路由器消费的「钥匙策略」——决定一笔请求到达上游时的鉴权头怎么处理。
@@ -92,12 +99,12 @@ export type ProviderAccess =
* 防把 Claude.ai / ChatGPT 订阅凭证泄漏给本地或自托管服务。
*/
export type AuthStrategy =
- | 'oauth-passthrough'
- | 'provider-oauth-header'
- | 'api-key-header'
- | 'gateway-key'
- | 'oauth-token'
- | 'none';
+ | "oauth-passthrough"
+ | "provider-oauth-header"
+ | "api-key-header"
+ | "gateway-key"
+ | "oauth-token"
+ | "none";
/**
* 授权(OAuth)供应商描述符 —— 让「接一家标准 OAuth 供应商」退化成目录数据。
@@ -125,7 +132,7 @@ interface OAuthProviderDescriptorBase {
export interface OAuthAuthorizationCodeDescriptor extends OAuthProviderDescriptorBase {
/** 缺省保持历史目录兼容;等价于 `authorization-code`。 */
- flow?: 'authorization-code';
+ flow?: "authorization-code";
/** 授权端点(authorization_endpoint)。 */
authorizeUrl: string;
/**
@@ -140,7 +147,7 @@ export interface OAuthAuthorizationCodeDescriptor extends OAuthProviderDescripto
}
export interface OAuthDeviceCodeDescriptor extends OAuthProviderDescriptorBase {
- flow: 'device-code';
+ flow: "device-code";
/** 申请 device_code / user_code 的端点(device_authorization_endpoint)。 */
deviceAuthorizationUrl: string;
/** 追加到设备授权 POST body 的厂商参数。 */
@@ -151,8 +158,7 @@ export interface OAuthDeviceCodeDescriptor extends OAuthProviderDescriptorBase {
}
export type OAuthProviderDescriptor =
- | OAuthAuthorizationCodeDescriptor
- | OAuthDeviceCodeDescriptor;
+ OAuthAuthorizationCodeDescriptor | OAuthDeviceCodeDescriptor;
/**
* 路由描述符(per provider × runtime)。喂给 host 侧通用路由器,决定请求的
@@ -198,7 +204,7 @@ export interface RoutingDescriptor {
headerDelete?: string[];
/** 额外固定请求头覆盖(少数特例用;多数由 authStrategy 隐含)。 */
headerOverride?: Record<string, string>;
- headerOverrideState?: 'configured' | 'unknown';
+ headerOverrideState?: "configured" | "unknown";
/** 可选 quirk 适配钩子名(对齐 OpenCode custom loader,承接无法纯数据表达的特例)。 */
adapter?: string;
/**
@@ -267,12 +273,16 @@ export interface ModelCost {
* 跨 provider(如 gpt-5.5 同时由 openai 与 xd 提供)则必须元数据一致(见 catalog.ts 校验)。
*/
export interface CatalogModel {
+ userModelConfig?: ProviderRuntimeModelConfig;
+ catalogPresetId?: string;
+ discoveredMetadata?: ModelMetadata;
+ nameExplicit?: boolean;
/** Canonical model API from the accepted Registry; null explicitly means unverified. */
nativeApi?: PiModelApi | null;
/** 与 maker-core 现有 model id 一致(如 'claude-opus-4-8' / 'gpt-5.5' / 'codex/gpt-5.5')。 */
id: string;
/** Server entitlement state. Paid-locked models remain present for UI but are never routable. */
- availability?: 'available' | 'requires_payment';
+ availability?: "available" | "requires_payment";
/** Sparse PI protocol override; absence means use PI's bundled model catalog. */
piApi?: PiModelApi;
/** 同一 provider/runtime 内该模型的上游覆盖;缺省使用 provider 级路由。 */
@@ -347,7 +357,7 @@ export interface CatalogModel {
* Model-specific effort 显示名覆盖(= maker-core ModelDescriptor.effortDisplayNames)。
* 缺省时回退统一档名词表(桌面 i18n `effortLevels.*` / 手机 MOBILE_EFFORT_LABELS)→
* agent 级 effortLevels。当前 catalog 无覆盖项(2026-07 档名统一后清空),机制保留。
- */
+ */
effortDisplayNames?: Partial<Record<Effort, string>>;
/** 默认 effort;null = 不支持。 */
defaultEffort: Effort | null;
@@ -402,7 +412,7 @@ export interface CatalogModel {
* 「discovery 仍能发现但远端已判死」的条目标记为 'retired',供 modelList 准入过滤
* (新选择禁止,keepSelected 运行会话豁免;完整 local addition 可显式复活)。
*/
- status?: 'active' | 'alpha' | 'deprecated' | 'retired';
+ status?: "active" | "alpha" | "deprecated" | "retired";
/**
* 该模型在「设置 → 模型供应商」展开列表里**默认是否开启显示**(缺省 ⇒ true,即默认开)。
*
@@ -449,7 +459,7 @@ export interface CatalogModel {
export interface ProviderMediaModel {
id: string;
name: string;
- availability?: 'available' | 'requires_payment';
+ availability?: "available" | "requires_payment";
modalities?: { input: string[]; output: string[] };
officialDocs?: string;
disabled?: boolean;
@@ -547,6 +557,8 @@ export interface Provider {
* 并随用户配置持久化,避免已知长上下文模型被错误降级。
*/
export interface ProviderRuntimeModelConfig {
+ discoveredMetadata?: ModelMetadata;
+ nameExplicit?: boolean;
id: string;
name: string;
/** Per-model PI protocol override; provider wireProtocol remains the fallback. */
@@ -609,7 +621,7 @@ export interface ProviderPresetRuntime {
* 供应商预设 —— 降低自定义供应商接入摩擦的**纯 UI 模板数据**(不参与路由 / 不是 Provider)。
*
* 与 `Provider` 的区别:预设只在「创建自定义供应商」对话框里消费,选中即快照进用户自己的
- * `CustomProviderConfig`,之后与预设脱钩(预设更新不回写已创建的供应商,override 语义)。
+ * `CustomProviderConfig`,地址与用户修改保持不变;新建连接可通过 catalogPresetId 继承当前模型默认资料。
* 数据随目录走 OSS 热更:各家 baseUrl / 模型 id 变化只需推数据,无需发版。
*/
export interface ProviderPreset {
@@ -634,18 +646,18 @@ export interface ProviderPreset {
* 不需要回答「你在哪个地区」,可达性由「测试连接」实测裁决。缺省 = 区域中立
* (单端点全球服务的厂商,如 OpenRouter / DeepSeek),排序时居中。
*/
- regionHint?: 'cn' | 'global';
+ regionHint?: "cn" | "global";
/**
* 预设的鉴权形态。缺省 = API key;`none` 用于明确不要求客户端凭证的本机 / 自托管代理。
* 创建后会快照进 CustomProviderConfig,不随预设后续更新。
*/
- authMethod?: 'apiKey' | 'none';
+ authMethod?: "apiKey" | "none";
/** per-runtime 预填数据(至少一个)。 */
runtimes: Partial<Record<AgentKind, ProviderPresetRuntime>>;
}
/** 客户端实际构建区域;模型预设排序只看该版本身份,不看 UI 语言。 */
-export type PresetSortRegion = 'cn' | 'global' | 'dev';
+export type PresetSortRegion = "cn" | "global" | "dev";
/** 完整目录(OSS / 本地 / 内置 三处都是这个形状)。 */
export interface Catalog {
@@ -672,6 +684,8 @@ export interface Catalog {
* 两种端点,则两个 runtime 各有独立的 baseURL / 模型 / headers(见 CustomProviderConfig.runtimes)。
*/
export interface CustomProviderRuntimeConfig {
+ /** Follow current model defaults from this preset while its endpoint/protocol still match. */
+ catalogPresetId?: string;
/** 上游 wire protocol;缺省由 runtime agent 推导(Codex=Responses,Claude=Messages)。 */
wireProtocol?: ProviderWireProtocol;
/** 该 runtime 的兼容上游 base URL(cc=Anthropic 端点 / codex=OpenAI 端点)。 */
@@ -688,7 +702,7 @@ export interface CustomProviderRuntimeConfig {
*/
headers?: Record<string, string>;
/** Transient non-secret state; main normalization strips it before persistence. */
- headersState?: 'configured' | 'unknown';
+ headersState?: "configured" | "unknown";
/**
* 可选的「列模型」端点(「获取模型列表」按钮用;缺省由 baseUrl 推导 `…/v1/models`)。
* 从预设创建时随 `ProviderPresetRuntime.modelsUrl` 快照进来并持久化,编辑态仍可再拉。
@@ -725,9 +739,9 @@ export interface CustomProviderConfig {
* Bearer;此形态下不再使用 per-runtime API key。
*/
auth?:
- | { method: 'apiKey'; oauth?: never }
- | { method: 'oauth'; oauth: OAuthProviderDescriptor }
- | { method: 'none'; oauth?: never };
+ | { method: "apiKey"; oauth?: never }
+ | { method: "oauth"; oauth: OAuthProviderDescriptor }
+ | { method: "none"; oauth?: never };
/** per-runtime 独立配置(键为 agent,只含已配置的 runtime;至少一个)。 */
runtimes: Partial<Record<AgentKind, CustomProviderRuntimeConfig>>;
}
diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.ts
index be24243c79..3abb624f46 100644
--- a/packages/model-providers/src/user-provider.ts
+++ b/packages/model-providers/src/user-provider.ts
@@ -1,3 +1,11 @@
+import {
+ expandedRegistryEntries,
+ resolveModelMetadata,
+ applyModelMetadata,
+ pickModelMetadata,
+ runtimeUserModelMetadata,
+ type ModelMetadata,
+} from "./modelMetadataLayers.js";
/**
* 用户自定义供应商:把 `CustomProviderConfig` 展开成标准 `Provider`(纯逻辑,零依赖)。
*
@@ -23,7 +31,11 @@ import type {
} from "./types.js";
import type { ModelRegistry } from "./modelAccessBean.js";
import { isLoopbackProviderUrl } from "./provider-url.js";
-import { clampEffortToSupported, modelDefaultEffort, defaultEffortForCapabilities } from "./effortResolution.js";
+import {
+ clampEffortToSupported,
+ modelDefaultEffort,
+ defaultEffortForCapabilities,
+} from "./effortResolution.js";
/** 自定义模型缺省上下文窗口(用户不填元数据时的保守默认,仅用于展示)。 */
export const DEFAULT_CUSTOM_CONTEXT_WINDOW = 200_000;
@@ -48,6 +60,12 @@ export function storedCustomProviderId(providerId: string): string {
: providerId;
}
+function withoutTrailingSlashes(value: string): string {
+ let end = value.length;
+ while (end > 0 && value[end - 1] === "/") end -= 1;
+ return value.slice(0, end);
+}
+
function isOfficialXaiApiUpstream(upstream: string | undefined): boolean {
try {
const url = new URL(upstream ?? "");
@@ -135,7 +153,16 @@ interface RegistryEffortMetadata {
}
function toRegistryEffortMetadata(
- entry: { efforts?: readonly Effort[]; defaultEffort?: Effort | null; perAgent?: Partial<Record<string, { efforts?: readonly Effort[]; defaultEffort?: Effort | null }>> },
+ entry: {
+ efforts?: readonly Effort[];
+ defaultEffort?: Effort | null;
+ perAgent?: Partial<
+ Record<
+ string,
+ { efforts?: readonly Effort[]; defaultEffort?: Effort | null }
+ >
+ >;
+ },
agent: AgentKind,
): RegistryEffortMetadata | undefined {
const perAgent = entry.perAgent?.[agent];
@@ -143,9 +170,10 @@ function toRegistryEffortMetadata(
if (!efforts) return undefined;
const declaredDefault = modelDefaultEffort(entry);
const defaultEffort =
- efforts.length === 0 || declaredDefault === null ? null
+ efforts.length === 0 || declaredDefault === null
+ ? null
: declaredDefault !== undefined
- ? clampEffortToSupported(declaredDefault, efforts) as Effort
+ ? (clampEffortToSupported(declaredDefault, efforts) as Effort)
: defaultEffortForCapabilities(efforts);
return { efforts: [...efforts], defaultEffort };
}
@@ -189,7 +217,7 @@ function registryEffortMetadata(
if (agent === "pi" || !registry) return undefined;
// Stage 1 — exact lookup: only the original modelId.
- const exactMatches = registry.models.filter((entry) =>
+ const exactMatches = expandedRegistryEntries(registry).filter((entry) =>
entry.routes.some(
(route) =>
route.agents.includes(agent) &&
@@ -205,11 +233,11 @@ function registryEffortMetadata(
// (e.g. "openai/gpt-5.6-sol") can match registry entries whose
// route.modelId is just "gpt-5.6-sol".
const stripped = new Set<string>();
- for (const prefix of ['openai/', 'xd/', 'chatgpt/']) {
+ for (const prefix of ["openai/", "xd/", "chatgpt/"]) {
if (modelId.startsWith(prefix)) stripped.add(modelId.slice(prefix.length));
}
if (stripped.size === 0) return undefined;
- const fallbackMatches = registry.models.filter((entry) =>
+ const fallbackMatches = expandedRegistryEntries(registry).filter((entry) =>
entry.routes.some(
(route) =>
route.agents.includes(agent) &&
@@ -231,10 +259,9 @@ function registrySupportsFastMode(
): boolean {
if (agent !== "codex" || !registry) return false;
- const matches = registry.models.filter((entry) =>
+ const matches = expandedRegistryEntries(registry).filter((entry) =>
entry.routes.some(
- (route) =>
- route.agents.includes(agent) && route.modelId === modelId,
+ (route) => route.agents.includes(agent) && route.modelId === modelId,
),
);
return (
@@ -256,6 +283,7 @@ function toCatalogModel(
providerId: string,
agent: AgentKind,
modelRegistry: ModelRegistry | null | undefined,
+ providerDefaults?: ModelMetadata,
): CatalogModel {
// 显式 runtime 能力优先:reasoning:true 才导出 efforts;false = 明确无思考档。
// 字段缺省才走历史 fallback(Pi 空档 / 其它自定义 Provider 的 CUSTOM_EFFORTS)。
@@ -268,24 +296,26 @@ function toCatalogModel(
? []
: (CUSTOM_EFFORTS[agent] ?? []);
const registryEfforts =
- m.reasoning !== undefined
+ m.reasoning !== undefined || modelRegistry?.schemaVersion === 4
? undefined
: registryEffortMetadata(modelRegistry, m.id, agent);
- const supportsFastMode = registrySupportsFastMode(
- modelRegistry,
- m.id,
- agent,
- );
+ const supportsFastMode =
+ modelRegistry?.schemaVersion !== 4 &&
+ registrySupportsFastMode(modelRegistry, m.id, agent);
const effectiveEfforts = registryEfforts?.efforts ?? efforts;
const defaultEffort =
- registryEfforts !== undefined ? registryEfforts.defaultEffort :
- (m.reasoning === true &&
- m.reasoningDefaultEffort &&
- effectiveEfforts.includes(m.reasoningDefaultEffort)
- ? m.reasoningDefaultEffort
- : defaultEffortForCapabilities(effectiveEfforts));
- return {
+ registryEfforts !== undefined
+ ? registryEfforts.defaultEffort
+ : m.reasoning === true &&
+ m.reasoningDefaultEffort &&
+ effectiveEfforts.includes(m.reasoningDefaultEffort)
+ ? m.reasoningDefaultEffort
+ : defaultEffortForCapabilities(effectiveEfforts);
+ const model: CatalogModel = {
+ userModelConfig: { ...m },
id: m.id,
+ discoveredMetadata: m.discoveredMetadata,
+ nameExplicit: m.nameExplicit,
name: m.name,
...(agent === "pi" && m.piApi ? { piApi: m.piApi } : {}),
...(m.route ? { route: { ...m.route } } : {}),
@@ -307,6 +337,22 @@ function toCatalogModel(
...(m.thinkingToggle === true ? { thinkingToggle: true } : {}),
...(supportsFastMode ? { supportsFastMode: true } : {}),
};
+ const user = runtimeUserModelMetadata(m);
+ const resolved =
+ modelRegistry?.schemaVersion === 4 ||
+ m.discoveredMetadata ||
+ providerDefaults
+ ? resolveModelMetadata(
+ modelRegistry ?? undefined,
+ providerId,
+ m.id,
+ m.discoveredMetadata,
+ pickModelMetadata(user),
+ agent,
+ providerDefaults,
+ )
+ : pickModelMetadata(user);
+ return applyModelMetadata(model, resolved);
}
function defaultWireProtocol(agent: AgentKind): ProviderWireProtocol {
@@ -334,11 +380,11 @@ function toRouting(
const r: RoutingDescriptor = {
upstream: baseUrl,
authStrategy: strategy,
- ...(agent === 'codex'
- && (wireProtocol ?? defaultWireProtocol(agent)) === 'openai-responses'
+ ...(agent === "codex" &&
+ (wireProtocol ?? defaultWireProtocol(agent)) === "openai-responses"
? { supportsResponsesCustomTools: false }
: {}),
- ...(agent === 'codex' && supportsImageGeneration === true
+ ...(agent === "codex" && supportsImageGeneration === true
? { supportsImageGeneration: true }
: {}),
...(strategy === "none" &&
@@ -347,7 +393,8 @@ function toRouting(
? { disabled: true }
: {}),
...(requestPath ? { requestPath } : {}),
- ...(wireProtocol && (agent === 'pi' || wireProtocol !== defaultWireProtocol(agent))
+ ...(wireProtocol &&
+ (agent === "pi" || wireProtocol !== defaultWireProtocol(agent))
? { wireProtocol }
: {}),
};
@@ -370,6 +417,7 @@ function toRouting(
*/
export interface BuildUserProviderOptions {
modelRegistry?: ModelRegistry | null;
+ presets?: readonly import("./types.js").ProviderPreset[];
}
export function buildUserProvider(
@@ -401,9 +449,47 @@ export function buildUserProvider(
rt.piCatalogProviderId,
rt.supportsImageGeneration,
);
- models[agent] = rt.models.map((m) =>
- toCatalogModel(m, config.id, agent, options.modelRegistry),
+ const preset = options.presets?.find(
+ (preset) => preset.id === rt.catalogPresetId,
);
+ const presetRuntime = preset?.runtimes[agent];
+ const followsPreset =
+ presetRuntime &&
+ withoutTrailingSlashes(rt.baseUrl) ===
+ withoutTrailingSlashes(presetRuntime.baseUrl) &&
+ (rt.wireProtocol ?? defaultWireProtocol(agent)) ===
+ (presetRuntime.wireProtocol ?? defaultWireProtocol(agent)) &&
+ (rt.requestPath ?? "") === (presetRuntime.requestPath ?? "");
+ models[agent] = rt.models.map((m) => {
+ const presetModel = followsPreset
+ ? presetRuntime.models.find((model) => model.id === m.id)
+ : undefined;
+ const sameRoute =
+ m.route?.baseUrl === presetModel?.route?.baseUrl &&
+ m.route?.wireProtocol === presetModel?.route?.wireProtocol &&
+ m.route?.requestPath === presetModel?.route?.requestPath;
+ const defaults =
+ presetModel && sameRoute
+ ? pickModelMetadata({
+ ...presetModel,
+ efforts:
+ presetModel.reasoning === false
+ ? []
+ : presetModel.reasoningEfforts,
+ defaultEffort: presetModel.reasoningDefaultEffort,
+ })
+ : undefined;
+ return {
+ ...toCatalogModel(
+ m,
+ followsPreset && sameRoute ? preset!.id : config.id,
+ agent,
+ options.modelRegistry,
+ defaults,
+ ),
+ ...(rt.catalogPresetId ? { catalogPresetId: rt.catalogPresetId } : {}),
+ };
+ });
}
return {
id: runtimeProviderId,