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): consume unified remote model catalog (#1174)

Chris Zhang7cae3cb3488f
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 9868ab0096..8659e597a8 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -9,3 +9,17 @@
# 这里同时列出 team 与个人:即使 team 尚未建好或未授权,自动指派仍然生效。
# team 确认可用后可以删掉个人账号那一项。
* @makecindy/maintainers
+
+# 统一模型 registry 的协议、内置快照、远程加载与运行时投影是同一权威面。
+# 最后匹配规则覆盖上面的通用 owner;任何改动都会显式请求 registry owner。
+/.github/CODEOWNERS @zqchris
+/cindy-protocol @zqchris
+/packages/model-providers/catalog/model-registry.json @zqchris
+/packages/model-providers/src/catalog.ts @zqchris
+/packages/model-providers/src/modelRegistry.ts @zqchris
+/packages/model-providers/src/source.ts @zqchris
+/packages/model-providers/src/types.ts @zqchris
+/apps/desktop/src/main/maker-host/active-catalog.ts @zqchris
+/apps/desktop/src/main/model-access/devMetaOverlay.ts @zqchris
+/apps/desktop/src/main/usage/modelPriceOverrideStore.ts @zqchris
+/apps/desktop/src/main/usage/modelPricing.ts @zqchris
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 7cde3ebb46..69e0a72ea5 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -371,24 +371,40 @@ describe('maker:event hot path ordering', () => {
expect(codexDoneSource).toContain('? codexSubscriptionUsageModelKey(pricingModel)');
expect(codexDoneSource).toContain(': codexApiUsageModelKey(pricingModel)');
expect(codexDoneSource).toContain('const price = isCodexXaiProviderRoute');
- expect(codexDoneSource).toContain('? getSubscriptionDirectValuePrice(pricingModel)');
- expect(codexDoneSource).toContain('? getCodexSubscriptionValuePrice(pricingModel, pricing)');
+ expect(codexDoneSource).toContain(
+ "? getSubscriptionDirectValuePrice(pricingModel, 'codex', pricing)",
+ );
+ // 订阅估值按显式来源取各自 registry 日期定价:内置 anthropic(access.kind=subscription)
+ // 不再被记成 #billing=api;默认/openai 仍走 OpenAI 价表。
+ expect(codexDoneSource).toContain("sessionProviderAccessKind === 'subscription'");
+ expect(codexDoneSource).toContain('isCodexSubscriptionAccessRoute ||');
+ expect(codexDoneSource).toMatch(
+ /\? getCodexProviderSubscriptionValuePrice\(\s*subscriptionValueProviderId,\s*pricingModel,\s*pricing,\s*\)/,
+ );
expect(codexDoneSource).toContain("? getModelPriceQuote(pricing, 'xd', pricingModel)");
- expect(codexDoneSource).toContain('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute');
+ expect(codexDoneSource).toContain(
+ "? getModelPriceQuote(pricing, sessionProvider, pricingModel, 'codex')",
+ );
+ expect(codexDoneSource).toContain('const pricing = isSubscriptionValue');
+ expect(codexDoneSource).not.toContain('isSubscriptionValue && !isCodexXaiProviderRoute');
expect(codexDoneSource).toContain('? await getModelPricing()');
expect(codexDoneSource).toContain("? await getModelPricingForModel('xd', pricingModel)");
expect(codexDoneSource).toContain('price ?? undefined');
- expect(codexDoneSource).toContain('if (!isSubscriptionValue && money)');
+ expect(codexDoneSource).toContain(
+ "if (!isSubscriptionValue && money && price?.source === 'gateway')",
+ );
expect(codexDoneSource).toContain('void recordTurnSpend(money);');
expect(codexDoneSource).toContain('void recordSessionTurnSpend(session.id, money);');
expect(codexDoneSource).toMatch(
- /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*inputTokensDelta: promptTokens,\s*outputTokensDelta: completionTokens,\s*cacheReadTokensDelta: cachedTokens,\s*cacheCreateTokensDelta: 0,\s*\}\)\.finally\(\(\) => rebroadcastCodexTodayUsage\(\)\);[\s\S]*?const pricing = isSubscriptionValue && !isCodexXaiProviderRoute/,
+ /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*inputTokensDelta: promptTokens,\s*outputTokensDelta: completionTokens,\s*cacheReadTokensDelta: cachedTokens,\s*cacheCreateTokensDelta: 0,\s*\}\)\.finally\(\(\) => rebroadcastCodexTodayUsage\(\)\);[\s\S]*?const pricing = isSubscriptionValue/,
);
expect(codexDoneSource).toMatch(
/await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*money,\s*inputTokensDelta: 0,\s*outputTokensDelta: 0,\s*cacheReadTokensDelta: 0,\s*cacheCreateTokensDelta: 0,\s*\}\);/,
);
const costRecordIndex = codexDoneSource.indexOf('void recordTurnSpend(money);');
- const modelCostRecordIndex = codexDoneSource.indexOf('if (!isSubscriptionValue && money)');
+ const modelCostRecordIndex = codexDoneSource.indexOf(
+ "if (!isSubscriptionValue && money && price?.source === 'gateway')",
+ );
const schedulerCostRecordIndex = codexDoneSource.indexOf('await recordSchedulerTurnCost({');
expect(costRecordIndex).toBeGreaterThanOrEqual(0);
expect(modelCostRecordIndex).toBeGreaterThanOrEqual(0);
@@ -420,12 +436,16 @@ describe('maker:event hot path ordering', () => {
expect(claudeDoneSource).toContain("'xd',");
expect(claudeDoneSource).toContain('normalizeModelIdForPricing(deltas[0]?.model)');
expect(claudeDoneSource).toContain(': await getModelPricing();');
- expect(claudeDoneSource).toContain('const { turnMoney, perModel } = resolveClaudeTurnCostSinks(');
+ expect(claudeDoneSource).toContain(
+ 'const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(',
+ );
expect(claudeDoneSource).toContain('providerId: sessionProviderForBilling');
expect(claudeDoneSource).toContain('billingRoute,');
expect(claudeDoneSource).toContain('recordTurnSpend(turnMoney);');
expect(claudeDoneSource).toContain('recordSessionTurnSpend(session.id, turnMoney);');
- expect(claudeDoneSource).toContain('money: m.money,');
+ expect(claudeDoneSource).toContain(
+ "money: m.money?.kind === 'actual-cost' ? m.money : null,",
+ );
// 订阅轮 (Claude Anthropic 订阅或 bridge 订阅直连) 打 #billing=subscription 标记,
// 仪表盘按订阅估算价折算; 其余轮仍写归一化裸 id。
expect(claudeDoneSource).toContain(
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 ff20d3c0a1..070a1dfc26 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -47,10 +47,28 @@ function legacyCatalog(): Catalog {
const openai = legacy.providers.find((p) => p.id === 'openai');
if (!openai) throw new Error('fixture missing openai');
openai.models.codex = [
- { id: 'gpt-5.5', name: 'GPT-5.5', group: 'gpt', sortOrder: 20, contextWindow: 272000, efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', status: 'active' },
+ {
+ id: 'gpt-5.5',
+ name: 'GPT-5.5',
+ group: 'gpt',
+ sortOrder: 20,
+ contextWindow: 272000,
+ efforts: ['low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'high',
+ status: 'active',
+ },
];
openai.models['claude-code'] = [
- { id: 'chatgpt/gpt-5.5', name: 'GPT-5.5 (ChatGPT 订阅)', group: 'gpt', sortOrder: 25, contextWindow: 123456, efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', status: 'active' },
+ {
+ id: 'chatgpt/gpt-5.5',
+ name: 'GPT-5.5 (ChatGPT 订阅)',
+ group: 'gpt',
+ sortOrder: 25,
+ contextWindow: 123456,
+ efforts: ['low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'high',
+ status: 'active',
+ },
];
return legacy;
}
@@ -71,19 +89,22 @@ describe('active-catalog discovered augment', () => {
it('bridge 投影剔除 max/ultra:codex 侧保留、claude-code 侧封顶 xhigh(issue #352)', () => {
setActiveCatalog(BUNDLED_CATALOG);
- setDiscoveredCodexModels([{
- ...fake('gpt-5.6-sol', 17),
- efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
- defaultEffort: 'ultra',
- }]);
+ setDiscoveredCodexModels([
+ {
+ ...fake('gpt-5.6-sol', 17),
+ efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
+ defaultEffort: 'ultra',
+ },
+ ]);
const openai = getActiveCatalog().providers.find((p) => p.id === 'openai');
const codex = (openai?.models.codex ?? []).find((m) => m.id === 'gpt-5.6-sol');
- const bridge = (openai?.models['claude-code'] ?? []).find((m) => m.id === 'chatgpt/gpt-5.6-sol');
+ const bridge = (openai?.models['claude-code'] ?? []).find(
+ (m) => m.id === 'chatgpt/gpt-5.6-sol',
+ );
// codex 侧完整保留(该模型确实支持 max/ultra)。
expect(codex?.efforts).toEqual(['low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
expect(codex?.defaultEffort).toBe('ultra');
- // claude-code bridge 侧剔除 max/ultra 并把 defaultEffort 封顶到 xhigh
- // (anthropic-responses bridge 对 GPT 模型推理档封顶 xhigh)。
+ // claude-code bridge 侧剔除 max/ultra,默认值随之回落到剩余最高档 xhigh。
expect(bridge?.efforts).toEqual(['low', 'medium', 'high', 'xhigh']);
expect(bridge?.defaultEffort).toBe('xhigh');
});
@@ -93,9 +114,11 @@ describe('active-catalog discovered augment', () => {
setDiscoveredCodexModels([fake('gpt-5.7', 17), fake('gpt-5.5', 20)]);
expect(openaiIds('codex')).toEqual(['gpt-5.7', 'gpt-5.5']);
expect(openaiIds('claude-code')).toEqual(['chatgpt/gpt-5.7', 'chatgpt/gpt-5.5']);
- // 快照的元数据就是权威(没有静态条目掩盖)。
+ // 动态快照决定存在性,且明确返回的运行时能力高于 registry 基线。
const openai = getActiveCatalog().providers.find((p) => p.id === 'openai');
- expect((openai?.models.codex ?? []).find((m) => m.id === 'gpt-5.5')?.contextWindow).toBe(400000);
+ expect((openai?.models.codex ?? []).find((m) => m.id === 'gpt-5.5')?.contextWindow).toBe(
+ 400000,
+ );
});
it('legacy v1 远端目录的静态段被忽略(清单来源唯一化:注册表快照就是全部)', () => {
@@ -105,7 +128,7 @@ describe('active-catalog discovered augment', () => {
expect(ids).toEqual(['gpt-5.5']);
const openai = getActiveCatalog().providers.find((p) => p.id === 'openai');
const m55 = (openai?.models.codex ?? []).find((m) => m.id === 'gpt-5.5');
- // 元数据以注册表快照为准(400000),legacy 静态条目(272000)不复活
+ // 动态快照决定存在性和明确能力;legacy 静态条目不复活。
expect(m55?.contextWindow).toBe(400000);
});
@@ -138,7 +161,7 @@ describe('active-catalog discovered augment', () => {
const cc = openai?.models['claude-code'] ?? [];
expect(cc.find((m) => m.id === 'chatgpt/gpt-5.4')?.defaultEnabled).toBe(false);
expect(cc.find((m) => m.id === 'chatgpt/gpt-5.4-mini')?.defaultEnabled).toBe(false);
- expect(cc.find((m) => m.id === 'chatgpt/gpt-5.5')?.defaultEnabled).toBe(true);
+ expect(cc.find((m) => m.id === 'chatgpt/gpt-5.5')?.defaultEnabled).toBe(false);
});
it('空 discovered + bundled 零静态 → openai 两个 tab 都为空(不用假数据冒充)', () => {
@@ -166,7 +189,17 @@ function anthropicList(agent: AgentKind = 'claude-code'): CatalogModel[] {
return p?.models[agent] ?? [];
}
-describe('anthropic 发现条目的 cindyModelMeta 元数据基线', () => {
+function withAnthropicRegistry(models: NonNullable<Catalog['modelRegistry']>['models']): Catalog {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ catalog.modelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models,
+ };
+ return catalog;
+}
+
+describe('anthropic 发现条目的 modelRegistry 元数据基线', () => {
afterEach(() => {
setActiveCatalog(BUNDLED_CATALOG);
setAnthropicDiscoveredModels([]);
@@ -204,18 +237,22 @@ describe('anthropic 发现条目的 cindyModelMeta 元数据基线', () => {
supportsFastMode: false,
})),
);
- expect(Object.fromEntries([
- 'claude-fable-5',
- 'claude-opus-5',
- 'claude-opus-4-8',
- 'claude-opus-4-7',
- 'claude-opus-4-6',
- 'claude-opus-4-5',
- 'claude-sonnet-5',
- 'claude-sonnet-4-6',
- 'claude-sonnet-4-5',
- 'claude-haiku-4-5',
- ].map((id) => [id, getCindyModelEffortBaseline(id)]))).toEqual({
+ expect(
+ Object.fromEntries(
+ [
+ 'claude-fable-5',
+ 'claude-opus-5',
+ 'claude-opus-4-8',
+ 'claude-opus-4-7',
+ 'claude-opus-4-6',
+ 'claude-opus-4-5',
+ 'claude-sonnet-5',
+ 'claude-sonnet-4-6',
+ 'claude-sonnet-4-5',
+ 'claude-haiku-4-5',
+ ].map((id) => [id, getCindyModelEffortBaseline(id)]),
+ ),
+ ).toEqual({
'claude-fable-5': {
efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
defaultEffort: 'high',
@@ -262,14 +299,25 @@ describe('anthropic 发现条目的 cindyModelMeta 元数据基线', () => {
});
it('active overlay 不覆盖能力;发现模块可单独读取 effort 基线', () => {
- const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- catalog.cindyModelMeta = {
- version: 1,
- models: {
- 'claude-known': { name: 'Known Pro', defaultEnabled: false, contextWindow: 123, efforts: ['max'] },
- },
- };
- setActiveCatalog(catalog);
+ setActiveCatalog(
+ withAnthropicRegistry([
+ {
+ id: 'anthropic/claude-known',
+ name: 'Known Pro',
+ defaultEnabled: false,
+ contextWindow: 123,
+ efforts: ['max'],
+ defaultEffort: 'max',
+ routes: [
+ {
+ providerId: 'anthropic',
+ modelId: 'claude-known',
+ agents: ['claude-code'],
+ },
+ ],
+ },
+ ]),
+ );
setAnthropicDiscoveredModels([
anthro('claude-known', 'known raw', 0),
anthro('claude-unknown', 'Unknown Raw', 1),
@@ -290,63 +338,44 @@ describe('anthropic 发现条目的 cindyModelMeta 元数据基线', () => {
expect(anthropicList().find((m) => m.id === 'claude-unknown')?.name).toBe('Unknown Raw');
});
- it('远端 v1 元数据不完整时按模型、按字段回落 bundled v1', () => {
- const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- catalog.cindyModelMeta = {
- version: 1,
- models: {
- // 模拟旧远端只认识展示名,不带 4.5 的窗口与 effort 能力。
- 'claude-sonnet-4-5': { name: 'Remote Sonnet 4.5' },
- },
- };
- setActiveCatalog(catalog);
+ it('远端 registry 是完整快照,不会与 bundled 按字段暗中合并', () => {
+ setActiveCatalog(
+ withAnthropicRegistry([
+ {
+ id: 'anthropic/claude-sonnet-4-5',
+ name: 'Remote Sonnet 4.5',
+ routes: [
+ {
+ providerId: 'anthropic',
+ modelId: 'claude-sonnet-4-5',
+ agents: ['claude-code'],
+ },
+ ],
+ },
+ ]),
+ );
setAnthropicDiscoveredModels([
anthro('claude-sonnet-4-5', 'Sonnet Raw', 0),
anthro('claude-opus-5', 'Opus Raw', 1),
]);
- expect(anthropicList().find((m) => m.id === 'claude-sonnet-4-5')?.name).toBe('Remote Sonnet 4.5');
- expect(getCindyModelContextWindow('claude-sonnet-4-5')).toBe(200_000);
- expect(getCindyModelEffortBaseline('claude-sonnet-4-5')).toEqual({
- efforts: [],
- defaultEffort: null,
- });
- // 远端完全缺席的 bundled 新模型也必须保留完整能力基线。
- expect(getCindyModelContextWindow('claude-opus-5')).toBe(1_000_000);
- expect(getCindyModelEffortBaseline('claude-opus-5')).toEqual({
- efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
- defaultEffort: 'high',
- });
- });
-
- it('版本门禁:cindyModelMeta.version !== 1 整段忽略;坏信封安全跳过', () => {
- const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- catalog.cindyModelMeta = { version: 2, models: { 'claude-fable-5': { name: 'V2 Name' } } };
- setActiveCatalog(catalog);
- setAnthropicDiscoveredModels([anthro('claude-fable-5', 'Fable', 0)]);
- expect(anthropicList()[0]?.name).toBe('Fable');
- expect(getCindyModelEffortBaseline('claude-fable-5')).toBeNull();
- expect(getCindyModelContextWindow('claude-fable-5')).toBeNull();
-
- catalog.cindyModelMeta = 'not-an-object';
- setActiveCatalog(JSON.parse(JSON.stringify(catalog)) as Catalog);
- setAnthropicDiscoveredModels([anthro('claude-fable-5', 'Fable', 0)]);
- expect(anthropicList()[0]?.name).toBe('Fable');
- expect(getCindyModelEffortBaseline('claude-fable-5')).toBeNull();
- expect(getCindyModelContextWindow('claude-fable-5')).toBeNull();
+ expect(anthropicList().find((m) => m.id === 'claude-sonnet-4-5')?.name).toBe(
+ 'Remote Sonnet 4.5',
+ );
+ expect(getCindyModelContextWindow('claude-sonnet-4-5')).toBeNull();
+ expect(getCindyModelEffortBaseline('claude-sonnet-4-5')).toBeNull();
+ expect(getCindyModelContextWindow('claude-opus-5')).toBeNull();
+ expect(getCindyModelEffortBaseline('claude-opus-5')).toBeNull();
});
- it('active 目录未携带 cindyModelMeta 时回落 bundled v1 基线', () => {
+ it('active 目录未携带 registry 时不存在旁路元数据回落', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- delete catalog.cindyModelMeta;
+ delete catalog.modelRegistry;
setActiveCatalog(catalog);
setAnthropicDiscoveredModels([anthro('claude-fable-5', 'Fable Raw', 0)]);
- expect(anthropicList()[0]?.name).toBe('Fable 5');
- expect(getCindyModelContextWindow('claude-fable-5')).toBe(1_000_000);
- expect(getCindyModelEffortBaseline('claude-fable-5')).toEqual({
- efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
- defaultEffort: 'high',
- });
+ expect(anthropicList()[0]?.name).toBe('Fable Raw');
+ expect(getCindyModelContextWindow('claude-fable-5')).toBeNull();
+ expect(getCindyModelEffortBaseline('claude-fable-5')).toBeNull();
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
index 51ffaffc56..dc726b25df 100644
--- a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
@@ -149,13 +149,36 @@ describe('mapAnthropicSdkModels', () => {
]);
});
- it('active v1 元数据缺字段时仍从 bundled v1 取得窗口和 effort', () => {
+ it('active registry 快照提供窗口和 effort 基线', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- catalog.cindyModelMeta = {
- version: 1,
- models: {
- 'claude-sonnet-4-5': { name: 'Remote Sonnet 4.5' },
- },
+ catalog.modelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models: [
+ {
+ id: 'anthropic/claude-sonnet-4-5',
+ name: 'Remote Sonnet 4.5',
+ contextWindow: 200_000,
+ efforts: [],
+ routes: [{
+ providerId: 'anthropic',
+ modelId: 'claude-sonnet-4-5',
+ agents: ['claude-code'],
+ }],
+ },
+ {
+ id: 'anthropic/claude-opus-5',
+ name: 'Opus 5',
+ contextWindow: 1_000_000,
+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ defaultEffort: 'high',
+ routes: [{
+ providerId: 'anthropic',
+ modelId: 'claude-opus-5',
+ agents: ['claude-code'],
+ }],
+ },
+ ],
};
setActiveCatalog(catalog);
@@ -232,7 +255,7 @@ describe('mapAnthropicSdkModels', () => {
]);
expect(out.map((e) => e.model.id)).toEqual(['claude-fable-5', 'claude-opus-4-8']);
expect(out[0].model.name).toBe('Fable 5'); // first-wins
- // 归一化前 [1m] id 查不到 cindyModelMeta 基线,会塌回合成三档;归一化后按裸 id 命中。
+ // 归一化前 [1m] id 查不到 registry 基线,会塌回合成三档;归一化后按裸 id 命中。
expect(out[0].model.efforts).toContain('xhigh');
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
index 261f294cbd..db306d456f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
@@ -63,10 +63,14 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {
const cc = deriveAvailableModels(BUNDLED_CATALOG, 'claude-code');
const codex = deriveAvailableModels(BUNDLED_CATALOG, 'codex');
expect(cc.map((m) => m.id)).toEqual([
- 'xai/grok-4.5', 'xai/grok-4.3', 'xai/grok-4.20', 'xai/grok-code-fast',
+ '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',
]);
expect(codex.map((m) => m.id)).toEqual([
- 'xai/grok-4.5', 'xai/grok-4.3', 'xai/grok-4.20', 'xai/grok-code-fast',
+ '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',
]);
});
@@ -106,7 +110,9 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {
expect(ids).toEqual([
'claude-opus-4-8',
'chatgpt/gpt-5.5',
- 'xai/grok-4.5', 'xai/grok-4.3', 'xai/grok-4.20', 'xai/grok-code-fast',
+ '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',
'gpt-5.5',
]);
// 首见胜出:opus 取 anthropic 条目(supportsFastMode=true),不是 xd 的 false。
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 ec729a607e..cb0413d931 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
@@ -1,4 +1,7 @@
+import { randomUUID } from 'node:crypto';
+import { promises as fsp } from 'node:fs';
import os from 'node:os';
+import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
@@ -9,10 +12,15 @@ const h = vi.hoisted(() => ({
source: Record<string, unknown>;
resolve: (catalog: unknown) => void;
}>,
+ refreshLoads: [] as Array<{
+ source: Record<string, unknown>;
+ resolve: (result: unknown) => void;
+ }>,
}));
vi.mock('electron', () => ({
app: { getPath: () => os.tmpdir() },
+ BrowserWindow: { getAllWindows: () => [] },
net: { request: vi.fn() },
}));
@@ -26,6 +34,12 @@ vi.mock('@cindy/model-providers', async (importOriginal) => {
h.loads.push({ source, resolve });
}),
),
+ loadCatalogWithSource: vi.fn(
+ (source: Record<string, unknown>) =>
+ new Promise((resolve) => {
+ h.refreshLoads.push({ source, resolve });
+ }),
+ ),
};
});
@@ -42,6 +56,7 @@ vi.mock('../../authManager.js', () => ({
}));
vi.mock('../../appSessionState.js', () => ({
getActiveAppSession: () => ({ mode: 'signed-out', dataOwnerId: null }),
+ ownerScopedUserDataPath: (...segments: string[]) => path.join(os.tmpdir(), ...segments),
}));
vi.mock('../../appCapabilities.js', () => ({
getAppCapabilities: () => ({ canUseCindyGateway: false }),
@@ -102,13 +117,19 @@ vi.mock('../model-discovery/anthropic.js', () => ({
import { BUNDLED_CATALOG, type Catalog } from '@cindy/model-providers';
import { getActiveCatalog } from '../active-catalog.js';
import {
+ __testing,
ensureActiveCatalogLoaded,
+ refreshActiveCatalogFromSource,
reloadActiveCatalogForEndpointChange,
+ shouldDisableCatalogFetch,
} from '../createDesktopProviderService.js';
-function catalogNamed(name: string): Catalog {
+function catalogNamed(name: string, updatedAt?: string): Catalog {
return {
...BUNDLED_CATALOG,
+ ...(updatedAt && BUNDLED_CATALOG.modelRegistry
+ ? { modelRegistry: { ...BUNDLED_CATALOG.modelRegistry, updatedAt } }
+ : {}),
providers: BUNDLED_CATALOG.providers.map((provider, index) =>
index === 0 ? { ...provider, name } : provider,
),
@@ -120,6 +141,136 @@ function activeMarker(): string | undefined {
}
describe('provider catalog realm reload', () => {
+ it('persists only a digest of a catalog scope that may contain URL credentials', () => {
+ const scope = 'https://catalog.example/models?access_token=do-not-persist';
+ const envelope = __testing.catalogLkgEnvelope(scope, '{"schemaVersion":1}');
+
+ expect(envelope).toMatchObject({
+ version: 2,
+ scopeHash: expect.stringMatching(/^[a-f0-9]{64}$/),
+ catalog: '{"schemaVersion":1}',
+ });
+ expect(JSON.stringify(envelope)).not.toContain(scope);
+ expect(JSON.stringify(envelope)).not.toContain('do-not-persist');
+ });
+
+ it('uses a unique temporary path for every LKG write', () => {
+ const first = __testing.catalogLkgTemporaryPath('/catalog.json');
+ const second = __testing.catalogLkgTemporaryPath('/catalog.json');
+
+ expect(first).not.toBe(second);
+ expect(first).toMatch(/\/catalog\.json\.\d+\.[0-9a-f-]+\.tmp$/);
+ expect(second).toMatch(/\/catalog\.json\.\d+\.[0-9a-f-]+\.tmp$/);
+ });
+
+ it('serializes the complete LKG replacement transaction for the same scope', async () => {
+ const events: string[] = [];
+ let finishFirst!: () => void;
+ const firstGate = new Promise<void>((resolve) => {
+ finishFirst = resolve;
+ });
+ const first = __testing.serializeCatalogLkgWrite('/same-catalog.json', async () => {
+ events.push('first:start');
+ await firstGate;
+ events.push('first:end');
+ });
+ await vi.waitFor(() => expect(events).toEqual(['first:start']));
+
+ const second = __testing.serializeCatalogLkgWrite('/same-catalog.json', async () => {
+ events.push('second:start');
+ events.push('second:end');
+ });
+ await Promise.resolve();
+ expect(events).toEqual(['first:start']);
+
+ finishFirst();
+ await Promise.all([first, second]);
+ expect(events).toEqual(['first:start', 'first:end', 'second:start', 'second:end']);
+ });
+
+ it('keeps a newer LKG when an older response queues behind it for the same scope', async () => {
+ const scope = `https://catalog.example.test/${randomUUID()}`;
+ const file = __testing.catalogLkgPath(scope);
+ const older = JSON.stringify(catalogNamed('OLDER', '2026-07-30T00:00:00.000Z'));
+ const newer = JSON.stringify(catalogNamed('NEWER', '2026-08-01T00:00:00.000Z'));
+
+ try {
+ await __testing.writeCatalogLkg(scope, older);
+ const newerCommit = __testing.writeCatalogLkg(scope, newer);
+ const staleCommit = __testing.writeCatalogLkg(scope, older);
+
+ await expect(newerCommit).resolves.toBe(newer);
+ await expect(staleCommit).resolves.toBe(newer);
+ await expect(__testing.readCatalogLkg(scope)).resolves.toBe(newer);
+ } finally {
+ await fsp.rm(file, { force: true });
+ await fsp.rm(`${file}.bak`, { force: true });
+ }
+ });
+
+ it('replaces an existing LKG through a Windows-safe backup path', async () => {
+ const files = new Set(['/catalog.json', '/catalog.tmp']);
+ const calls: Array<[string, string]> = [];
+ let firstReplace = true;
+ const fileIo = {
+ async rename(from: string, to: string) {
+ calls.push([from, to]);
+ if (firstReplace && from === '/catalog.tmp' && to === '/catalog.json') {
+ firstReplace = false;
+ throw Object.assign(new Error('destination exists'), { code: 'EEXIST' });
+ }
+ if (!files.has(from)) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ files.delete(from);
+ files.add(to);
+ },
+ async rm(target: string) {
+ files.delete(target);
+ },
+ };
+
+ await __testing.replaceCatalogLkgFile('/catalog.tmp', '/catalog.json', fileIo);
+
+ expect(calls).toEqual([
+ ['/catalog.tmp', '/catalog.json'],
+ ['/catalog.json', '/catalog.json.bak'],
+ ['/catalog.tmp', '/catalog.json'],
+ ]);
+ expect(files).toEqual(new Set(['/catalog.json']));
+ });
+
+ it('restores the previous LKG if the replacement still fails', async () => {
+ const files = new Set(['/catalog.json', '/catalog.tmp']);
+ let temporaryAttempts = 0;
+ const fileIo = {
+ async rename(from: string, to: string) {
+ if (from === '/catalog.tmp') {
+ temporaryAttempts += 1;
+ throw Object.assign(new Error('locked'), { code: temporaryAttempts === 1 ? 'EPERM' : 'EBUSY' });
+ }
+ if (!files.has(from)) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ files.delete(from);
+ files.add(to);
+ },
+ async rm(target: string) {
+ files.delete(target);
+ },
+ };
+
+ await expect(
+ __testing.replaceCatalogLkgFile('/catalog.tmp', '/catalog.json', fileIo),
+ ).rejects.toMatchObject({ code: 'EBUSY' });
+ expect(files.has('/catalog.json')).toBe(true);
+ expect(files.has('/catalog.json.bak')).toBe(false);
+ });
+
+ it('keeps dev offline by default but permits an explicit catalog URL', () => {
+ expect(shouldDisableCatalogFetch(true, undefined, false)).toBe(true);
+ expect(shouldDisableCatalogFetch(true, ' ', false)).toBe(true);
+ expect(shouldDisableCatalogFetch(true, 'http://127.0.0.1/catalog', false)).toBe(false);
+ expect(shouldDisableCatalogFetch(false, undefined, false)).toBe(false);
+ expect(shouldDisableCatalogFetch(false, 'http://127.0.0.1/catalog', true)).toBe(true);
+ });
+
it('invalidates the old realm immediately and ignores a stale cross-realm response', async () => {
const initial = ensureActiveCatalogLoaded();
expect(h.loads[0]?.source).toMatchObject({
@@ -150,4 +301,71 @@ describe('provider catalog realm reload', () => {
await cnReload;
expect(activeMarker()).toBe('catalog-cn-latest');
});
+
+ it('ignores an automatic refresh response from a superseded realm', async () => {
+ const staleRefresh = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ expect(h.refreshLoads[0]?.source).toMatchObject({
+ baseUrl: 'https://model.cn.example',
+ });
+
+ h.endpoint = 'https://model.global.example';
+ const globalReloadIndex = h.loads.length;
+ const globalReload = reloadActiveCatalogForEndpointChange();
+ h.loads[globalReloadIndex]!.resolve(
+ catalogNamed('catalog-global-current', '2026-07-31T12:00:00.000Z'),
+ );
+ await globalReload;
+
+ const currentRefresh = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ expect(h.refreshLoads[1]?.source).toMatchObject({
+ baseUrl: 'https://model.global.example',
+ });
+ h.refreshLoads[1]!.resolve({
+ catalog: catalogNamed('catalog-global-refreshed', '2026-07-31T12:30:00.000Z'),
+ source: 'remote',
+ });
+ await currentRefresh;
+
+ h.refreshLoads[0]!.resolve({
+ catalog: catalogNamed('catalog-cn-stale', '2026-07-31T13:00:00.000Z'),
+ source: 'remote',
+ });
+ await staleRefresh;
+
+ expect(activeMarker()).toBe('catalog-global-current');
+ expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-07-31T12:30:00.000Z');
+ });
+
+ it('does not downgrade the active catalog when refresh falls back to an older cache', async () => {
+ const activeXaiModels = getActiveCatalog().providers
+ .find((provider) => provider.id === 'xai')
+ ?.models.codex;
+ const staleCatalog = structuredClone(
+ catalogNamed('catalog-global-cached', '2026-07-31T11:00:00.000Z'),
+ );
+ const staleXai = staleCatalog.providers.find((provider) => provider.id === 'xai');
+ if (!staleXai) throw new Error('expected bundled xai provider');
+ staleXai.models.codex = [{
+ id: 'xai/stale-cache-only',
+ name: 'Stale cache only',
+ contextWindow: 1,
+ efforts: [],
+ defaultEffort: null,
+ }];
+ const refresh = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ const load = h.refreshLoads.at(-1)!;
+ load.resolve({
+ catalog: staleCatalog,
+ source: 'cache',
+ });
+ await refresh;
+
+ expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-07-31T12:30:00.000Z');
+ expect(
+ getActiveCatalog().providers.find((provider) => provider.id === 'xai')?.models.codex,
+ ).toEqual(activeXaiModels);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
index 45e4994207..979cdd945a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
@@ -34,6 +34,61 @@ function deferred(): {
}
describe('provider model auto-refresh coordinator', () => {
+ it('refreshes the shared Catalog after cooldown even when xAI is disconnected', async () => {
+ let now = 1_000;
+ const refreshCatalog = vi.fn(async () => undefined);
+ const coordinator = createProviderModelRefreshCoordinator({
+ listProviders: async () => [
+ view('openai', true),
+ view('xai', false),
+ ],
+ refreshProvider: vi.fn(async () => undefined),
+ refreshCatalog,
+ now: () => now,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+
+ // Splash 已取过公共 Catalog;startup 不重复请求,并给失败恢复留 5 分钟宽限。
+ await coordinator.requestAutoRefresh('startup');
+ expect(refreshCatalog).not.toHaveBeenCalled();
+ await coordinator.requestAutoRefresh('providers-open');
+ expect(refreshCatalog).not.toHaveBeenCalled();
+
+ now += PROVIDER_MODEL_AUTO_REFRESH_FAILURE_COOLDOWN_MS;
+ await coordinator.requestAutoRefresh('model-selector-open');
+ expect(refreshCatalog).toHaveBeenCalledOnce();
+ await coordinator.requestAutoRefresh('foreground');
+ expect(refreshCatalog).toHaveBeenCalledOnce();
+ });
+
+ it('does not repeat the shared Catalog refresh through the connected xAI provider hook', async () => {
+ let now = 1_000;
+ const refreshCatalog = vi.fn(async () => undefined);
+ const refreshProvider = vi.fn(async () => undefined);
+ const coordinator = createProviderModelRefreshCoordinator({
+ listProviders: async () => [view('xai', true)],
+ refreshProvider,
+ refreshCatalog,
+ now: () => now,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+
+ // Splash already loaded the public Catalog; startup must not immediately fetch it again via
+ // xAI's provider-level hook.
+ await coordinator.requestAutoRefresh('startup');
+ expect(refreshCatalog).not.toHaveBeenCalled();
+ expect(refreshProvider).not.toHaveBeenCalled();
+
+ now += PROVIDER_MODEL_AUTO_REFRESH_FAILURE_COOLDOWN_MS;
+ await coordinator.requestAutoRefresh('foreground');
+ expect(refreshCatalog).toHaveBeenCalledOnce();
+ expect(refreshProvider).not.toHaveBeenCalled();
+
+ // An explicit manual refresh remains available and executes the provider hook once.
+ await coordinator.refreshManually('xai');
+ expect(refreshProvider).toHaveBeenCalledOnce();
+ });
+
it('refreshes only connected built-ins and applies a per-provider cooldown', async () => {
let now = 1_000;
const refreshProvider =
@@ -70,6 +125,27 @@ describe('provider model auto-refresh coordinator', () => {
]);
});
+ it('applies the shared Catalog before provider discovery derives model capabilities', async () => {
+ const catalog = deferred();
+ const refreshProvider = vi.fn(async () => undefined);
+ const refreshCatalog = vi.fn(() => catalog.promise);
+ const coordinator = createProviderModelRefreshCoordinator({
+ listProviders: async () => [view('anthropic', true)],
+ refreshProvider,
+ refreshCatalog,
+ now: () => 1_000,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+
+ const refresh = coordinator.requestAutoRefresh('providers-open');
+ await vi.waitFor(() => expect(refreshCatalog).toHaveBeenCalledOnce());
+ expect(refreshProvider).not.toHaveBeenCalled();
+
+ catalog.resolve();
+ await refresh;
+ expect(refreshProvider).toHaveBeenCalledOnce();
+ });
+
it('honors an explicit provider filter without waiting on unrelated sources', async () => {
const refreshProvider = vi.fn(async (_providerId: BuiltinRefreshableProviderId) => {});
const coordinator = createProviderModelRefreshCoordinator({
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 8e04a5f845..cca69a9e01 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -25,6 +25,7 @@
import {
BUNDLED_CATALOG,
+ findModelRegistryRoute,
type AgentKind,
type Catalog,
type CatalogModel,
@@ -145,9 +146,7 @@ function xdGatewayTargetAgents(model: XdGatewayModelInfo): AgentKind[] {
return model.agents && model.agents.length > 0 ? model.agents : ['claude-code'];
}
-function deriveXdCodexAnthropicBridgeModelIds(
- models: XdGatewayModelInfo[],
-): Set<string> {
+function deriveXdCodexAnthropicBridgeModelIds(models: XdGatewayModelInfo[]): Set<string> {
const support = new Map<string, { claudeCode: boolean; codex: boolean }>();
for (const model of models) {
const current = support.get(model.id) ?? { claudeCode: false, codex: false };
@@ -207,8 +206,8 @@ function effectiveGatewayModelCost(model: XdGatewayModelInfo): CatalogModel['cos
/** base + custom + discovered augment 的合并缓存;null = 待重算(惰性)。 */
let merged: Catalog | null = null;
-/** bundled + active v1 `cindyModelMeta` 的合并索引;目录变化时与 merged 一起失效。 */
-let effectiveCindyModelMetaIndex: Map<string, CindyModelMetaFields> | null = null;
+/** 当前 registry 的 Anthropic 路由元数据索引;目录变化时与 merged 一起失效。 */
+let effectiveRegistryMetaIndex: Map<string, RegistryMetaFields> | null = null;
/**
* 目录修订号。所有会改变 getActiveCatalog() 结果的写入都必须经过 markChanged,
@@ -221,7 +220,7 @@ let changedListener: ((nextRevision: number) => void) | null = null;
function markChanged(): void {
merged = null;
- effectiveCindyModelMetaIndex = null;
+ effectiveRegistryMetaIndex = null;
revision += 1;
changedListener?.(revision);
}
@@ -312,100 +311,86 @@ function projectCodexModelsToClaude(p: Provider): Provider {
const DYNAMIC_LIST_PROVIDER_IDS: ReadonlySet<string> = new Set(['anthropic', 'openai', 'xd']);
/**
- * cindyModelMeta 里客户端认识的字段子集。展示字段直接覆盖发现条目;context / effort
+ * modelRegistry 里客户端认识的字段子集。展示字段直接覆盖发现条目;context / effort
* 字段只在 Anthropic 动态通道**没有能力信息**时作为基线,由
* model-discovery/anthropic 消费。上游显式能力始终优先,meta 不在 active catalog
* overlay 阶段改写能力。
*/
-interface CindyModelMetaFields {
+interface RegistryMetaFields {
name?: string;
group?: string;
description?: string;
sortOrder?: number;
defaultEnabled?: boolean;
contextWindow?: number;
+ maxOutput?: number;
efforts?: Effort[];
defaultEffort?: Effort | null;
+ supportsFastMode?: boolean;
+ status?: CatalogModel['status'];
}
-/**
- * 解析目录顶层 `cindyModelMeta`(`{ version: 1, models: { id: {...} } }` 信封)为
- * 展示字段索引。schema 归服务端所有,客户端只读认识的字段、逐字段校验类型;
- * **版本门禁**:version !== 1 整段忽略(未来服务端升 schema 时老客户端安全降级,
- * 不按旧语义误读新数据)。坏信封 / 坏条目静默跳过,绝不让元数据把清单弄坏。
- */
-function buildCindyModelMetaIndex(meta: unknown): Map<string, CindyModelMetaFields> {
- const index = new Map<string, CindyModelMetaFields>();
- if (!meta || typeof meta !== 'object' || Array.isArray(meta)) return index;
- const envelope = meta as { version?: unknown; models?: unknown };
- if (envelope.version !== 1) return index;
- const models = envelope.models;
- if (!models || typeof models !== 'object' || Array.isArray(models)) return index;
- for (const [id, entry] of Object.entries(models as Record<string, unknown>)) {
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
- const e = entry as Record<string, unknown>;
- const fields: CindyModelMetaFields = {};
- if (typeof e.name === 'string' && e.name.length > 0) fields.name = e.name;
- if (typeof e.group === 'string' && e.group.length > 0) fields.group = e.group;
- if (typeof e.description === 'string' && e.description.length > 0)
- fields.description = e.description;
- if (typeof e.sortOrder === 'number' && Number.isFinite(e.sortOrder))
- fields.sortOrder = e.sortOrder;
- if (typeof e.defaultEnabled === 'boolean') fields.defaultEnabled = e.defaultEnabled;
- if (
- typeof e.contextWindow === 'number' &&
- Number.isFinite(e.contextWindow) &&
- e.contextWindow > 0
- ) {
- fields.contextWindow = e.contextWindow;
- }
- if (Array.isArray(e.efforts)) {
- const efforts = e.efforts.filter(
- (value): value is Effort => typeof value === 'string' && VALID_EFFORTS.has(value),
- );
- if (efforts.length === e.efforts.length) fields.efforts = efforts;
- }
- if (e.defaultEffort === null) fields.defaultEffort = null;
- else if (typeof e.defaultEffort === 'string' && VALID_EFFORTS.has(e.defaultEffort)) {
- fields.defaultEffort = e.defaultEffort as Effort;
- }
- if (Object.keys(fields).length > 0) index.set(id, fields);
- }
- return index;
+function modelRegistryMetaFields(
+ providerId: string,
+ agent: AgentKind,
+ modelId: string,
+): RegistryMetaFields | undefined {
+ const catalog = base ?? BUNDLED_CATALOG;
+ const matched = findModelRegistryRoute(catalog.modelRegistry, providerId, modelId, agent);
+ if (!matched) return undefined;
+ const { entry } = matched;
+ const perAgent = entry.perAgent?.[agent];
+ const efforts = perAgent?.efforts ?? entry.efforts;
+ const defaultEffort = perAgent?.defaultEffort ?? entry.defaultEffort;
+ return {
+ name: entry.name,
+ ...(entry.group !== undefined ? { group: entry.group } : {}),
+ ...(entry.description !== undefined ? { description: entry.description } : {}),
+ ...(entry.sortOrder !== undefined ? { sortOrder: entry.sortOrder } : {}),
+ ...(perAgent?.defaultEnabled !== undefined || entry.defaultEnabled !== undefined
+ ? { defaultEnabled: perAgent?.defaultEnabled ?? entry.defaultEnabled }
+ : {}),
+ ...(perAgent?.contextWindow !== undefined || entry.contextWindow !== undefined
+ ? { contextWindow: perAgent?.contextWindow ?? entry.contextWindow }
+ : {}),
+ ...(entry.maxOutputTokens !== undefined ? { maxOutput: entry.maxOutputTokens } : {}),
+ ...(efforts !== undefined ? { efforts: efforts as Effort[] } : {}),
+ ...(defaultEffort !== undefined
+ ? { defaultEffort: defaultEffort as Effort }
+ : efforts?.length === 0
+ ? { defaultEffort: null }
+ : {}),
+ ...(perAgent?.supportsFastMode !== undefined || entry.supportsFastMode !== undefined
+ ? { supportsFastMode: perAgent?.supportsFastMode ?? entry.supportsFastMode }
+ : {}),
+ ...(entry.status !== undefined
+ ? {
+ status:
+ entry.status === 'preview'
+ ? 'alpha'
+ : entry.status === 'deprecated' || entry.status === 'retired'
+ ? 'deprecated'
+ : 'active',
+ }
+ : {}),
+ };
}
-/**
- * 远端 v1 元数据允许按模型、按字段增量覆盖 bundled v1。旧远端目录经常只带
- * 部分新字段或缺少新模型;缺口必须回落 bundled,否则已知 200k 模型会落入
- * 1M 启发式。非 v1 active 信封仍整段忽略,不能拿 bundled v1 混入未知 schema。
- */
-function buildEffectiveCindyModelMetaIndex(): Map<string, CindyModelMetaFields> {
- if (effectiveCindyModelMetaIndex) return effectiveCindyModelMetaIndex;
-
- const bundled = buildCindyModelMetaIndex(BUNDLED_CATALOG.cindyModelMeta);
- if (!base || base.cindyModelMeta === undefined) {
- effectiveCindyModelMetaIndex = bundled;
- return effectiveCindyModelMetaIndex;
- }
+/** Registry 是动态发现缺少能力信息时唯一的产品元数据基线。 */
+function buildEffectiveRegistryMetaIndex(): Map<string, RegistryMetaFields> {
+ if (effectiveRegistryMetaIndex) return effectiveRegistryMetaIndex;
- const activeMeta = base.cindyModelMeta;
- if (
- !activeMeta ||
- typeof activeMeta !== 'object' ||
- Array.isArray(activeMeta) ||
- (activeMeta as { version?: unknown }).version !== 1
- ) {
- effectiveCindyModelMetaIndex = new Map();
- return effectiveCindyModelMetaIndex;
- }
-
- const effective = new Map<string, CindyModelMetaFields>();
- for (const [id, fields] of bundled) effective.set(id, { ...fields });
- for (const [id, fields] of buildCindyModelMetaIndex(activeMeta)) {
- effective.set(id, { ...effective.get(id), ...fields });
+ const effective = new Map<string, RegistryMetaFields>();
+ const registry = (base ?? BUNDLED_CATALOG).modelRegistry;
+ for (const entry of registry?.models ?? []) {
+ for (const route of entry.routes) {
+ if (route.providerId !== 'anthropic' || !route.agents.includes('claude-code')) continue;
+ const fields = modelRegistryMetaFields('anthropic', 'claude-code', route.modelId);
+ if (fields) effective.set(route.modelId, fields);
+ }
}
- effectiveCindyModelMetaIndex = effective;
- return effectiveCindyModelMetaIndex;
+ effectiveRegistryMetaIndex = effective;
+ return effectiveRegistryMetaIndex;
}
export interface CindyModelEffortBaseline {
@@ -415,7 +400,7 @@ export interface CindyModelEffortBaseline {
/** 返回当前目录的已知上下文窗口;只供动态发现缺少上游明确值时兜底。 */
export function getCindyModelContextWindow(modelId: string): number | null {
- return buildEffectiveCindyModelMetaIndex().get(modelId)?.contextWindow ?? null;
+ return buildEffectiveRegistryMetaIndex().get(modelId)?.contextWindow ?? null;
}
/**
@@ -423,7 +408,7 @@ export function getCindyModelContextWindow(modelId: string): number | null {
* 模型是否存在仍完全由 HTTP / SDK 动态清单决定。
*/
export function getCindyModelEffortBaseline(modelId: string): CindyModelEffortBaseline | null {
- const fields = buildEffectiveCindyModelMetaIndex().get(modelId);
+ const fields = buildEffectiveRegistryMetaIndex().get(modelId);
if (!fields?.efforts) return null;
const efforts = [...fields.efforts];
const defaultEffort =
@@ -441,9 +426,9 @@ export function getCindyModelEffortBaseline(modelId: string): CindyModelEffortBa
* 典型修正:订阅 `/v1/models` / SDK 捕获给的家族级名字("Fable")→ 产品命名
* ("Fable 5");上游无排序 → 产品排序。
*/
-function overlayCindyMeta(
+function overlayRegistryMeta(
model: CatalogModel,
- fields: CindyModelMetaFields | undefined,
+ fields: RegistryMetaFields | undefined,
): CatalogModel {
if (!fields) return model;
return {
@@ -456,6 +441,39 @@ function overlayCindyMeta(
};
}
+function overlayModelRegistry(
+ providerId: string,
+ agent: AgentKind,
+ models: CatalogModel[],
+): CatalogModel[] {
+ return sortModelsByOrder(
+ models.map((model) => {
+ const fields = modelRegistryMetaFields(providerId, agent, model.id);
+ const overlaid = overlayRegistryMeta(model, fields);
+ if (!fields) return overlaid;
+ if (DYNAMIC_LIST_PROVIDER_IDS.has(providerId)) {
+ return {
+ ...overlaid,
+ ...(fields.status !== undefined ? { status: fields.status } : {}),
+ };
+ }
+ return {
+ ...overlaid,
+ ...(fields.contextWindow !== undefined
+ ? { contextWindow: fields.contextWindow, contextWindowVerified: true }
+ : {}),
+ ...(fields.maxOutput !== undefined ? { maxOutput: fields.maxOutput } : {}),
+ ...(fields.efforts !== undefined ? { efforts: fields.efforts } : {}),
+ ...(fields.defaultEffort !== undefined ? { defaultEffort: fields.defaultEffort } : {}),
+ ...(fields.supportsFastMode !== undefined
+ ? { supportsFastMode: fields.supportsFastMode }
+ : {}),
+ ...(fields.status !== undefined ? { status: fields.status } : {}),
+ };
+ }),
+ );
+}
+
/** 按 sortOrder 稳定排序(无 sortOrder 排最后,按进入序)——与 augmentModels 同口径。 */
function sortModelsByOrder(models: CatalogModel[]): CatalogModel[] {
return models
@@ -519,13 +537,13 @@ function computeMerged(): Catalog {
// Anthropic 权威模型清单重建(2026-07-19 统一重构):清单唯一来源是 SDK / 登录时
// HTTP 发现(host 经 setAnthropicDiscoveredModels 注入),目录静态段已退役(bundled
// 恒为空数组)。空 = 未发现,anthropic 供应商保留但不暴露任何模型,不用静态数据冒充。
- // 展示元数据(名字/分组/排序/默认可见)以目录 cindyModelMeta 为基线覆盖(2026-07-21
+ // 展示元数据(名字/分组/排序/默认可见)以目录 modelRegistry 为基线覆盖(2026-07-21
// 三层合并:存在性=发现,展示=产品目录,用户 override 永远最高)——订阅通道返回的
// 家族级名字("Fable")在此归位为产品命名("Fable 5");能力字段仍以发现为准。
if (anthropicModels.length > 0) {
- const metaIndex = buildEffectiveCindyModelMetaIndex();
+ const metaIndex = buildEffectiveRegistryMetaIndex();
const overlaid = sortModelsByOrder(
- anthropicModels.map((m) => overlayCindyMeta(m, metaIndex.get(m.id))),
+ anthropicModels.map((m) => overlayRegistryMeta(m, metaIndex.get(m.id))),
);
const codexBridgeModels = overlaid.map((model) => ({
...model,
@@ -545,9 +563,24 @@ function computeMerged(): Catalog {
);
}
+ providers = providers.map((provider) => {
+ if (provider.id === 'xd') return provider;
+ let changed = false;
+ const models: Provider['models'] = { ...provider.models };
+ for (const [agent, entries] of Object.entries(provider.models) as [
+ AgentKind,
+ CatalogModel[],
+ ][]) {
+ const overlaid = overlayModelRegistry(provider.id, agent, entries);
+ if (overlaid.some((model, index) => model !== entries[index])) changed = true;
+ models[agent] = overlaid;
+ }
+ return changed ? { ...provider, models } : provider;
+ });
+
// XD 网关权威模型清单重建。即使实时清单为空也必须重建为空:不能证明某个模型
// 当前在网关可用就不显示。元数据**只信服务端下发 + 确定性默认值**(2026-07-19 起
- // 不再回落产品目录条目——服务端 MODEL_METADATA 已是唯一权威):
+ // 不再回落产品目录静态模型条目——服务端 modelRegistry 已是唯一策展元数据权威):
// - perAgent 覆盖块按 tab 应用在基线字段之上;
// - efforts 字段缺失 = 未登记 → 合成 3 档(low/medium/high,默认 high);
// 显式 [] = 登记为不可调 → 尊重为空;
@@ -578,15 +611,13 @@ function computeMerged(): Catalog {
const defaultEffort: Effort | null =
rawDefault === null
? null
- : rawDefault &&
- VALID_EFFORTS.has(rawDefault) &&
- efforts.includes(rawDefault as Effort)
- ? (rawDefault as Effort)
- : efforts.includes('high')
- ? 'high'
- : efforts.length > 0
- ? efforts[efforts.length - 1]
- : null;
+ : rawDefault && VALID_EFFORTS.has(rawDefault) && efforts.includes(rawDefault as Effort)
+ ? (rawDefault as Effort)
+ : efforts.includes('high')
+ ? 'high'
+ : efforts.length > 0
+ ? efforts[efforts.length - 1]
+ : null;
const defaultEnabled = ov.defaultEnabled ?? gm.defaultEnabled;
const cost = effectiveGatewayModelCost(gm);
const merged: CatalogModel = {
@@ -667,10 +698,7 @@ export function getCatalogModelContextWindow(
modelId: string,
stripPrefix?: string,
): number | null {
- const candidates = new Set<string>([
- modelId,
- modelId.replace(/\[1m\]$/, ''),
- ]);
+ const candidates = new Set<string>([modelId, modelId.replace(/\[1m\]$/, '')]);
if (stripPrefix && modelId.startsWith(stripPrefix)) {
const stripped = modelId.slice(stripPrefix.length);
candidates.add(stripped);
@@ -710,6 +738,13 @@ export function setProviderModelsFromCatalog(providerId: string, catalog: Catalo
markChanged();
}
+export function setModelRegistryFromCatalog(catalog: Catalog): void {
+ if (!catalog.modelRegistry) return;
+ const current = base ?? BUNDLED_CATALOG;
+ base = { ...current, modelRegistry: catalog.modelRegistry };
+ markChanged();
+}
+
/**
* 注入 / 刷新用户自定义供应商(CRUD 后、或换账号 DB 重开后调用)。
* 传入的是已 `buildUserProvider` 展开的标准 `Provider[]`(**不含 API key**)。
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index eb4ee907be..fac0913378 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -7,7 +7,8 @@
* - release:优先从区域化 Model Access 公共接口加载,失败时回退旧 OSS 目录。
* - dev:关闭联网(与 manifestService 一致),可由 XDT_MODELS_PATH 指向本地文件即时生效。
* - env 兜底:XDT_MODELS_URL(完整覆盖 URL)/ XDT_DISABLE_MODELS_FETCH(强制不联网)。
- * **每进程拉一次、存内存、无 TTL、无磁盘缓存**:远端目录是运行时真源,bundled 是最终兜底。
+ * **每进程拉一次、存内存、无 TTL**:启动总是先拉远端;失败时才读按端点隔离的
+ * last-known-good 快照,最后回退 bundled。
* 启动期(splash)由 bootstrap-electron 在构造 Maker 前 await 一次(见 registerMakerIpcsAfterSplash)。
* 2. `getDesktopProviderService`:把 active-catalog + 连接状态读取器注入 provider-service。
* 连接状态直接复用现有凭证存储——XD = 托管 gateway key 是否存在、
@@ -16,6 +17,7 @@
*/
import { app, net } from 'electron';
+import { createHash, randomUUID } from 'node:crypto';
import { promises as fsp } from 'node:fs';
import path from 'node:path';
@@ -25,6 +27,7 @@ import {
DEFAULT_REMOTE_CATALOG_BUDGET_MS,
loadCatalog,
loadCatalogWithSource,
+ parseCatalog,
type Catalog,
type CatalogIO,
type CatalogSourceConfig,
@@ -38,6 +41,7 @@ import {
setActiveCatalog,
setCustomProviders,
setDiscoveredCodexModels,
+ setModelRegistryFromCatalog,
setProviderModelsFromCatalog,
} from './active-catalog.js';
import {
@@ -89,6 +93,7 @@ import {
migrateLegacyNativeProviderAuthBindings,
} from './nativeProviderAuthBinding.js';
import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';
+import { broadcastEffectiveModelPricing } from '../usage/modelPricing.js';
const log = createLogger('provider-service');
@@ -143,9 +148,168 @@ function fetchText(url: string, timeoutMs: number): Promise<string> {
});
}
-/** 桌面端 CatalogIO —— net + fs 落地(无磁盘缓存:目录每进程拉一次存内存,无需落盘)。 */
+const CATALOG_LKG_VERSION = 2;
+
+interface CatalogLkgEnvelope {
+ version: typeof CATALOG_LKG_VERSION;
+ scopeHash: string;
+ catalog: string;
+}
+
+interface CatalogLkgFileIo {
+ rename(from: string, to: string): Promise<void>;
+ rm(target: string, options: { force: boolean }): Promise<void>;
+}
+
+const catalogLkgWriteTails = new Map<string, Promise<void>>();
+
+function catalogScopeHash(scope: string): string {
+ return createHash('sha256').update(scope).digest('hex');
+}
+
+function catalogLkgPath(scope: string): string {
+ return path.join(
+ app.getPath('userData'),
+ 'cache',
+ 'model-catalog',
+ `${catalogScopeHash(scope).slice(0, 24)}.json`,
+ );
+}
+
+function catalogLkgEnvelope(scope: string, catalog: string): CatalogLkgEnvelope {
+ return {
+ version: CATALOG_LKG_VERSION,
+ scopeHash: catalogScopeHash(scope),
+ catalog,
+ };
+}
+
+async function readCatalogLkg(scope: string): Promise<string | null> {
+ const file = catalogLkgPath(scope);
+ for (const candidate of [file, `${file}.bak`]) {
+ try {
+ const envelope = JSON.parse(
+ await fsp.readFile(candidate, 'utf8'),
+ ) as Partial<CatalogLkgEnvelope>;
+ return envelope.version === CATALOG_LKG_VERSION &&
+ envelope.scopeHash === catalogScopeHash(scope) &&
+ typeof envelope.catalog === 'string'
+ ? envelope.catalog
+ : null;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw err;
+ }
+ }
+ return null;
+}
+
+/**
+ * Replace an existing LKG without depending on POSIX rename-overwrite semantics. Windows may
+ * reject that operation while the destination exists, so preserve the prior snapshot until the
+ * new file is in place and restore it if the second rename fails.
+ */
+async function replaceCatalogLkgFile(
+ temporary: string,
+ file: string,
+ fileIo: CatalogLkgFileIo = fsp,
+): Promise<void> {
+ try {
+ await fileIo.rename(temporary, file);
+ await fileIo.rm(`${file}.bak`, { force: true }).catch(() => undefined);
+ return;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY' && code !== 'EEXIST') throw err;
+ }
+
+ const backup = `${file}.bak`;
+ await fileIo.rm(backup, { force: true }).catch(() => undefined);
+ let preservedExisting = false;
+ try {
+ await fileIo.rename(file, backup);
+ preservedExisting = true;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
+ }
+ try {
+ await fileIo.rename(temporary, file);
+ } catch (err) {
+ if (preservedExisting) {
+ await fileIo.rename(backup, file).catch(() => undefined);
+ }
+ throw err;
+ }
+ if (preservedExisting) {
+ await fileIo.rm(backup, { force: true }).catch(() => undefined);
+ }
+}
+
+function catalogLkgTemporaryPath(file: string, nonce = randomUUID()): string {
+ return `${file}.${process.pid}.${nonce}.tmp`;
+}
+
+/** Serialize the complete replace transaction per scope while leaving different scopes parallel. */
+async function serializeCatalogLkgWrite<T>(
+ file: string,
+ write: () => Promise<T>,
+): Promise<T> {
+ const previous = catalogLkgWriteTails.get(file) ?? Promise.resolve();
+ const current = previous.catch(() => undefined).then(write);
+ const tail = current.then(
+ () => undefined,
+ () => undefined,
+ );
+ catalogLkgWriteTails.set(file, tail);
+ try {
+ return await current;
+ } finally {
+ if (catalogLkgWriteTails.get(file) === tail) catalogLkgWriteTails.delete(file);
+ }
+}
+
+function selectCatalogLkgSnapshot(incoming: string, current: string | null): string {
+ if (current === null) return incoming;
+ try {
+ const incomingUpdatedAt = parseCatalog(incoming).modelRegistry?.updatedAt;
+ const currentUpdatedAt = parseCatalog(current).modelRegistry?.updatedAt;
+ const incomingRevision = incomingUpdatedAt ? Date.parse(incomingUpdatedAt) : Number.NaN;
+ const currentRevision = currentUpdatedAt ? Date.parse(currentUpdatedAt) : Number.NaN;
+ if (
+ Number.isFinite(currentRevision) &&
+ (!Number.isFinite(incomingRevision) || currentRevision > incomingRevision)
+ ) {
+ return current;
+ }
+ } catch {
+ // An invalid current envelope payload is not an LKG; replace it with the already-validated input.
+ }
+ return incoming;
+}
+
+async function writeCatalogLkg(scope: string, catalog: string): Promise<string> {
+ const file = catalogLkgPath(scope);
+ return serializeCatalogLkgWrite(file, async () => {
+ const selected = selectCatalogLkgSnapshot(catalog, await readCatalogLkg(scope));
+ if (selected !== catalog) return selected;
+ const temporary = catalogLkgTemporaryPath(file);
+ await fsp.mkdir(path.dirname(file), { recursive: true });
+ const envelope = catalogLkgEnvelope(scope, selected);
+ await fsp.writeFile(temporary, JSON.stringify(envelope), 'utf8');
+ try {
+ await replaceCatalogLkgFile(temporary, file);
+ } finally {
+ await fsp.rm(temporary, { force: true }).catch(() => undefined);
+ }
+ return selected;
+ });
+}
+
+/** 桌面端 CatalogIO —— net + fs + 按端点隔离的 last-known-good 快照。 */
const io: CatalogIO = {
fetchText,
+ readCache: readCatalogLkg,
+ writeCache: writeCatalogLkg,
async readFile(p) {
try {
return await fsp.readFile(p, 'utf-8');
@@ -166,18 +330,32 @@ const io: CatalogIO = {
*/
function buildSource(): CatalogSourceConfig {
const dev = isDev();
+ const explicitUrl = process.env.XDT_MODELS_URL;
const baseUrl = dev ? undefined : getClientEndpoint('modelAccessApiBaseUrl');
const usesBuildRealm = !dev && baseUrl === getBuildClientEndpoint('modelAccessApiBaseUrl');
return {
- url: process.env.XDT_MODELS_URL,
+ url: explicitUrl,
localPath: process.env.XDT_MODELS_PATH,
baseUrl,
fallbackBaseUrl: dev || !usesBuildRealm ? undefined : getBaseUrl(),
remoteBudgetMs: DEFAULT_REMOTE_CATALOG_BUDGET_MS,
- disableFetch: dev || process.env.XDT_DISABLE_MODELS_FETCH === '1',
+ disableFetch: shouldDisableCatalogFetch(
+ dev,
+ explicitUrl,
+ process.env.XDT_DISABLE_MODELS_FETCH === '1',
+ ),
};
}
+/** dev 缺省禁网;显式 URL 是唯一远端调试入口,强制禁网始终拥有最高优先级。 */
+export function shouldDisableCatalogFetch(
+ dev: boolean,
+ explicitUrl: string | undefined,
+ forcedDisabled: boolean,
+): boolean {
+ return forcedDisabled || (dev && !explicitUrl?.trim());
+}
+
function catalogSourceKey(source: CatalogSourceConfig): string {
return JSON.stringify({
url: source.url ?? null,
@@ -189,8 +367,8 @@ function catalogSourceKey(source: CatalogSourceConfig): string {
}
/**
- * 一次性清理旧版本遗留的目录磁盘缓存(provider-catalog-cache.json + .tmp)。
- * 现版本目录每进程拉一次存内存、不落盘,这两个文件不再被读写,纯属历史孤儿。
+ * 一次性清理旧版本遗留的未分 scope 目录缓存(provider-catalog-cache.json + .tmp)。
+ * 新版 LKG 使用 cache/model-catalog/<scope-hash>.json,不读取这两个历史文件。
* best-effort:不存在 / 删除失败都静默忽略(fsp.rm force 不因 ENOENT 抛),绝不阻塞或抛。
*/
async function cleanupLegacyCatalogCache(): Promise<void> {
@@ -206,7 +384,10 @@ async function cleanupLegacyCatalogCache(): Promise<void> {
let activeLoaded = false;
let activeInflight: Promise<Catalog> | null = null;
-let catalogRefreshInflight: Promise<Catalog> | null = null;
+let catalogRefreshInflight: {
+ sourceKey: string;
+ promise: Promise<Catalog>;
+} | null = null;
let activeCatalogSourceKey: string | null = null;
let endpointReloadGeneration = 0;
let endpointReloadInflight: {
@@ -273,6 +454,7 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
.then(async (catalog) => {
activeCatalogSourceKey = sourceKey;
setActiveCatalog(catalog);
+ broadcastEffectiveModelPricing();
// 读 codex models_cache.json 得到规范化快照,由 active-catalog 同时投影到 Codex 与
// Claude bridge。null 表示没读到有效 cache,保留现值 / 静态兜底;[] 表示合法空快照。
try {
@@ -319,6 +501,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
activeCatalogSourceKey = null;
// 必须在网络 await 前失效:登录提交后 renderer/agent 可能立即读取目录。
setActiveCatalog(BUNDLED_CATALOG);
+ broadcastEffectiveModelPricing();
const flight = loadCatalog(source, io)
.then((catalog) => {
@@ -330,6 +513,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
}
activeCatalogSourceKey = sourceKey;
setActiveCatalog(catalog);
+ broadcastEffectiveModelPricing();
return getActiveCatalog();
})
.finally(() => {
@@ -342,25 +526,53 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
}
/**
- * 手动重载 xAI 模型目录。先确保启动期动态发现已完成,再复用同一 `loadCatalog`
- * 源选择与 bundled fallback;只投影 xAI 的静态模型列表,当前 routing/auth 以及其它
- * provider 全部保持不变,避免活跃 turn 中途被整份远端目录切换路由。
+ * 手动重载 xAI 模型目录与统一 modelRegistry。先确保启动期动态发现已完成,再复用同一
+ * `loadCatalog` 源选择与 bundled fallback;xAI 只投影静态模型列表,当前 routing/auth
+ * 以及其它 provider 保持不变;modelRegistry 仅接受不旧于当前版本的快照。
*/
export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
await ensureActiveCatalogLoaded();
- if (catalogRefreshInflight) return catalogRefreshInflight;
- const flight = loadCatalogWithSource(buildSource(), io)
+ const sourceConfig = buildSource();
+ const sourceKey = catalogSourceKey(sourceConfig);
+ if (catalogRefreshInflight?.sourceKey === sourceKey) {
+ return catalogRefreshInflight.promise;
+ }
+ const generation = endpointReloadGeneration;
+ const flight = loadCatalogWithSource(sourceConfig, io)
.then(({ catalog, source }) => {
if (source === 'bundled') {
throw new Error('catalog refresh exhausted configured sources; keeping current snapshot');
}
+ if (
+ endpointReloadGeneration !== generation ||
+ activeCatalogSourceKey !== sourceKey ||
+ catalogSourceKey(buildSource()) !== sourceKey
+ ) {
+ return getActiveCatalog();
+ }
+ const currentRegistry = getActiveCatalog().modelRegistry;
+ const incomingRegistry = catalog.modelRegistry;
+ if (
+ currentRegistry &&
+ incomingRegistry &&
+ incomingRegistry.updatedAt < currentRegistry.updatedAt
+ ) {
+ return getActiveCatalog();
+ }
setProviderModelsFromCatalog('xai', catalog);
+ if (
+ incomingRegistry &&
+ (!currentRegistry || incomingRegistry.updatedAt >= currentRegistry.updatedAt)
+ ) {
+ setModelRegistryFromCatalog(catalog);
+ }
+ broadcastEffectiveModelPricing();
return getActiveCatalog();
})
.finally(() => {
- if (catalogRefreshInflight === flight) catalogRefreshInflight = null;
+ if (catalogRefreshInflight?.promise === flight) catalogRefreshInflight = null;
});
- catalogRefreshInflight = flight;
+ catalogRefreshInflight = { sourceKey, promise: flight };
return flight;
}
@@ -544,3 +756,14 @@ export function getDesktopProviderService(): ProviderService {
});
return singleton;
}
+
+export const __testing = {
+ catalogLkgEnvelope,
+ catalogLkgPath,
+ catalogLkgTemporaryPath,
+ readCatalogLkg,
+ replaceCatalogLkgFile,
+ selectCatalogLkgSnapshot,
+ serializeCatalogLkgWrite,
+ writeCatalogLkg,
+};
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 c8d559b18a..7b0a784278 100644
--- a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
+++ b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
@@ -32,7 +32,7 @@
* 串行队列 + 原子 rename,保证登出删缓存不会被较早的 SDK 持久化反向覆盖。
*
* contextWindow 规则:
- * HTTP 响应带 max_input_tokens 用之;否则读取当前 cindyModelMeta 的已知窗口;
+ * HTTP 响应带 max_input_tokens 用之;否则读取当前 modelRegistry 的已知窗口;
* 目录未知时默认 1M,仅 id 含 "haiku" 例外 200k。这样已知旧模型不会被错误提升到
* 1M,未来新模型仍可在目录更新前按当代默认工作。
*
@@ -290,7 +290,7 @@ function fallbackEffortBaseline(id: string): { efforts: Effort[]; defaultEffort:
* SDK `supportedModels()` 条目 → 映射结果。纯函数。
* 只收 `claude` 开头的显式版本 id(规则 10:禁止 opus/sonnet 裸别名进目录)。
* ModelInfo 的能力字段全部 optional:字段在场时 SDK 是能力权威(supportsEffort=false =
- * 不可调);**字段缺席 = 该字段未知**,按 cindyModelMeta 基线 / 确定性默认合成,
+ * 不可调);**字段缺席 = 该字段未知**,按 modelRegistry 基线 / 确定性默认合成,
* 合并时保留该字段已精化的旧值——不能把「CLI 没填」解读成「不支持」而抹掉档位。
*/
export function mapAnthropicSdkModels(raw: unknown): SdkMappedModel[] {
@@ -419,7 +419,7 @@ function mergeCapabilitiesWithPrevious(
/**
* HTTP `GET /v1/models` 单页条目数组 → 映射结果。纯函数,对响应形状容错:
* 能力字段(capabilities.efforts / fast_mode)是 Anthropic 侧未固化的扩展,逐字段识别;
- * effort 认不出时按 cindyModelMeta 能力基线合成,目录也没有才回落当代旗舰 5 档
+ * effort 认不出时按 modelRegistry 能力基线合成,目录也没有才回落当代旗舰 5 档
* (low/medium/high/xhigh/max,默认 high),haiku 系例外 0 档。fastMode 未知时先为 false,
* 合并阶段会保留已明确探测过的旧值。
*/
diff --git a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
index 61216ce55f..88c629bb21 100644
--- a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
@@ -26,6 +26,8 @@ export const PROVIDER_MODEL_FOREGROUND_BACKGROUND_THRESHOLD_MS = 15 * 60_000;
export interface ProviderModelAutoRefreshDeps {
listProviders(options: { allowSideEffects: true }): Promise<ProviderView[]>;
refreshProvider(providerId: BuiltinRefreshableProviderId): Promise<void>;
+ /** Refresh the shared public Catalog independently of any provider connection state. */
+ refreshCatalog?: () => Promise<void>;
getScopeKey?: () => string | number;
now(): number;
log: Pick<Logger, 'debug' | 'warn'>;
@@ -60,6 +62,10 @@ export function createProviderModelRefreshCoordinator(
const lastAttemptAt = new Map<BuiltinRefreshableProviderId, number>();
const lastFailureAt = new Map<BuiltinRefreshableProviderId, number>();
const providerGenerations = new Map<BuiltinRefreshableProviderId, number>();
+ let catalogInflight: { promise: Promise<void>; scopeGeneration: number } | null = null;
+ let catalogLastAttemptAt: number | undefined;
+ let catalogLastFailureAt: number | undefined;
+ let catalogStartupGraceUntil: number | undefined;
let scopeKey = deps.getScopeKey?.();
let scopeGeneration = 0;
@@ -75,6 +81,10 @@ export function createProviderModelRefreshCoordinator(
// 强制请求 join 进去等于让它等一件与自己无关的事。
forcedFollowUp.clear();
providerGenerations.clear();
+ catalogInflight = null;
+ catalogLastAttemptAt = undefined;
+ catalogLastFailureAt = undefined;
+ catalogStartupGraceUntil = undefined;
deps.log.debug('provider model auto-refresh scope changed', { scopeGeneration });
}
@@ -92,6 +102,72 @@ export function createProviderModelRefreshCoordinator(
}
lastAttemptAt.clear();
lastFailureAt.clear();
+ catalogLastAttemptAt = undefined;
+ catalogLastFailureAt = undefined;
+ catalogStartupGraceUntil = undefined;
+ }
+
+ async function refreshCatalogAutomatically(
+ trigger: ProviderModelAutoRefreshTrigger,
+ ): Promise<void> {
+ if (!deps.refreshCatalog) return;
+ syncScope();
+ // splash 已经 await ensureActiveCatalogLoaded;startup 不重复请求。加载器对 bundled
+ // 兜底同样返回成功,故这里不能武断地压 30 分钟——只给 5 分钟启动宽限,服务器刚
+ // 恢复时不必等半小时;首次后续成功再进入正常 30 分钟冷却。
+ if (trigger === 'startup') {
+ catalogStartupGraceUntil =
+ deps.now() + PROVIDER_MODEL_AUTO_REFRESH_FAILURE_COOLDOWN_MS;
+ return;
+ }
+ if (catalogInflight?.scopeGeneration === scopeGeneration) {
+ return catalogInflight.promise;
+ }
+ const now = deps.now();
+ if (catalogStartupGraceUntil !== undefined) {
+ if (now < catalogStartupGraceUntil) {
+ deps.log.debug('model catalog auto-refresh skipped by startup grace', {
+ trigger,
+ remainingMs: catalogStartupGraceUntil - now,
+ });
+ return;
+ }
+ catalogStartupGraceUntil = undefined;
+ }
+ const cooldownStartedAt = catalogLastFailureAt ?? catalogLastAttemptAt;
+ const cooldownMs = catalogLastFailureAt === undefined
+ ? PROVIDER_MODEL_AUTO_REFRESH_COOLDOWN_MS
+ : PROVIDER_MODEL_AUTO_REFRESH_FAILURE_COOLDOWN_MS;
+ if (cooldownStartedAt !== undefined && now - cooldownStartedAt < cooldownMs) {
+ deps.log.debug('model catalog auto-refresh skipped by cooldown', {
+ trigger,
+ cooldown: catalogLastFailureAt === undefined ? 'normal' : 'failure-retry',
+ remainingMs: cooldownMs - (now - cooldownStartedAt),
+ });
+ return;
+ }
+
+ const generation = scopeGeneration;
+ catalogLastAttemptAt = now;
+ const flight = Promise.resolve()
+ .then(() => deps.refreshCatalog!())
+ .then(
+ () => {
+ if (scopeGeneration === generation) catalogLastFailureAt = undefined;
+ },
+ (error: unknown) => {
+ if (scopeGeneration === generation) catalogLastFailureAt = deps.now();
+ deps.log.warn('model catalog auto-refresh failed', {
+ trigger,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ },
+ )
+ .finally(() => {
+ if (catalogInflight?.promise === flight) catalogInflight = null;
+ });
+ catalogInflight = { promise: flight, scopeGeneration: generation };
+ await flight;
}
/**
@@ -186,6 +262,7 @@ export function createProviderModelRefreshCoordinator(
return {
async requestAutoRefresh(trigger, providerIds): Promise<void> {
syncScope();
+ const catalogRefresh = refreshCatalogAutomatically(trigger);
let providers: ProviderView[];
try {
providers = await deps.listProviders({ allowSideEffects: true });
@@ -194,9 +271,14 @@ export function createProviderModelRefreshCoordinator(
trigger,
error: err instanceof Error ? err.message : String(err),
});
+ await catalogRefresh;
return;
}
+ // Provider discovery may use the public registry to fill context windows and effort
+ // defaults omitted by the provider response. Apply the catalog snapshot first so a
+ // concurrent discovery cannot permanently derive capabilities from the previous one.
+ await catalogRefresh;
syncScope();
const connectedIds = new Set<BuiltinRefreshableProviderId>();
for (const provider of providers) {
@@ -210,7 +292,15 @@ export function createProviderModelRefreshCoordinator(
}
const requestedIds = providerIds ?? BUILTIN_REFRESHABLE_PROVIDER_IDS;
- const ids = requestedIds.filter((id) => connectedIds.has(id));
+ const ids = requestedIds.filter(
+ (id) =>
+ connectedIds.has(id) &&
+ // xAI's provider refresh reads the same public Catalog as refreshCatalog. The shared
+ // refresh already ran (or was intentionally skipped because splash/cooldown made its
+ // snapshot current), so running the provider hook would fetch the identical source a
+ // second time. Manual xAI refresh still uses refreshProvider and bypasses this path.
+ !(id === 'xai' && deps.refreshCatalog),
+ );
// 启动期无视冷却(见 `'startup'` trigger 注释);in-flight 合并仍生效,所以并发的
// 启动触发与手动刷新不会各起一次 codex app-server。
const force = isForcedProviderModelAutoRefreshTrigger(trigger);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index ef0a8bf4b7..411fb533fd 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -100,6 +100,21 @@ function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps
scanLocalCli: vi.fn(async () => []),
setModelsDisabled: vi.fn(() => {}),
setProviderDisabled: vi.fn(() => {}),
+ getLedgerCurrency: () => 'USD',
+ readModelPriceOverride: vi.fn((target) => ({
+ target,
+ editable: target.providerId !== 'xd',
+ reference: null,
+ effective: null,
+ override: null,
+ conflict: false,
+ registryUpdatedAt: null,
+ allowedCurrencies: ['USD' as const],
+ })),
+ writeModelPriceOverride: vi.fn(() => {}),
+ clearModelPriceOverride: vi.fn(() => {}),
+ stageClearProviderModelPriceOverrides: vi.fn(() => () => true),
+ broadcastPricingChanged: vi.fn(() => {}),
...over,
};
}
@@ -1029,6 +1044,7 @@ describe('provider:custom:* CRUD handlers', () => {
keys.delete(agent);
return { success: true };
}),
+ stageClearProviderModelPriceOverrides: vi.fn(() => () => true),
}));
await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig);
raw!.exec(`
@@ -1267,6 +1283,8 @@ describe('provider:custom:* CRUD handlers', () => {
expect(await listCustomProviders()).toEqual([]);
expect(keys.size).toBe(0);
expect(calls).toEqual(['cancel', 'clear']);
+ expect(deps.stageClearProviderModelPriceOverrides).toHaveBeenCalledWith('openrouter');
+ expect(deps.broadcastPricingChanged).toHaveBeenCalled();
await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, '')).rejects.toThrow(
/INVALID_PARAMS/,
@@ -1357,6 +1375,126 @@ describe('provider:custom:* CRUD handlers', () => {
});
});
+describe('model price override handlers', () => {
+ const target = {
+ providerId: 'openrouter',
+ agent: 'codex' as const,
+ modelId: 'meta/llama-4',
+ };
+
+ it('reads and writes a catalog member through the trusted visual settings path', async () => {
+ const harness = new IpcHarness();
+ const deps = makeDeps({
+ listProviders: async () => [
+ catalogView('openrouter', { codex: ['meta/llama-4'] }),
+ ],
+ });
+ registerProviderHandlers(harness, deps);
+
+ await harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_GET, target);
+ expect(deps.readModelPriceOverride).toHaveBeenCalledWith(target);
+
+ const desired = {
+ currency: 'USD' as const,
+ inputPerMtok: 1.25,
+ outputPerMtok: 5,
+ cacheReadPerMtok: null,
+ };
+ await harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_SET, target, desired);
+ expect(deps.writeModelPriceOverride).toHaveBeenCalledWith(target, desired);
+ expect(deps.broadcastPricingChanged).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects unknown models, malformed prices, and XD sale-price overrides', async () => {
+ const harness = new IpcHarness();
+ const deps = makeDeps({
+ listProviders: async () => [
+ catalogView('openrouter', { codex: ['meta/llama-4'] }),
+ catalogView('xd', { codex: ['gpt-5.5'] }),
+ ],
+ });
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_GET, {
+ ...target,
+ modelId: 'missing',
+ }),
+ ).rejects.toThrow(/INVALID_PARAMS/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_SET, target, {
+ currency: 'USD',
+ inputPerMtok: -1,
+ outputPerMtok: 5,
+ }),
+ ).rejects.toThrow(/INVALID_PARAMS/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_SET, target, {
+ currency: 'CNY',
+ inputPerMtok: 1,
+ outputPerMtok: 5,
+ }),
+ ).rejects.toThrow(/CNY price overrides cannot project into a USD ledger/);
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.MODEL_PRICE_OVERRIDE_SET,
+ { providerId: 'xd', agent: 'codex', modelId: 'gpt-5.5' },
+ { currency: 'USD', inputPerMtok: 1, outputPerMtok: 2 },
+ ),
+ ).rejects.toThrow(/server-controlled/);
+ expect(deps.writeModelPriceOverride).not.toHaveBeenCalled();
+ });
+
+ it('guards price reads before returning owner-scoped override data', async () => {
+ const harness = new IpcHarness();
+ const assertTrustedSender = vi.fn(() => {
+ throwIpcError('PERMISSION_DENIED', 'untrusted price override reader');
+ });
+ const deps = makeDeps({
+ assertTrustedSender,
+ listProviders: async () => [catalogView('openrouter', { codex: ['meta/llama-4'] })],
+ });
+ registerProviderHandlers(harness, deps);
+
+ await expect(harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_GET, target)).rejects.toThrow(
+ /PERMISSION_DENIED/,
+ );
+ expect(assertTrustedSender).toHaveBeenCalledOnce();
+ expect(deps.readModelPriceOverride).not.toHaveBeenCalled();
+ });
+
+ it('resets an orphaned sparse override without requiring the model to remain listed', async () => {
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+
+ await harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_RESET, target);
+ expect(deps.clearModelPriceOverride).toHaveBeenCalledWith(target);
+ expect(deps.broadcastPricingChanged).toHaveBeenCalledTimes(1);
+ });
+
+ it('converts reset persistence failures to a stable IPC error without leaking paths', async () => {
+ const harness = new IpcHarness();
+ const clearModelPriceOverride = vi.fn(() => {
+ throw new Error('EROFS: read-only file system, unlink /private/userData/model-price.json');
+ });
+ const deps = makeDeps({ clearModelPriceOverride });
+ registerProviderHandlers(harness, deps);
+
+ let failure: unknown;
+ try {
+ await harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_RESET, target);
+ } catch (error) {
+ failure = error;
+ }
+
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toMatch(/INTERNAL.*failed to reset model price override/);
+ expect((failure as Error).message).not.toContain('/private/userData');
+ expect(deps.broadcastPricingChanged).not.toHaveBeenCalled();
+ });
+});
+
describe('provider:presets handler', () => {
it('returns injected presets as { presets }', async () => {
const harness = new IpcHarness();
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index ea14615c8e..e0d0e667e1 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -207,6 +207,10 @@ export const MAKER_INVOKE = {
* **不进 device-link allowlist**(远程改被控端全局设置越权,见 allowlist.ts 准入判据)。
*/
MODEL_DISABLE_SET: 'maker:model-disable:set',
+ /** Visual Settings UI only: read/write/reset a per-provider × runtime × model price estimate. */
+ MODEL_PRICE_OVERRIDE_GET: 'maker:model-price-override:get',
+ MODEL_PRICE_OVERRIDE_SET: 'maker:model-price-override:set',
+ MODEL_PRICE_OVERRIDE_RESET: 'maker:model-price-override:reset',
// 附加只读引用目录 — 走 closure 推送; DB 持久化由 renderer 同步调
// local-db:sessions:update (跟 SET_MODEL / sessionService.update 双 IPC 协调先例一致)
SET_EXTRA_DIRS: 'maker:set-extra-dirs',
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 2d6bf4384b..6fb298b704 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -26,6 +26,12 @@ import {
import type { LocalCliDetection } from '../../shared/localCliDetect.js';
import { isIpcError } from '../../shared/ipc-errors.js';
+import type {
+ ModelPriceOverrideDesiredQuote,
+ ModelPriceOverrideTarget,
+ ModelPriceOverrideView,
+} from '../../shared/modelPriceOverride.js';
+import type { MoneyCurrency } from '../../shared/regionalMoney.js';
import {
BUILTIN_REFRESHABLE_PROVIDER_IDS,
isBuiltinRefreshableProviderId,
@@ -279,6 +285,16 @@ export interface ProviderHandlerDeps {
* 可选:未注入(单测最小桩)= 不做归属校验。
*/
currentOwnerId?(): string | null;
+ /** Active account ledger currency; used to reject unsupported reverse-FX overrides. */
+ getLedgerCurrency(): MoneyCurrency;
+ readModelPriceOverride(target: ModelPriceOverrideTarget): ModelPriceOverrideView;
+ writeModelPriceOverride(
+ target: ModelPriceOverrideTarget,
+ desired: ModelPriceOverrideDesiredQuote,
+ ): void;
+ clearModelPriceOverride(target: ModelPriceOverrideTarget): void;
+ stageClearProviderModelPriceOverrides?(providerId: string): () => boolean;
+ broadcastPricingChanged(): void;
}
/** 校验 PROVIDER_TEST_CONNECTION 入参形状(确定性代码校验,非法直接 INVALID_PARAMS)。 */
@@ -802,6 +818,146 @@ export function registerProviderHandlers(
return enqueueDisableWrite(run);
});
+ const parsePriceTarget = (value: unknown): ModelPriceOverrideTarget => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throwIpcError('INVALID_PARAMS', 'price override target must be an object');
+ }
+ const target = value as Record<string, unknown>;
+ if (
+ typeof target.providerId !== 'string' ||
+ target.providerId.length === 0 ||
+ target.providerId.length > MAX_DISABLE_ID_LENGTH ||
+ !VALID_AGENTS.includes(String(target.agent)) ||
+ typeof target.modelId !== 'string' ||
+ target.modelId.length === 0 ||
+ target.modelId.length > MAX_DISABLE_ID_LENGTH
+ ) {
+ throwIpcError('INVALID_PARAMS', 'invalid price override target');
+ }
+ return {
+ providerId: target.providerId,
+ agent: target.agent as AgentKind,
+ modelId: target.modelId,
+ };
+ };
+ const parseDesiredPrice = (value: unknown): ModelPriceOverrideDesiredQuote => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throwIpcError('INVALID_PARAMS', 'price override quote must be an object');
+ }
+ const quote = value as Record<string, unknown>;
+ const validNumber = (candidate: unknown): candidate is number =>
+ typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0;
+ const validNullableNumber = (candidate: unknown): boolean =>
+ candidate === undefined || candidate === null || validNumber(candidate);
+ if (
+ (quote.currency !== 'USD' && quote.currency !== 'CNY') ||
+ !validNumber(quote.inputPerMtok) ||
+ !validNumber(quote.outputPerMtok) ||
+ !validNullableNumber(quote.cacheReadPerMtok) ||
+ !validNullableNumber(quote.cacheCreatePerMtok)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'invalid price override quote');
+ }
+ return {
+ currency: quote.currency,
+ inputPerMtok: quote.inputPerMtok,
+ outputPerMtok: quote.outputPerMtok,
+ ...(quote.cacheReadPerMtok === null || validNumber(quote.cacheReadPerMtok)
+ ? { cacheReadPerMtok: quote.cacheReadPerMtok }
+ : {}),
+ ...(quote.cacheCreatePerMtok === null || validNumber(quote.cacheCreatePerMtok)
+ ? { cacheCreatePerMtok: quote.cacheCreatePerMtok }
+ : {}),
+ };
+ };
+ const requirePriceTargetModel = async (
+ target: ModelPriceOverrideTarget,
+ ): Promise<ProviderView> => {
+ const provider = (await deps.listProviders({ allowSideEffects: false }))
+ .find((candidate) => candidate.id === target.providerId);
+ const known = provider?.models[target.agent]?.some((model) => model.id === target.modelId);
+ if (!provider || !known) {
+ throwIpcError('INVALID_PARAMS', 'price override target is not in the active catalog');
+ }
+ return provider;
+ };
+ let priceMutationTail: Promise<unknown> = Promise.resolve();
+ const enqueuePriceMutation = <T,>(run: () => T | Promise<T>): Promise<T> => {
+ const result = priceMutationTail.catch(() => undefined).then(run);
+ priceMutationTail = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+ };
+
+ registry.handle(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_GET, async (event, input: unknown) => {
+ assertTrustedProviderMutationSender(event);
+ const target = parsePriceTarget(input);
+ await requirePriceTargetModel(target);
+ return deps.readModelPriceOverride(target);
+ });
+
+ registry.handle(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_SET, async (event, targetInput: unknown, quoteInput: unknown) => {
+ assertTrustedProviderMutationSender(event);
+ const target = parsePriceTarget(targetInput);
+ const desired = parseDesiredPrice(quoteInput);
+ if (target.providerId === 'xd') {
+ throwIpcError('INVALID_PARAMS', 'Cindy AI Gateway pricing is server-controlled');
+ }
+ if (desired.currency === 'CNY' && deps.getLedgerCurrency() === 'USD') {
+ throwIpcError('INVALID_PARAMS', 'CNY price overrides cannot project into a USD ledger');
+ }
+ const ownerAtIngress = deps.currentOwnerId?.() ?? null;
+ return withProviderConfigMutation(target.providerId, () =>
+ enqueuePriceMutation(async () => {
+ await requirePriceTargetModel(target);
+ if (deps.currentOwnerId && (deps.currentOwnerId() ?? null) !== ownerAtIngress) {
+ throwIpcError('INTERNAL', 'active account changed before persisting price override');
+ }
+ try {
+ deps.writeModelPriceOverride(target, desired);
+ } catch (err) {
+ log.warn('model price override persist failed', {
+ providerId: target.providerId,
+ agent: target.agent,
+ modelId: target.modelId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ throwIpcError('INTERNAL', 'failed to persist model price override');
+ }
+ deps.broadcastPricingChanged();
+ return deps.readModelPriceOverride(target);
+ }),
+ );
+ });
+
+ registry.handle(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_RESET, async (event, input: unknown) => {
+ assertTrustedProviderMutationSender(event);
+ const target = parsePriceTarget(input);
+ const ownerAtIngress = deps.currentOwnerId?.() ?? null;
+ return withProviderConfigMutation(target.providerId, () =>
+ enqueuePriceMutation(async () => {
+ if (deps.currentOwnerId && (deps.currentOwnerId() ?? null) !== ownerAtIngress) {
+ throwIpcError('INTERNAL', 'active account changed before resetting price override');
+ }
+ try {
+ deps.clearModelPriceOverride(target);
+ } catch (err) {
+ log.warn('model price override reset failed', {
+ providerId: target.providerId,
+ agent: target.agent,
+ modelId: target.modelId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ throwIpcError('INTERNAL', 'failed to reset model price override');
+ }
+ deps.broadcastPricingChanged();
+ return deps.readModelPriceOverride(target);
+ }),
+ );
+ });
+
registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, async (event, input: unknown, keyInput?: unknown) => {
assertTrustedProviderMutationSender(event);
const v = validateCustomProviderConfig(input);
@@ -921,6 +1077,7 @@ export function registerProviderHandlers(
// OAuth 形态自定义供应商的凭证 blob 一并清掉(apiKey 形态无 blob,幂等无害)。
let restoreOAuthCredentials: (() => boolean) | null = null;
let restoreDisableOverrides: (() => boolean) | null = null;
+ let restorePriceOverrides: (() => boolean) | null = null;
// 整个删除事务(清 override → 删凭证 → 删配置 → 刷目录)在 disable 写队列**内**
// 执行,持队列直到 afterChange 刷完 active-catalog:只把清理入队的话,清理落盘
// 后队列即释放,「删除完成前」的窗口里并发 MODEL_DISABLE_SET 仍能从未刷新的
@@ -935,6 +1092,8 @@ export function registerProviderHandlers(
// 不再出现「配置删了、override 残留」让同 id 重建复活旧停用状态。
restoreDisableOverrides =
deps.stageClearProviderDisableOverrides?.(providerId) ?? null;
+ restorePriceOverrides =
+ deps.stageClearProviderModelPriceOverrides?.(providerId) ?? null;
restoreOAuthCredentials = deps.removeOAuthCredentials(providerId);
if (!restoreOAuthCredentials) {
throwIpcError('INTERNAL', 'failed to remove existing OAuth credentials');
@@ -942,9 +1101,10 @@ export function registerProviderHandlers(
await deleteCustomProvider(providerId);
} catch (err) {
const overridesRestored = !restoreDisableOverrides || restoreDisableOverrides();
+ const pricesRestored = !restorePriceOverrides || restorePriceOverrides();
const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
const keysRestored = restoreProviderKeys(providerId, keySnapshots);
- if (!oauthRestored || !keysRestored || !overridesRestored) {
+ if (!oauthRestored || !keysRestored || !overridesRestored || !pricesRestored) {
throwIpcError(
'INTERNAL',
'provider deletion failed and existing credentials could not be restored',
@@ -956,6 +1116,7 @@ export function registerProviderHandlers(
// provider。afterChange 失败时配置已删,凭证/override 不回写(与改动前
// 语义一致 —— 恢复只覆盖删除本身失败的场景)。
await afterChange();
+ deps.broadcastPricingChanged();
});
return { ok: true };
} finally {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index a47b66087f..61fa31e406 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -296,10 +296,11 @@ import {
import { recordModelMismatchOnMessage } from '../modelMismatchBroadcaster.js';
import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';
import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
-import { getCodexSubscriptionValuePrice, getGatewayAccountCurrency, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';
+import { broadcastEffectiveModelPricing, getCodexProviderSubscriptionValuePrice, getGatewayAccountCurrency, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';
+import { clearModelPriceOverride, stageProviderModelPriceOverridesClear, readModelPriceOverrideView, setModelPriceOverride } from '../usage/modelPriceOverrideStore.js';
import { computeModelUsageDeltas, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';
import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey } from '../usage/usageHistory.js';
-import { buildClaudeTurnUsageDetails, computePriceQuoteTurnMoney, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks, type BillingRoute } from '../usage/turnCostCalculator.js';
+import { billingRouteForExplicitProvider, buildClaudeTurnUsageDetails, computePriceQuoteTurnMoney, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks, type BillingRoute } from '../usage/turnCostCalculator.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX, isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
import {
addRegionalMoney,
@@ -3248,6 +3249,14 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const sessionProviderForBilling = getSessionProvider(session.id);
const observedClaudeRoute =
sessionProviderForBilling == null ? readClaudeSessionRoute(session.id) : null;
+ const explicitProviderBillingRoute = billingRouteForExplicitProvider(
+ sessionProviderForBilling,
+ sessionProviderForBilling
+ ? getActiveCatalog().providers.find(
+ (provider) => provider.id === sessionProviderForBilling,
+ )?.access?.kind
+ : null,
+ );
const isClaudeSubscriptionSession = !session.remoteHostId && (
sessionProviderForBilling === 'anthropic'
|| (
@@ -3261,11 +3270,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
? 'unknown'
: isClaudeSubscriptionSession
? 'subscription'
- : sessionProviderForBilling === 'xd' || observedClaudeRoute === 'gateway'
- ? 'xd-gateway'
- : sessionProviderForBilling
- ? 'provider-api'
- : 'unknown';
+ : explicitProviderBillingRoute
+ ?? (observedClaudeRoute === 'gateway' ? 'xd-gateway' : 'unknown');
const pricing =
billingRoute === 'xd-gateway'
? await getModelPricingForModel(
@@ -3273,7 +3279,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
normalizeModelIdForPricing(deltas[0]?.model),
)
: await getModelPricing();
- const { turnMoney, perModel } = resolveClaudeTurnCostSinks(
+ const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(
deltas,
pricing,
{
@@ -3297,17 +3303,19 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
modelUsageWrites.push(recordModelTurnUsage({
agentKind: 'claude-code',
model: isClaudeSubscriptionValueRow ? claudeSubscriptionUsageModelKey(m.model) : m.model,
- money: m.money,
+ // daily_model_usage does not persist RegionalMoney.kind. Keep reference estimates
+ // out of this actual-cost row so they cannot be reconstructed as real API spend.
+ money: m.money?.kind === 'actual-cost' ? m.money : null,
inputTokensDelta: m.deltas.inputTokens,
outputTokensDelta: m.deltas.outputTokens,
cacheReadTokensDelta: m.deltas.cacheReadTokens,
cacheCreateTokensDelta: m.deltas.cacheCreateTokens,
}));
}
- // 纯订阅轮 (turnTotalUsd=0) 不走 recordTurnSpend, 没有任何 usage push ——
- // 等模型行落库后重广播今日 spend 快照, 通知已打开的首页仪表盘刷新
- // (对齐 codex 订阅轮的 rebroadcastCodexTodayUsage)。
- if (hasSubscriptionValueRow && !turnMoney) {
+ // 无真实费用、但产生订阅价值或 provider 参考估值的轮次不走
+ // recordTurnSpend。等模型行落库后重广播今日 spend 快照,通知已打开的首页
+ // 仪表盘刷新(对齐 codex 订阅轮的 rebroadcastCodexTodayUsage)。
+ if ((hasSubscriptionValueRow || estimatedTurnMoney) && !turnMoney) {
void Promise.allSettled(modelUsageWrites).then(() => rebroadcastTodaySpend());
}
if (turnMoney && turnMoney.amount > 0) {
@@ -3327,19 +3335,22 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
});
if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);
} else if (turnAssistantPersistId) {
- // 纯订阅轮(无真实计费)的「本轮价值」估算,挂到消息(isEstimate:true,chip 的
+ // 无真实计费轮的「本轮价值」估算,挂到消息(isEstimate:true,chip 的
// "本会话价值"由 useSessionEstimatedValue 汇总),不进 daily_spend /
- // sessions.total_cost_usd(那些是真实账单)。两类订阅同轮可叠加(如 Claude 订阅
- // 主会话 + bridge 订阅子 agent):
+ // sessions.total_cost_usd(那些是真实账单)。provider 参考价与两类订阅估值
+ // 可叠加(如 Claude 订阅主会话 + bridge 订阅子 agent):
+ // - provider-api 参考价:远程目录中的公开参考价,不是供应商真实账单;
// - bridge 订阅模型(chatgpt/ / xai/,source==='subscription'):静态参考价折算;
// - Claude 订阅会话(显式选 Anthropic,SDK 自报 cost=0):Anthropic 牌价折算
// (纯 Anthropic 轮 pricing 为 null → 家族牌价兜底表,不为估值发起网络请求)。
// 混合轮(真实计费 > 0)走上面的真实分支,订阅部分不另挂估算 —— 一条消息只有一个
// cost 字段,真实计费优先;订阅 token 明细仍在 turnUsageDetails.perModelCost 里。
- const estimatedValues: RegionalMoney[] = [];
+ const estimatedValues: RegionalMoney[] = estimatedTurnMoney
+ ? [estimatedTurnMoney]
+ : [];
for (const m of perModel) {
if (m.source !== 'subscription') continue;
- const quote = getSubscriptionDirectValuePrice(m.model);
+ const quote = getSubscriptionDirectValuePrice(m.model, 'claude-code', pricing);
const value = computePriceQuoteTurnMoney(
m.deltas,
quote ?? undefined,
@@ -3351,6 +3362,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const claudeEstimated = estimateClaudeSubscriptionTurnValue(
perModel,
currentLedgerCurrency(),
+ await getModelPricing(),
);
if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);
}
@@ -3405,25 +3417,30 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
await recordUsageOnly();
return;
}
- // 订阅直连轮(chatgpt/ / xai/)走窄兜底时: 真实计费恒 0, 不写 daily_spend /
- // sessions.total_cost_usd(与主路径 resolveTurnCost 的 subscription gate 同口径,
- // 避免把订阅 SDK 自报 cost 误记进计费)。
- if (isSubscriptionDirectModel(resolvedModel)) {
- await recordUsageOnly();
- return;
- }
const providerId = getSessionProvider(session.id);
const observedRoute =
providerId == null ? readClaudeSessionRoute(session.id) : null;
+ const explicitProviderRoute = billingRouteForExplicitProvider(
+ providerId,
+ providerId
+ ? getActiveCatalog().providers.find((provider) => provider.id === providerId)
+ ?.access?.kind
+ : null,
+ );
const route: BillingRoute = session.remoteHostId
? 'unknown'
: providerId === 'anthropic' || observedRoute === 'subscription'
? 'subscription'
- : providerId === 'xd' || observedRoute === 'gateway'
- ? 'xd-gateway'
- : providerId
- ? 'provider-api'
- : 'unknown';
+ : explicitProviderRoute
+ ?? (observedRoute === 'gateway' ? 'xd-gateway' : 'unknown');
+ // 订阅直连轮(chatgpt/ / xai/)走窄兜底时: 真实计费恒 0, 不写 daily_spend /
+ // sessions.total_cost_usd(与主路径 resolveTurnCost 的 subscription gate 同口径,
+ // 避免把订阅 SDK 自报 cost 误记进计费)。但显式 provider-api 是权威路由:
+ // 自定义 API 供应商可能供应带订阅前缀的模型 id,不能按前缀把真实费用判掉。
+ if (route !== 'provider-api' && isSubscriptionDirectModel(resolvedModel)) {
+ await recordUsageOnly();
+ return;
+ }
if (route === 'subscription' || route === 'xd-gateway') {
await recordUsageOnly();
return;
@@ -3518,13 +3535,32 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
isCodexBudgetRoute ||
(sessionProvider === 'xd' && hasGatewayKey)
);
+ // 显式来源的订阅判定以目录 access.kind 为权威(内置 anthropic 的 Claude.ai
+ // 订阅同样是订阅价值,不能只认 OpenAI/xAI);目录缺 access 的旧快照仍靠下面
+ // 的 openai oauth 分支兜底。
+ const sessionProviderAccessKind = sessionProvider
+ ? getActiveCatalog().providers.find((provider) => provider.id === sessionProvider)
+ ?.access?.kind
+ : null;
+ const isCodexSubscriptionAccessRoute =
+ !isRemoteCodexSession &&
+ sessionProvider != null &&
+ sessionProvider !== 'xd' &&
+ sessionProviderAccessKind === 'subscription' &&
+ !hasEffectiveGatewayRoute;
const isSubscriptionValue = isRemoteCodexSession ||
isCodexXaiProviderRoute ||
+ isCodexSubscriptionAccessRoute ||
(
isCodexOpenAiProviderRoute
&& codexAuthInjection === 'oauth-bearer'
&& !hasEffectiveGatewayRoute
);
+ const usesReferencePriceEstimate =
+ !isSubscriptionValue &&
+ !isRemoteCodexSession &&
+ !hasEffectiveGatewayRoute &&
+ Boolean(sessionProvider && sessionProvider !== 'xd');
const modelUsageKey = isSubscriptionValue
? codexSubscriptionUsageModelKey(pricingModel)
: codexApiUsageModelKey(pricingModel);
@@ -3562,24 +3598,41 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
});
};
try {
- const pricing = isSubscriptionValue && !isCodexXaiProviderRoute
+ const pricing = isSubscriptionValue
? await getModelPricing()
: hasEffectiveGatewayRoute
? await getModelPricingForModel('xd', pricingModel)
- : null;
+ : usesReferencePriceEstimate
+ ? await getModelPricing()
+ : null;
+ // 订阅估值按显式来源取各自的日期定价路由:内置 anthropic 走 Anthropic
+ // registry 参考价(含 codex 侧价格覆盖),默认/openai 保持 OpenAI 价表。
+ const subscriptionValueProviderId =
+ isCodexSubscriptionAccessRoute && sessionProvider != null
+ ? sessionProvider
+ : 'openai';
const price = isCodexXaiProviderRoute
- ? getSubscriptionDirectValuePrice(pricingModel)
+ ? getSubscriptionDirectValuePrice(pricingModel, 'codex', pricing)
: isSubscriptionValue
- ? getCodexSubscriptionValuePrice(pricingModel, pricing)
+ ? getCodexProviderSubscriptionValuePrice(
+ subscriptionValueProviderId,
+ pricingModel,
+ pricing,
+ )
: hasEffectiveGatewayRoute
? getModelPriceQuote(pricing, 'xd', pricingModel)
- : undefined;
+ : usesReferencePriceEstimate
+ ? getModelPriceQuote(pricing, sessionProvider, pricingModel, 'codex')
+ : undefined;
const money = computePriceQuoteTurnMoney(
codexUsageToTokens(u),
price ?? undefined,
currentLedgerCurrency(),
);
- if (!isSubscriptionValue && money) {
+ // Only Gateway sale prices are actual API spend. Third-party/user reference quotes
+ // are value estimates and daily_model_usage cannot preserve RegionalMoney.kind, so
+ // writing them into #billing=api would later reconstruct an estimate as actual cost.
+ if (!isSubscriptionValue && money && price?.source === 'gateway') {
await recordModelTurnUsage({
agentKind: 'codex',
model: modelUsageKey,
@@ -3591,7 +3644,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
});
}
if (money && money.amount > 0) {
- if (!isSubscriptionValue) {
+ const isActualApiCost = !isSubscriptionValue && price?.source === 'gateway';
+ if (isActualApiCost) {
void recordTurnSpend(money);
void recordSessionTurnSpend(session.id, money);
}
@@ -4080,6 +4134,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
configureProviderModelAutoRefresh({
listProviders: (opts) => getDesktopProviderService().listProviders(opts),
getScopeKey: () => getActiveAppSession().generation,
+ refreshCatalog: async () => {
+ await refreshActiveCatalogFromSource();
+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
+ },
refreshProvider: (providerId) =>
refreshBuiltinProviderModels(providerId, {
refreshXd: options.refreshXdGatewayModels,
@@ -4090,6 +4148,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
),
refreshXaiCatalog: async () => {
await refreshActiveCatalogFromSource();
+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
},
}),
});
@@ -4131,6 +4190,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 停用写入的归属校验:入口捕获 / 持久化前复核,异步窗口内切账号即拒,防 A 的
// 点击写进 B 的 owner-scoped 偏好文件(PR #744 review 第七轮)。
currentOwnerId: () => getCurrentDataOwnerId(),
+ getLedgerCurrency: currentLedgerCurrency,
+ readModelPriceOverride: (target) =>
+ readModelPriceOverrideView(target, getActiveCatalog().modelRegistry),
+ writeModelPriceOverride: (target, desired) =>
+ setModelPriceOverride(target, desired, getActiveCatalog().modelRegistry),
+ clearModelPriceOverride,
+ stageClearProviderModelPriceOverrides: stageProviderModelPriceOverridesClear,
+ broadcastPricingChanged: broadcastEffectiveModelPricing,
// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现
// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。
oauthLogin: async (providerId, isCurrent) => {
diff --git a/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts b/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts
index b5d3ff8a00..a7ac4df172 100644
--- a/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts
@@ -1,11 +1,12 @@
/**
- * devMetaOverlay 单测 —— dev 本地 cindyModelMeta 覆盖服务端网关模型元数据的
- * 合并语义(与服务端 listGatewayChatModels 对齐):同 id 覆盖、null 撤销、
- * 网关权威字段保留、非法信封/条目保留服务端原值。纯函数,不碰 Electron。
+ * Dev ModelRegistry overlay contract: live Gateway membership and prices stay
+ * authoritative while the local registry can replace curated metadata.
*/
import { describe, expect, it, vi } from 'vitest';
-import { overlayCindyModelMeta } from '../devMetaOverlay.js';
+import type { ModelRegistry, ModelRegistryEntry } from '@cindy/model-providers';
+
+import { overlayModelRegistryMeta } from '../devMetaOverlay.js';
import type { ModelAccessGatewayModel } from '../../../shared/modelAccess.js';
const SERVER_MODEL: ModelAccessGatewayModel = {
@@ -21,27 +22,35 @@ const SERVER_MODEL: ModelAccessGatewayModel = {
supportsFastMode: true,
};
-const LOCAL_ENTRY = {
- agents: ['codex'],
+const LOCAL_ENTRY: ModelRegistryEntry = {
+ id: 'openai/gpt-5.5',
name: 'GPT-5.5(local)',
group: 'gpt-local',
contextWindow: 999_000,
+ maxOutputTokens: 64_000,
efforts: ['low', 'high', 'xhigh'],
defaultEffort: 'xhigh',
sortOrder: 3,
supportsFastMode: false,
defaultEnabled: false,
perAgent: { codex: { supportsFastMode: true } },
+ routes: [{ providerId: 'xd', modelId: 'gpt-5.5', agents: ['codex'] }],
};
-const envelope = (models: Record<string, unknown>) => ({ version: 1, models });
+function registry(...entries: ModelRegistryEntry[]): ModelRegistry {
+ return {
+ schemaVersion: 1,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models: entries,
+ };
+}
-describe('overlayCindyModelMeta', () => {
- it('同 id 条目整体替换元数据;网关上报的 contextWindow/maxOutputTokens 权威保留', () => {
- const [m] = overlayCindyModelMeta([SERVER_MODEL], envelope({ 'gpt-5.5': LOCAL_ENTRY }));
- expect(m).toMatchObject({
+describe('overlayModelRegistryMeta', () => {
+ it('同 id 路由整体替换元数据;Gateway 上报的窗口和输出上限保持权威', () => {
+ const [model] = overlayModelRegistryMeta([SERVER_MODEL], registry(LOCAL_ENTRY));
+ expect(model).toMatchObject({
id: 'gpt-5.5',
- contextWindow: 272_000, // 网关权威,本地 999_000 不生效
+ contextWindow: 272_000,
maxOutputTokens: 32_000,
agents: ['codex'],
name: 'GPT-5.5(local)',
@@ -55,13 +64,18 @@ describe('overlayCindyModelMeta', () => {
});
});
- it('服务端条目没有 contextWindow 时才用本地值兜底(同服务端规则)', () => {
- const noCtx: ModelAccessGatewayModel = { id: 'gpt-5.5', name: 'x', agents: ['claude-code'] };
- const [m] = overlayCindyModelMeta([noCtx], envelope({ 'gpt-5.5': LOCAL_ENTRY }));
- expect(m.contextWindow).toBe(999_000);
+ it('Gateway 未提供窗口或输出上限时才用 registry 兜底', () => {
+ const live: ModelAccessGatewayModel = {
+ id: 'gpt-5.5',
+ name: 'x',
+ agents: ['claude-code'],
+ };
+ const [model] = overlayModelRegistryMeta([live], registry(LOCAL_ENTRY));
+ expect(model.contextWindow).toBe(999_000);
+ expect(model.maxOutputTokens).toBe(64_000);
});
- it('本地元数据覆盖和撤销都保留 Gateway 价格字段', () => {
+ it('元数据覆盖和 retired 路由都保留 Gateway 价格字段', () => {
const priced: ModelAccessGatewayModel = {
...SERVER_MODEL,
costDiscount: 0.2,
@@ -75,16 +89,13 @@ describe('overlayCindyModelMeta', () => {
},
],
};
- const [overridden] = overlayCindyModelMeta(
- [priced],
- envelope({ 'gpt-5.5': LOCAL_ENTRY }),
- );
- const [revoked] = overlayCindyModelMeta(
+ const [overridden] = overlayModelRegistryMeta([priced], registry(LOCAL_ENTRY));
+ const [retired] = overlayModelRegistryMeta(
[priced],
- envelope({ 'gpt-5.5': null }),
+ registry({ ...LOCAL_ENTRY, status: 'retired' }),
);
- for (const model of [overridden, revoked]) {
+ for (const model of [overridden, retired]) {
expect(model).toMatchObject({
costDiscount: 0.2,
inputCostPerToken: 0.000003,
@@ -98,77 +109,38 @@ describe('overlayCindyModelMeta', () => {
],
});
}
+ expect(retired).toEqual({
+ id: 'gpt-5.5',
+ contextWindow: 272_000,
+ maxOutputTokens: 32_000,
+ costDiscount: 0.2,
+ inputCostPerToken: 0.000003,
+ outputCostPerToken: 0.000015,
+ tieredPricing: [
+ {
+ range: [0, 200_000],
+ inputCostPerToken: 0.000003,
+ outputCostPerToken: 0.000015,
+ },
+ ],
+ });
});
- it('icon(展示图标)可经本地条目覆盖 / 撤销:字符串透传,非字符串条目整条拒绝', () => {
- const [withIcon] = overlayCindyModelMeta(
- [SERVER_MODEL],
- envelope({ 'gpt-5.5': { ...LOCAL_ENTRY, icon: 'codex' } }),
- );
- expect(withIcon.icon).toBe('codex');
- // 本地条目未带 icon → 覆盖后的条目也不带(整体替换语义,服务端 icon 不残留)。
- const serverWithIcon: ModelAccessGatewayModel = { ...SERVER_MODEL, icon: 'claude' };
- const [replaced] = overlayCindyModelMeta(
- [serverWithIcon],
- envelope({ 'gpt-5.5': LOCAL_ENTRY }),
- );
- expect('icon' in replaced).toBe(false);
- const warn = vi.fn();
- const [kept] = overlayCindyModelMeta(
- [serverWithIcon],
- envelope({ 'gpt-5.5': { ...LOCAL_ENTRY, icon: 42 } }),
- { warn, info: vi.fn() },
- );
- expect(kept.icon).toBe('claude'); // 非法条目跳过,保留服务端原值
- expect(warn).toHaveBeenCalled();
- });
-
- it('null = 撤销登记:剥掉全部元数据只留网关权威字段', () => {
- const [m] = overlayCindyModelMeta([SERVER_MODEL], envelope({ 'gpt-5.5': null }));
- expect(m).toEqual({ id: 'gpt-5.5', contextWindow: 272_000, maxOutputTokens: 32_000 });
- });
-
- it('本地表没有的 id 原样保留;本地多出的 id 不会凭空进清单', () => {
- const out = overlayCindyModelMeta([SERVER_MODEL], envelope({ 'other-model': LOCAL_ENTRY }));
+ it('无 XD 路由不会覆盖,也不会凭 registry 增加可用模型', () => {
+ const officialOnly: ModelRegistryEntry = {
+ ...LOCAL_ENTRY,
+ routes: [{ providerId: 'openai', modelId: 'gpt-5.5', agents: ['codex'] }],
+ };
+ const out = overlayModelRegistryMeta([SERVER_MODEL], registry(officialOnly));
expect(out).toEqual([SERVER_MODEL]);
expect(out).toHaveLength(1);
});
- it('信封非法(缺 version / models 非对象 / undefined)原样返回不炸', () => {
- for (const bad of [undefined, null, 42, { models: {} }, { version: 2, models: {} }, { version: 1, models: [] }]) {
- expect(overlayCindyModelMeta([SERVER_MODEL], bad)).toEqual([SERVER_MODEL]);
- }
- });
-
- it('单条目非法只跳过该条(warn)保留服务端原值,其余照常覆盖', () => {
- const other: ModelAccessGatewayModel = { id: 'm2', name: 'M2', agents: ['claude-code'] };
- const warn = vi.fn();
- const out = overlayCindyModelMeta(
- [SERVER_MODEL, other],
- envelope({
- 'gpt-5.5': { ...LOCAL_ENTRY, agents: ['browser'] }, // 非法 agent
- m2: { agents: ['claude-code'], name: 'M2(local)' },
- }),
- { warn, info: vi.fn() },
- );
- expect(out[0]).toEqual(SERVER_MODEL);
- expect(out[1]).toMatchObject({ id: 'm2', name: 'M2(local)' });
- expect(warn).toHaveBeenCalledTimes(1);
- });
-
- it('efforts 显式空数组(不可调)被尊重透传', () => {
- const [m] = overlayCindyModelMeta(
- [SERVER_MODEL],
- envelope({
- 'gpt-5.5': {
- agents: ['claude-code'],
- name: 'X',
- efforts: [],
- defaultEffort: null,
- },
- }),
- );
- expect(m.efforts).toEqual([]);
- expect(m.defaultEffort).toBeNull();
+ it('缺少 registry 时原样返回且不产生日志', () => {
+ const info = vi.fn();
+ expect(overlayModelRegistryMeta([SERVER_MODEL], undefined, { info, warn: vi.fn() })).toEqual([
+ SERVER_MODEL,
+ ]);
+ expect(info).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/model-access/devMetaOverlay.ts b/apps/desktop/src/main/model-access/devMetaOverlay.ts
index 0c50268dc6..ee54c29850 100644
--- a/apps/desktop/src/main/model-access/devMetaOverlay.ts
+++ b/apps/desktop/src/main/model-access/devMetaOverlay.ts
@@ -1,65 +1,33 @@
/**
- * devMetaOverlay —— dev 模式下用本地目录文件的 `cindyModelMeta` 段覆盖服务端
- * 下发的 XD 网关模型元数据。
- * ---------------------------------------------------------------------------
- * 背景:XD 模型的产品元数据权威在服务端(model-access-server 内置基线 + OSS
- * `cfg/providers.json` 顶层 `cindyModelMeta` 远程覆盖表,GET /models 合并下发)。
- * 改元数据要「发 OSS → 等服务端热加载」,dev 自测太重。本模块让 dev 环境像
- * providers.json 的其它段一样直接吃本地文件:改仓内
- * `packages/model-providers/catalog/providers.json` 的 cindyModelMeta → 重启
- * dev 实例即可在 Cindy AI 模型列表看到效果。**packaged 一律不走本覆盖**
- * (调用点用 isDev() 门控,见 model-access/index.ts applyGatewayModels)。
+ * Dev-only projection of the local public ModelRegistry onto the XD Gateway's
+ * live model list.
*
- * 合并语义与服务端 listGatewayChatModels 逐条对齐(服务端仓
- * services/modelAccess.ts):
- * - **只覆盖服务端清单里已存在的 id**——清单成员资格仍由网关证明可用性,
- * 本地表多出的 id 不会凭空出现在列表里;
- * - contextWindow / maxOutputTokens 网关上报权威:保留服务端条目的值,本地
- * entry.contextWindow 仅在服务端条目没有时兜底(与服务端规则一致)。注意
- * wire 上无法区分服务端条目的 contextWindow 是网关上报还是服务端元数据表
- * 兜底——若网关未报而服务端表补了值,本地改 contextWindow 不会生效(服务端
- * 值粘住),这是 dev 覆盖的固有限制,不是 bug;
- * - 其余展示元数据(agents/name/group/description/efforts/defaultEffort/
- * sortOrder/supportsFastMode/defaultEnabled/perAgent)整体以本地条目为准,
- * 替换服务端下发的对应字段(模拟「服务端远程表登记了该条目」的下发结果);
- * - 条目为 null = 撤销登记:剥掉全部元数据只留网关权威字段,客户端回落
- * 确定性默认(见 active-catalog computeMerged 的 xd 重建);
- * - 信封 / 条目非法:整份或单条跳过并 warn,保留服务端原值——dev 工具绝不
- * 让坏数据把列表弄坏,校验规则镜像服务端 modelMetadataSource parseEntry。
+ * Availability and prices remain Gateway-authoritative: registry entries only
+ * enrich ids that the server already returned. A retired XD route removes the
+ * curated metadata and lets downstream deterministic defaults apply. Packaged
+ * builds never call this function.
*/
+import type {
+ ModelRegistry,
+ ModelRegistryEntry,
+ ModelRegistryRoute,
+} from '@cindy/model-providers';
+
import type {
ModelAccessAgentOverride,
ModelAccessGatewayModel,
} from '../../shared/modelAccess.js';
-type Agent = 'claude-code' | 'codex';
-
-const VALID_AGENTS: ReadonlySet<string> = new Set(['claude-code', 'codex']);
-/** 与服务端 modelMetadataSource / active-catalog 同一套 effort 口径。 */
-const VALID_EFFORTS: ReadonlySet<string> = new Set([
- 'minimal',
- 'low',
- 'medium',
- 'high',
- 'xhigh',
- 'max',
- 'ultra',
-]);
-
/** 覆盖日志回调(生产接统一 logger;测试可缺省)。 */
export interface OverlayLog {
warn(msg: string, meta?: Record<string, unknown>): void;
info(msg: string, meta?: Record<string, unknown>): void;
}
-function isPlainObject(v: unknown): v is Record<string, unknown> {
- return typeof v === 'object' && v !== null && !Array.isArray(v);
-}
-
/**
- * 去掉可由 dev 元数据覆盖的展示、归属和能力字段,保留 token 上限和全部
- * Gateway 价格。这样本地 overlay 或 null 撤销登记都不会把同快照里的价格静默丢掉。
+ * 去掉可由 registry 覆盖的展示、归属和能力字段,保留 token 上限和全部
+ * Gateway 价格。这样本地 overlay 或 retired 路由都不会把同快照里的价格静默丢掉。
*/
function gatewayFields(m: ModelAccessGatewayModel): ModelAccessGatewayModel {
const fields = { ...m };
@@ -67,7 +35,6 @@ function gatewayFields(m: ModelAccessGatewayModel): ModelAccessGatewayModel {
delete fields.name;
delete fields.group;
delete fields.description;
- delete fields.icon;
delete fields.efforts;
delete fields.defaultEffort;
delete fields.sortOrder;
@@ -77,151 +44,81 @@ function gatewayFields(m: ModelAccessGatewayModel): ModelAccessGatewayModel {
return fields;
}
-/** 校验并拷贝 override 形态的能力字段(基线与 perAgent 共用);非法返回原因。 */
-function readOverrideFields(
- o: Record<string, unknown>,
- out: ModelAccessAgentOverride,
-): string | null {
- if (o.contextWindow !== undefined) {
- if (typeof o.contextWindow !== 'number' || !Number.isFinite(o.contextWindow) || o.contextWindow <= 0) {
- return 'contextWindow 必须是正数';
- }
- out.contextWindow = o.contextWindow;
- }
- if (o.efforts !== undefined) {
- if (!Array.isArray(o.efforts) || o.efforts.some((e) => typeof e !== 'string' || !VALID_EFFORTS.has(e))) {
- return `efforts 只允许 ${[...VALID_EFFORTS].join('/')}`;
- }
- out.efforts = o.efforts as string[];
- }
- if (o.defaultEffort !== undefined) {
- if (
- o.defaultEffort !== null &&
- (typeof o.defaultEffort !== 'string' || !VALID_EFFORTS.has(o.defaultEffort))
- ) {
- return 'defaultEffort 非法';
- }
- out.defaultEffort = o.defaultEffort as string | null;
- }
- if (o.supportsFastMode !== undefined) {
- if (typeof o.supportsFastMode !== 'boolean') return 'supportsFastMode 必须是布尔';
- out.supportsFastMode = o.supportsFastMode;
- }
- if (o.defaultEnabled !== undefined) {
- if (typeof o.defaultEnabled !== 'boolean') return 'defaultEnabled 必须是布尔';
- out.defaultEnabled = o.defaultEnabled;
- }
- return null;
-}
-
-/** 元数据条目(不含 id)——ModelAccessGatewayModel 去掉网关权威字段的形态。 */
-type MetaEntry = Omit<ModelAccessGatewayModel, 'id' | 'maxOutputTokens'>;
-
-/** 解析单个本地元数据条目;非法返回原因字符串(镜像服务端 parseEntry 规则)。 */
-function parseEntry(raw: unknown): { meta: MetaEntry } | { reason: string } {
- if (!isPlainObject(raw)) return { reason: '条目必须是对象或 null' };
- if (
- !Array.isArray(raw.agents) ||
- raw.agents.length === 0 ||
- raw.agents.some((a) => typeof a !== 'string' || !VALID_AGENTS.has(a))
- ) {
- return { reason: 'agents 必须是非空数组,取值 claude-code/codex' };
- }
- if (typeof raw.name !== 'string' || !raw.name.trim()) return { reason: 'name 必须是非空字符串' };
-
- const meta: MetaEntry = { agents: raw.agents as Agent[], name: raw.name };
- for (const k of ['group', 'description', 'icon'] as const) {
- if (raw[k] !== undefined) {
- if (typeof raw[k] !== 'string') return { reason: `${k} 必须是字符串` };
- meta[k] = raw[k] as string;
- }
- }
- if (raw.sortOrder !== undefined) {
- if (typeof raw.sortOrder !== 'number' || !Number.isFinite(raw.sortOrder)) {
- return { reason: 'sortOrder 必须是数字' };
- }
- meta.sortOrder = raw.sortOrder;
+function findXdRoute(
+ registry: ModelRegistry,
+ modelId: string,
+): { entry: ModelRegistryEntry; route: ModelRegistryRoute } | undefined {
+ for (const entry of registry.models) {
+ const route = entry.routes.find(
+ (candidate) => candidate.providerId === 'xd' && candidate.modelId === modelId,
+ );
+ if (route) return { entry, route };
}
- const baseErr = readOverrideFields(raw, meta);
- if (baseErr) return { reason: baseErr };
-
- if (raw.perAgent !== undefined) {
- if (!isPlainObject(raw.perAgent)) return { reason: 'perAgent 必须是对象' };
- const perAgent: Partial<Record<Agent, ModelAccessAgentOverride>> = {};
- for (const [agent, ov] of Object.entries(raw.perAgent)) {
- if (!VALID_AGENTS.has(agent)) return { reason: `perAgent 键非法: ${agent}` };
- if (!isPlainObject(ov)) return { reason: `perAgent.${agent} 必须是对象` };
- const parsed: ModelAccessAgentOverride = {};
- const err = readOverrideFields(ov, parsed);
- if (err) return { reason: `perAgent.${agent}: ${err}` };
- perAgent[agent as Agent] = parsed;
- }
- meta.perAgent = perAgent;
- }
- return { meta };
+ return undefined;
}
-/** 以本地条目重建服务端下发条目(网关权威字段保留,元数据字段整体替换)。 */
-function rebuildModel(m: ModelAccessGatewayModel, meta: MetaEntry): ModelAccessGatewayModel {
+/** 以 registry 条目重建服务端下发条目(Gateway 权威字段保留,策展元数据整体替换)。 */
+function rebuildModel(
+ model: ModelAccessGatewayModel,
+ entry: ModelRegistryEntry,
+ route: ModelRegistryRoute,
+): ModelAccessGatewayModel {
return {
- ...gatewayFields(m),
- // 网关上报的 token 上限权威;本地 contextWindow 仅在服务端条目缺失时兜底(同服务端规则)。
- ...(m.contextWindow === undefined && meta.contextWindow !== undefined
- ? { contextWindow: meta.contextWindow }
+ ...gatewayFields(model),
+ // Gateway 上报的 token 上限权威;registry 仅在服务端条目缺失时兜底。
+ ...(model.contextWindow === undefined && entry.contextWindow !== undefined
+ ? { contextWindow: entry.contextWindow }
+ : {}),
+ ...(model.maxOutputTokens === undefined && entry.maxOutputTokens !== undefined
+ ? { maxOutputTokens: entry.maxOutputTokens }
+ : {}),
+ agents: route.agents,
+ name: entry.name,
+ ...(entry.group ? { group: entry.group } : {}),
+ ...(entry.description ? { description: entry.description } : {}),
+ ...(entry.efforts ? { efforts: entry.efforts } : {}),
+ ...(entry.defaultEffort !== undefined ? { defaultEffort: entry.defaultEffort } : {}),
+ ...(entry.sortOrder !== undefined ? { sortOrder: entry.sortOrder } : {}),
+ ...(entry.supportsFastMode !== undefined ? { supportsFastMode: entry.supportsFastMode } : {}),
+ ...(entry.defaultEnabled !== undefined ? { defaultEnabled: entry.defaultEnabled } : {}),
+ ...(entry.perAgent
+ ? {
+ perAgent: entry.perAgent as Partial<
+ Record<'claude-code' | 'codex', ModelAccessAgentOverride>
+ >,
+ }
: {}),
- agents: meta.agents,
- name: meta.name,
- ...(meta.group ? { group: meta.group } : {}),
- ...(meta.description ? { description: meta.description } : {}),
- ...(meta.icon ? { icon: meta.icon } : {}),
- ...(meta.efforts ? { efforts: meta.efforts } : {}),
- ...(meta.defaultEffort !== undefined ? { defaultEffort: meta.defaultEffort } : {}),
- ...(meta.sortOrder !== undefined ? { sortOrder: meta.sortOrder } : {}),
- ...(meta.supportsFastMode !== undefined ? { supportsFastMode: meta.supportsFastMode } : {}),
- ...(meta.defaultEnabled !== undefined ? { defaultEnabled: meta.defaultEnabled } : {}),
- ...(meta.perAgent ? { perAgent: meta.perAgent } : {}),
};
}
/**
- * 用本地 cindyModelMeta 信封覆盖服务端下发的网关模型清单(纯函数)。
- * 信封非法 → 原样返回;条目非法 → 跳过该条保留服务端原值(warn)。
+ * 用本地 ModelRegistry 的 XD 路由覆盖服务端下发的网关模型清单(纯函数)。
+ * 本地无 registry / 无匹配路由 → 原样返回;不会凭 registry 增加可用模型。
*/
-export function overlayCindyModelMeta(
+export function overlayModelRegistryMeta(
models: ModelAccessGatewayModel[],
- envelope: unknown,
+ registry: ModelRegistry | undefined,
log?: OverlayLog,
): ModelAccessGatewayModel[] {
- if (!isPlainObject(envelope) || envelope.version !== 1 || !isPlainObject(envelope.models)) {
- if (envelope !== undefined) {
- log?.warn('local cindyModelMeta envelope invalid; dev overlay skipped');
- }
- return models;
- }
- const table = envelope.models;
+ if (!registry) return models;
let overridden = 0;
- let revoked = 0;
- const out = models.map((m) => {
- if (!Object.hasOwn(table, m.id)) return m; // hasOwn:防模型 id 撞原型链属性(toString 等)
- const raw = table[m.id];
- if (raw === null) {
- // 撤销登记:剥掉全部元数据,只留网关权威字段(客户端回落确定性默认)。
- revoked += 1;
- return gatewayFields(m);
- }
- const parsed = parseEntry(raw);
- if ('reason' in parsed) {
- log?.warn('local cindyModelMeta entry invalid; keeping server value', {
- id: m.id,
- reason: parsed.reason,
- });
- return m;
+ let retired = 0;
+ const out = models.map((model) => {
+ const matched = findXdRoute(registry, model.id);
+ if (!matched) return model;
+ if (matched.entry.status === 'retired') {
+ retired += 1;
+ return gatewayFields(model);
}
overridden += 1;
- return rebuildModel(m, parsed.meta);
+ return rebuildModel(model, matched.entry, matched.route);
});
- if (overridden > 0 || revoked > 0) {
- log?.info('dev cindyModelMeta overlay applied', { overridden, revoked, total: models.length });
+ if (overridden > 0 || retired > 0) {
+ log?.info('dev modelRegistry overlay applied', {
+ overridden,
+ retired,
+ total: models.length,
+ });
}
return out;
}
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index 128af960df..ca4a120c26 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -13,7 +13,7 @@ import {
} from '../maker-host/index.js';
import { getActiveCatalog, setXdGatewayModels } from '../maker-host/active-catalog.js';
import { isDev } from '../manifestService.js';
-import { overlayCindyModelMeta } from './devMetaOverlay.js';
+import { overlayModelRegistryMeta } from './devMetaOverlay.js';
import {
replaceGatewayModelPricing,
trackGatewayModelPricingSync,
@@ -168,12 +168,11 @@ function applyGatewayModels(
`xd gateway pricing quotes cover ${quoteCount}/${pricedCount} priced models (${models.length} total)`,
);
}
- // dev:本地目录文件(catalog/providers.json)的 cindyModelMeta 段覆盖服务端下发的
- // 元数据,改本地 json + 重启即可自测,无需发 OSS / 等服务端热加载;只覆盖同 id,
- // 清单成员资格仍以网关为准。packaged 不走此分支(语义见 devMetaOverlay.ts)。
+ // dev:本地统一 registry 的 XD 路由覆盖服务端下发的策展元数据;只覆盖同 id,
+ // 清单成员资格与价格仍以 Gateway 为准。packaged 不走此分支。
const overlaid =
isDev() && models.length > 0
- ? overlayCindyModelMeta(models, getActiveCatalog().cindyModelMeta, log)
+ ? overlayModelRegistryMeta(models, getActiveCatalog().modelRegistry, log)
: models;
// 能力字段不在客户端二次转换 —— Model Access Server 已把 Gateway 的
// contextLength / supportedEndpoints / reasoning / supportsServiceTier / architecture
diff --git a/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts b/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts
new file mode 100644
index 0000000000..d58b8e8757
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts
@@ -0,0 +1,392 @@
+import { describe, expect, it } from 'vitest';
+
+import { __testing } from '../modelPriceOverrideStore';
+
+describe('model price override sparse persistence', () => {
+ it('keys overrides by provider instance, runtime, and exact model id', () => {
+ expect(
+ __testing.overrideKey({
+ providerId: 'custom-a',
+ agent: 'codex',
+ modelId: 'same-model',
+ }),
+ ).not.toBe(
+ __testing.overrideKey({
+ providerId: 'custom-b',
+ agent: 'codex',
+ modelId: 'same-model',
+ }),
+ );
+ expect(
+ __testing.overrideKey({
+ providerId: 'custom-a',
+ agent: 'codex',
+ modelId: 'same-model',
+ }),
+ ).not.toBe(
+ __testing.overrideKey({
+ providerId: 'custom-a',
+ agent: 'claude-code',
+ modelId: 'same-model',
+ }),
+ );
+ });
+
+ it('stores only fields changed from the current remote reference', () => {
+ expect(
+ __testing.sparseValues(
+ {
+ currency: 'USD',
+ inputPerMtok: 2,
+ outputPerMtok: 8,
+ cacheReadPerMtok: null,
+ cacheCreatePerMtok: 2.5,
+ },
+ {
+ currency: 'USD',
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: 2.5,
+ },
+ ),
+ ).toEqual({
+ outputPerMtok: 8,
+ cacheReadPerMtok: null,
+ });
+ });
+
+ it('detects a later remote-price change against the saved base snapshot', () => {
+ const original = {
+ currency: 'USD' as const,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: null,
+ };
+ expect(__testing.sameComparable(original, { ...original })).toBe(true);
+ expect(
+ __testing.sameComparable(original, {
+ ...original,
+ outputPerMtok: 7,
+ }),
+ ).toBe(false);
+ expect(
+ __testing.sameComparable(original, {
+ ...original,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ },
+ ],
+ }),
+ ).toBe(false);
+ });
+
+ it('preserves remote long-context multipliers when applying a sparse local override', () => {
+ const inputTokenPriceBands = [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ },
+ ];
+ expect(
+ __testing.mergedQuote(
+ { providerId: 'custom', agent: 'codex', modelId: 'model' },
+ {
+ providerId: 'custom',
+ modelId: 'model',
+ currency: 'USD',
+ source: 'provider-reference',
+ approximate: true,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ inputTokenPriceBands,
+ },
+ { outputPerMtok: 8 },
+ ),
+ ).toMatchObject({
+ source: 'user-override',
+ outputPerMtok: 8,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 16,
+ },
+ ],
+ });
+ });
+
+ it('rewrites every inherited price when the user changes quote currency', () => {
+ const reference = {
+ currency: 'USD' as const,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: null,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ cacheReadPerMtok: 0.4,
+ },
+ ],
+ };
+ const values = __testing.sparseValues(
+ {
+ currency: 'CNY',
+ inputPerMtok: 3,
+ outputPerMtok: 9,
+ cacheReadPerMtok: 0.3,
+ cacheCreatePerMtok: null,
+ },
+ reference,
+ );
+ expect(values).toEqual({
+ currency: 'CNY',
+ inputPerMtok: 3,
+ outputPerMtok: 9,
+ cacheReadPerMtok: 0.3,
+ cacheCreatePerMtok: null,
+ });
+ expect(
+ __testing.mergedQuote(
+ { providerId: 'custom', agent: 'codex', modelId: 'model' },
+ {
+ providerId: 'custom',
+ modelId: 'model',
+ source: 'provider-reference',
+ approximate: true,
+ currency: reference.currency,
+ inputPerMtok: reference.inputPerMtok,
+ outputPerMtok: reference.outputPerMtok,
+ cacheReadPerMtok: reference.cacheReadPerMtok,
+ inputTokenPriceBands: reference.inputTokenPriceBands,
+ },
+ values,
+ ),
+ ).toMatchObject({
+ currency: 'CNY',
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 6,
+ outputPerMtok: 18,
+ cacheReadPerMtok: 0.6,
+ },
+ ],
+ });
+ });
+
+ it('keeps sparse numeric overrides in their saved base currency after a remote currency change', () => {
+ const savedBase = {
+ currency: 'USD' as const,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: null,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ },
+ ],
+ };
+ expect(
+ __testing.mergedQuote(
+ { providerId: 'custom', agent: 'codex', modelId: 'model' },
+ {
+ providerId: 'custom',
+ modelId: 'model',
+ source: 'provider-reference',
+ approximate: true,
+ currency: 'CNY',
+ inputPerMtok: 1,
+ outputPerMtok: 3,
+ },
+ { inputPerMtok: 4 },
+ savedBase,
+ ),
+ ).toMatchObject({
+ currency: 'USD',
+ inputPerMtok: 4,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 8,
+ outputPerMtok: 12,
+ },
+ ],
+ });
+ });
+
+ it('re-anchors saved long-context bands when a same-currency remote update drops them', () => {
+ const savedBase = {
+ currency: 'USD' as const,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: null,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ },
+ ],
+ };
+ const merged = __testing.mergedQuote(
+ { providerId: 'custom', agent: 'codex', modelId: 'model' },
+ {
+ providerId: 'custom',
+ modelId: 'model',
+ source: 'provider-reference',
+ approximate: true,
+ currency: 'USD',
+ inputPerMtok: 3,
+ outputPerMtok: 9,
+ cacheReadPerMtok: 0.3,
+ },
+ { inputPerMtok: 4 },
+ savedBase,
+ );
+ // 未覆盖的基础价跟随远端;分段价保留保存基底的相对倍率(输入 2×、输出 2×),
+ // 锚回远端新基础价后再按覆盖投影:输入档 2×4=8,输出档 2×9=18。
+ expect(merged).toMatchObject({
+ source: 'user-override',
+ currency: 'USD',
+ inputPerMtok: 4,
+ outputPerMtok: 9,
+ cacheReadPerMtok: 0.3,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 8,
+ outputPerMtok: 18,
+ },
+ ],
+ });
+ });
+
+ it('follows a same-currency remote update that keeps its long-context bands', () => {
+ const savedBase = {
+ currency: 'USD' as const,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: null,
+ cacheCreatePerMtok: null,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ },
+ ],
+ };
+ expect(
+ __testing.mergedQuote(
+ { providerId: 'custom', agent: 'codex', modelId: 'model' },
+ {
+ providerId: 'custom',
+ modelId: 'model',
+ source: 'provider-reference',
+ approximate: true,
+ currency: 'USD',
+ inputPerMtok: 3,
+ outputPerMtok: 9,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 6,
+ outputPerMtok: 18,
+ },
+ ],
+ },
+ { inputPerMtok: 4 },
+ savedBase,
+ ),
+ ).toMatchObject({
+ source: 'user-override',
+ currency: 'USD',
+ inputPerMtok: 4,
+ outputPerMtok: 9,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 8,
+ outputPerMtok: 18,
+ },
+ ],
+ });
+ });
+
+ it('keeps sparse overrides when the remote reference price disappears', () => {
+ const savedBase = {
+ currency: 'USD' as const,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: null,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ },
+ ],
+ };
+ expect(
+ __testing.mergedQuote(
+ { providerId: 'custom', agent: 'codex', modelId: 'model' },
+ undefined,
+ { inputPerMtok: 4 },
+ savedBase,
+ ),
+ ).toMatchObject({
+ source: 'user-override',
+ currency: 'USD',
+ inputPerMtok: 4,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.2,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 8,
+ outputPerMtok: 12,
+ },
+ ],
+ });
+ });
+
+ it('only accepts currencies that can project into the active ledger', () => {
+ expect(__testing.currencyCanProjectToLedger('USD', 'USD')).toBe(true);
+ expect(__testing.currencyCanProjectToLedger('USD', 'CNY')).toBe(true);
+ expect(__testing.currencyCanProjectToLedger('CNY', 'CNY')).toBe(true);
+ expect(__testing.currencyCanProjectToLedger('CNY', 'USD')).toBe(false);
+ });
+
+ it('drops malformed records instead of accepting poisoned local state', () => {
+ expect(
+ __testing.normalize({
+ entries: {
+ bad: {
+ providerId: 'custom',
+ agent: 'codex',
+ modelId: 'm',
+ values: { inputPerMtok: -1 },
+ baseReference: null,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ },
+ },
+ }),
+ ).toEqual({ version: 1, entries: {} });
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index 1f4eed424c..429420eb9c 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -54,7 +54,15 @@ vi.mock('../../secrets/providerSecretStore', () => ({
}));
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
+import { providerReferencePriceQuote } from '../../../shared/modelPriceQuote';
import { DEFAULT_USAGE_CURRENCY } from '../../../shared/regionalMoney';
+import { getActiveCatalog } from '../../maker-host/active-catalog';
+import {
+ applyModelPriceOverrides,
+ clearModelPriceOverride,
+ readModelPriceOverridesSnapshot,
+ setModelPriceOverride,
+} from '../modelPriceOverrideStore';
import {
__resetActiveLedgerCurrencyForTesting,
currentLedgerCurrency,
@@ -62,6 +70,8 @@ import {
import {
__resetModelPricingCacheForTesting,
clearGatewayModelPricing,
+ getClaudeSubscriptionValuePrice,
+ getCodexProviderSubscriptionValuePrice,
getCodexSubscriptionValuePrice,
getModelPricing,
getModelPricingForModel,
@@ -160,7 +170,37 @@ describe('gateway model pricing projection', () => {
},
},
});
- expect(mocks.send).toHaveBeenCalledWith(MODEL_PRICING_CHANGED_CHANNEL, pricing);
+ expect(mocks.send).toHaveBeenCalledWith(
+ MODEL_PRICING_CHANGED_CHANNEL,
+ expect.objectContaining(pricing),
+ );
+ });
+
+ it('preserves Gateway context-length tiers in the effective quote', () => {
+ const pricing = replaceGatewayModelPricing([
+ {
+ id: 'gpt-tiered',
+ inputCostPerToken: 0.000002,
+ outputCostPerToken: 0.000008,
+ tieredPricing: [
+ {
+ range: [200_001, 1_000_001],
+ inputCostPerToken: 0.000004,
+ outputCostPerToken: 0.000012,
+ cacheReadInputTokenCost: 0.0000004,
+ },
+ ],
+ },
+ ]);
+
+ const [band] = pricing?.xd?.['gpt-tiered']?.inputTokenPriceBands ?? [];
+ expect(band).toMatchObject({
+ minInputTokens: 200_001,
+ maxInputTokens: 1_000_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ });
+ expect(band?.cacheReadPerMtok).toBeCloseTo(0.4);
});
it('keeps legal zero tiers but drops missing, invalid and 0/0 standard prices', () => {
@@ -206,11 +246,14 @@ describe('gateway model pricing projection', () => {
expect(await getModelPricing()).not.toBeNull();
expect(replaceGatewayModelPricing([{ id: 'unpriced' }])).toEqual({});
- expect(await getModelPricing()).toEqual({});
- expect(mocks.send).toHaveBeenLastCalledWith(MODEL_PRICING_CHANGED_CHANNEL, {});
+ expect((await getModelPricing())?.xd).toBeUndefined();
+ expect(mocks.send).toHaveBeenLastCalledWith(
+ MODEL_PRICING_CHANGED_CHANNEL,
+ expect.objectContaining({ openai: expect.any(Object) }),
+ );
clearGatewayModelPricing();
- expect(await getModelPricing()).toEqual({});
+ expect((await getModelPricing())?.xd).toBeUndefined();
});
it('hydrates a successful empty pricing snapshot as loaded', async () => {
@@ -227,7 +270,10 @@ describe('gateway model pricing projection', () => {
});
__resetModelPricingCacheForTesting();
- await expect(getModelPricing()).resolves.toEqual({});
+ await expect(getModelPricing()).resolves.toMatchObject({
+ openai: expect.any(Object),
+ anthropic: expect.any(Object),
+ });
});
});
@@ -241,6 +287,13 @@ describe('pricing cache lifecycle', () => {
inputCostPerToken: 0.000005,
outputCostPerToken: 0.00003,
costDiscount: 0.2,
+ tieredPricing: [
+ {
+ range: [272_001, 1_000_001],
+ inputCostPerToken: 0.00001,
+ outputCostPerToken: 0.000045,
+ },
+ ],
},
]);
@@ -256,7 +309,7 @@ describe('pricing cache lifecycle', () => {
});
__resetModelPricingCacheForTesting();
- await expect(getModelPricing()).resolves.toEqual(pricing);
+ await expect(getModelPricing()).resolves.toMatchObject(pricing);
await prewarmModelPricing();
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -284,7 +337,10 @@ describe('pricing cache lifecycle', () => {
__resetActiveLedgerCurrencyForTesting();
expect(currentLedgerCurrency()).toBe(DEFAULT_USAGE_CURRENCY);
- await expect(getModelPricing()).resolves.toEqual({});
+ const hydrated = await getModelPricing();
+ // Gateway 报价为空,但统一 registry 的参考价仍属于有效价格目录。
+ expect(hydrated?.xd).toBeUndefined();
+ expect(hydrated?.openai).toBeDefined();
expect(currentLedgerCurrency()).toBe('USD');
expect(fetchMock).not.toHaveBeenCalled();
@@ -312,7 +368,7 @@ describe('pricing cache lifecycle', () => {
});
mocks.getCurrentDbClientUserId.mockReturnValue('user-a');
- await expect(getModelPricing()).resolves.toEqual(pricing);
+ await expect(getModelPricing()).resolves.toMatchObject(pricing);
});
it('does not hydrate another account pricing snapshot', async () => {
@@ -341,7 +397,9 @@ describe('pricing cache lifecycle', () => {
);
mocks.getCurrentDbClientUserId.mockReturnValue('user-b');
- await expect(getModelPricing()).resolves.toBeNull();
+ await expect(getModelPricing()).resolves.toMatchObject({
+ openai: expect.any(Object),
+ });
});
it('does not hydrate pricing written for an older gateway key identity', async () => {
@@ -367,7 +425,9 @@ describe('pricing cache lifecycle', () => {
ctimeNs: 7n,
});
- await expect(getModelPricing()).resolves.toBeNull();
+ await expect(getModelPricing()).resolves.toMatchObject({
+ openai: expect.any(Object),
+ });
});
it('rejects malformed or non-gateway disk quotes', async () => {
@@ -384,7 +444,7 @@ describe('pricing cache lifecycle', () => {
providerId: 'xd',
modelId: 'bad',
currency: 'USD',
- source: 'subscription-reference',
+ source: 'provider-reference',
approximate: true,
inputPerMtok: -1,
outputPerMtok: 2,
@@ -394,7 +454,9 @@ describe('pricing cache lifecycle', () => {
}),
'utf8',
);
- await expect(getModelPricing()).resolves.toBeNull();
+ await expect(getModelPricing()).resolves.toMatchObject({
+ openai: expect.any(Object),
+ });
});
it('requires provider identity on accounting lookups', async () => {
@@ -443,12 +505,38 @@ describe('pricing cache lifecycle', () => {
});
describe('reference pricing helpers', () => {
+ it('resolves historical subscription prices by their effective date', () => {
+ expect(
+ getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-08-31'),
+ ).toMatchObject({ inputPerMtok: 2, outputPerMtok: 10 });
+ expect(
+ getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-09-01'),
+ ).toMatchObject({ inputPerMtok: 3, outputPerMtok: 15 });
+ expect(
+ getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-06-29'),
+ ).toBeUndefined();
+ expect(
+ getClaudeSubscriptionValuePrice('sonnet', null, '2026-03-01'),
+ ).toMatchObject({ modelId: 'sonnet', inputPerMtok: 3, outputPerMtok: 15 });
+ expect(
+ getClaudeSubscriptionValuePrice(
+ 'claude-sonnet-4-6-20260701',
+ null,
+ '2026-08-01',
+ ),
+ ).toMatchObject({
+ modelId: 'claude-sonnet-4-6-20260701',
+ inputPerMtok: 3,
+ outputPerMtok: 15,
+ });
+ });
+
it('returns subscription reference quotes separately from the XD cache', () => {
expect(getCodexSubscriptionValuePrice('gpt-5.5', null)).toMatchObject({
providerId: 'openai',
modelId: 'gpt-5.5',
currency: 'USD',
- source: 'subscription-reference',
+ source: 'provider-reference',
approximate: true,
inputPerMtok: 5,
outputPerMtok: 30,
@@ -459,6 +547,83 @@ describe('reference pricing helpers', () => {
modelId: 'chatgpt/gpt-5.5',
source: 'subscription-reference',
});
+ expect(
+ getSubscriptionDirectValuePrice('chatgpt/gpt-5.5', 'claude-code', {
+ openai: {
+ 'gpt-5.5': {
+ providerId: 'openai',
+ modelId: 'gpt-5.5',
+ currency: 'USD',
+ source: 'user-override',
+ approximate: true,
+ inputPerMtok: 9,
+ outputPerMtok: 27,
+ },
+ },
+ }),
+ ).toMatchObject({
+ modelId: 'chatgpt/gpt-5.5',
+ source: 'user-override',
+ inputPerMtok: 9,
+ outputPerMtok: 27,
+ });
expect(getSubscriptionDirectValuePrice('unknown')).toBeUndefined();
});
+
+ it('prices Codex Anthropic subscription rounds through the anthropic date route', () => {
+ expect(
+ getCodexProviderSubscriptionValuePrice('anthropic', 'claude-sonnet-5', null, '2026-08-31'),
+ ).toMatchObject({ providerId: 'anthropic', inputPerMtok: 2, outputPerMtok: 10 });
+ expect(
+ getCodexProviderSubscriptionValuePrice('anthropic', 'claude-sonnet-5', null, '2026-09-01'),
+ ).toMatchObject({ inputPerMtok: 3, outputPerMtok: 15 });
+ });
+
+ it('re-merges sparse price overrides against the reference effective at the queried date', () => {
+ const registry = getActiveCatalog().modelRegistry;
+ const target = {
+ providerId: 'anthropic',
+ agent: 'claude-code',
+ modelId: 'claude-sonnet-5',
+ } as const;
+ const currentReference = providerReferencePriceQuote(
+ target.providerId,
+ target.modelId,
+ registry,
+ { agent: target.agent },
+ );
+ expect(currentReference).toBeDefined();
+ try {
+ // 只覆盖输入价:其余字段保持跟随参考价,形成稀疏 override。
+ setModelPriceOverride(
+ target,
+ {
+ currency: currentReference!.currency,
+ inputPerMtok: 2.5,
+ outputPerMtok: currentReference!.outputPerMtok,
+ cacheReadPerMtok: currentReference!.cacheReadPerMtok ?? null,
+ cacheCreatePerMtok: currentReference!.cacheCreatePerMtok ?? null,
+ },
+ registry,
+ );
+ const pricing = applyModelPriceOverrides({}, registry);
+ expect(
+ getClaudeSubscriptionValuePrice('claude-sonnet-5', pricing, '2026-08-31'),
+ ).toMatchObject({ source: 'user-override', inputPerMtok: 2.5, outputPerMtok: 10 });
+ expect(
+ getClaudeSubscriptionValuePrice('claude-sonnet-5', pricing, '2026-09-01'),
+ ).toMatchObject({ source: 'user-override', inputPerMtok: 2.5, outputPerMtok: 15 });
+ expect(getClaudeSubscriptionValuePrice('claude-sonnet-5', pricing)).toMatchObject({
+ source: 'user-override',
+ inputPerMtok: 2.5,
+ });
+ // 批量路径:传入一次性快照时结果一致,不逐行重读覆盖文件。
+ const snapshot = readModelPriceOverridesSnapshot();
+ expect(
+ getClaudeSubscriptionValuePrice('claude-sonnet-5', pricing, '2026-08-31', snapshot),
+ ).toMatchObject({ source: 'user-override', inputPerMtok: 2.5, outputPerMtok: 10 });
+ } finally {
+ clearModelPriceOverride(target);
+ }
+ });
});
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index 8fa54776b3..52c9af9299 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -6,7 +6,9 @@ import {
setActiveLedgerCurrency,
} from '../ledgerCurrency';
import {
+ billingRouteForExplicitProvider,
buildClaudeTurnUsageDetails,
+ computePriceQuoteTurnMoney,
computeGatewayTurnCost,
estimateClaudeSubscriptionTurnValue,
isAnthropicModel,
@@ -112,6 +114,16 @@ function resolvedModel(
}
describe('model id and route helpers', () => {
+ it('uses provider access semantics for explicit billing routes', () => {
+ expect(billingRouteForExplicitProvider('openai', 'subscription')).toBe('subscription');
+ expect(billingRouteForExplicitProvider('xai', 'subscription')).toBe('subscription');
+ expect(billingRouteForExplicitProvider('anthropic', undefined)).toBe('subscription');
+ expect(billingRouteForExplicitProvider('xd', 'managed')).toBe('xd-gateway');
+ expect(billingRouteForExplicitProvider('custom-api', 'api')).toBe('provider-api');
+ expect(billingRouteForExplicitProvider('custom-api', undefined)).toBe('provider-api');
+ expect(billingRouteForExplicitProvider(null, null)).toBeNull();
+ });
+
it('normalizes model suffixes without dropping provider prefixes', () => {
expect(normalizeModelIdForPricing('gpt-5.5[1m]')).toBe('gpt-5.5');
expect(normalizeModelIdForPricing('codex/gpt-5.5[1m]')).toBe('codex/gpt-5.5');
@@ -155,6 +167,102 @@ describe('computeGatewayTurnCost', () => {
),
).toBeCloseTo(12.7);
});
+
+ it('uses the matching context-length band for all token classes', () => {
+ expect(
+ computeGatewayTurnCost(
+ {
+ inputTokens: 210_000,
+ outputTokens: 10_000,
+ cacheReadTokens: 20_000,
+ cacheCreateTokens: 10_000,
+ },
+ quote('m', 2, 8, {
+ cacheReadPerMtok: 0.2,
+ cacheCreatePerMtok: 2.5,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: 4,
+ outputPerMtok: 12,
+ cacheReadPerMtok: 0.4,
+ cacheCreatePerMtok: 5,
+ },
+ ],
+ }),
+ ),
+ ).toBeCloseTo(1.018);
+ });
+
+ it('does not extend a bounded provider reference beyond its published interval', () => {
+ const boundedReference = quote('grok-code-fast', 0.2, 1.5, {
+ providerId: 'xai',
+ source: 'provider-reference',
+ approximate: true,
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 0,
+ maxInputTokens: 200_000,
+ inputPerMtok: 0.2,
+ outputPerMtok: 1.5,
+ },
+ ],
+ });
+
+ expect(
+ computeGatewayTurnCost(
+ {
+ inputTokens: 199_999,
+ outputTokens: 1,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ boundedReference,
+ ),
+ ).not.toBeNull();
+ expect(
+ computeGatewayTurnCost(
+ {
+ inputTokens: 200_000,
+ outputTokens: 1,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ boundedReference,
+ ),
+ ).toBeNull();
+ });
+});
+
+describe('computePriceQuoteTurnMoney', () => {
+ const tokens = {
+ inputTokens: 1_000_000,
+ outputTokens: 0,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ };
+
+ it('only marks subscription estimates with the subscription-value reason', () => {
+ expect(
+ computePriceQuoteTurnMoney(
+ tokens,
+ quote('subscription-model', 2, 10, {
+ source: 'subscription-reference',
+ approximate: true,
+ }),
+ 'USD',
+ )?.estimateReasons,
+ ).toEqual(['subscription-value', 'reference-price']);
+ for (const source of ['provider-reference', 'user-override'] as const) {
+ expect(
+ computePriceQuoteTurnMoney(
+ tokens,
+ quote('reference-model', 2, 10, { source, approximate: true }),
+ 'USD',
+ )?.estimateReasons,
+ ).toEqual(['reference-price']);
+ }
+ });
});
describe('resolveTurnCost', () => {
@@ -393,6 +501,34 @@ describe('resolveTurnCost', () => {
});
});
+ it('uses a provider reference or user override estimate when the SDK reports no cost', () => {
+ const result = resolveTurnCost({
+ rawModel: 'custom-model',
+ tokens: {
+ inputTokens: 1_000_000,
+ outputTokens: 100_000,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ sdkCostDelta: 0,
+ pricing: catalog(
+ quote('custom-model', 2, 10, {
+ providerId: 'anthropic',
+ source: 'user-override',
+ approximate: true,
+ }),
+ ),
+ context: PROVIDER_API,
+ });
+ expect(result.source).toBe('reference');
+ expect(result.money).toMatchObject({
+ amount: 3,
+ currency: 'USD',
+ approximate: true,
+ kind: 'value-estimate',
+ });
+ });
+
it('does not apply a Gateway discount to provider SDK cost facts', () => {
// 本例只验"折扣不落到第三方 SDK 实报值上",所以把账号币种显式钉成 USD:
// 否则 CNY 账本会按固定汇率投影,金额不再等于 SDK 原值,验的就不是折扣了。
@@ -416,7 +552,7 @@ describe('resolveTurnCost', () => {
}
});
- it('subscription routes and explicit subscription model prefixes never become actual cost', () => {
+ it('subscription routes and inferred subscription model prefixes never become actual cost', () => {
const byRoute = resolveTurnCost({
rawModel: 'claude-opus-4-8',
tokens: {
@@ -439,11 +575,69 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 5,
pricing: null,
- context: PROVIDER_API,
+ context: { providerId: null, billingRoute: 'unknown', region: 'global' },
});
expect(byRoute).toMatchObject({ source: 'subscription', money: null });
expect(byPrefix).toMatchObject({ source: 'subscription', money: null });
});
+
+ it('keeps explicit built-in OpenAI and xAI subscription sources out of actual spend', () => {
+ for (const [providerId, rawModel] of [
+ ['openai', 'chatgpt/gpt-5.5'],
+ ['xai', 'xai/grok-4.5'],
+ ] as const) {
+ const result = resolveTurnCost({
+ rawModel,
+ tokens: {
+ inputTokens: 1_000_000,
+ outputTokens: 100_000,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ sdkCostDelta: 5,
+ pricing: null,
+ context: {
+ providerId,
+ billingRoute: billingRouteForExplicitProvider(providerId, 'subscription')!,
+ region: 'global',
+ },
+ });
+ expect(result).toMatchObject({ source: 'subscription', money: null });
+ }
+ });
+
+ it('lets an explicit provider API route price a custom xAI-prefixed model', () => {
+ const result = resolveTurnCost({
+ rawModel: 'xai/grok-4.5',
+ tokens: {
+ inputTokens: 1_000_000,
+ outputTokens: 100_000,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ sdkCostDelta: 0,
+ pricing: catalog(
+ quote('xai/grok-4.5', 2, 10, {
+ providerId: 'vercel-ai-gateway',
+ source: 'user-override',
+ approximate: true,
+ }),
+ ),
+ context: {
+ providerId: 'vercel-ai-gateway',
+ billingRoute: 'provider-api',
+ region: 'global',
+ },
+ });
+
+ expect(result.source).toBe('reference');
+ expect(result.money).toMatchObject({
+ amount: 3,
+ currency: 'USD',
+ approximate: true,
+ kind: 'value-estimate',
+ });
+ });
});
describe('resolveClaudeTurnCostSinks', () => {
@@ -458,6 +652,7 @@ describe('resolveClaudeTurnCostSinks', () => {
XD_GATEWAY,
);
expect(result.turnMoney?.amount).toBe(7);
+ expect(result.estimatedTurnMoney).toBeNull();
expect(result.perModel.map((item) => item.money?.amount)).toEqual([5, 2]);
expect(result.perModel.map((item) => item.source)).toEqual(['gateway', 'gateway']);
});
@@ -491,15 +686,63 @@ describe('resolveClaudeTurnCostSinks', () => {
SUBSCRIPTION,
);
expect(result.turnMoney).toBeNull();
+ expect(result.estimatedTurnMoney).toBeNull();
expect(result.perModel[0]).toMatchObject({
source: 'subscription',
money: null,
});
});
+
+ it('keeps provider reference estimates out of actual spend', () => {
+ const reference = quote('claude-opus-4-8', 5, 25, {
+ providerId: 'anthropic',
+ source: 'provider-reference',
+ approximate: true,
+ });
+ const result = resolveClaudeTurnCostSinks(
+ [delta('claude-opus-4-8', { inputTokensDelta: 1_000_000 })],
+ catalog(reference),
+ PROVIDER_API,
+ );
+ expect(result.turnMoney).toBeNull();
+ expect(result.estimatedTurnMoney).toMatchObject({
+ amount: 5,
+ kind: 'value-estimate',
+ });
+ });
+
+ it('does not mix a reference estimate into an actual SDK cost total', () => {
+ const pricing = catalog(
+ quote('claude-opus-4-8', 5, 25, {
+ providerId: 'anthropic',
+ source: 'provider-reference',
+ approximate: true,
+ }),
+ );
+ const result = resolveClaudeTurnCostSinks(
+ [
+ delta('claude-opus-4-8', { inputTokensDelta: 1_000_000 }),
+ delta('other-model', { costUsdDelta: 2 }),
+ ],
+ pricing,
+ PROVIDER_API,
+ );
+ expect(result.turnMoney).toMatchObject({ amount: 2, kind: 'actual-cost' });
+ expect(result.estimatedTurnMoney).toMatchObject({ amount: 5, kind: 'value-estimate' });
+ });
});
describe('subscription value and usage details', () => {
it('estimates Anthropic subscription value from USD reference pricing', () => {
+ const pricing = catalog(
+ quote('claude-opus-4-8', 5, 25, {
+ providerId: 'anthropic',
+ source: 'provider-reference',
+ approximate: true,
+ cacheReadPerMtok: 0.5,
+ cacheCreatePerMtok: 6.25,
+ }),
+ );
const value = estimateClaudeSubscriptionTurnValue(
[
resolvedModel('claude-opus-4-8', {
@@ -508,6 +751,7 @@ describe('subscription value and usage details', () => {
}),
],
'USD',
+ pricing,
);
expect(value).toMatchObject({
amount: 10,
@@ -517,6 +761,63 @@ describe('subscription value and usage details', () => {
});
});
+ it('keeps estimates for Claude family aliases and dated wire ids', () => {
+ const pricing = catalog(
+ quote('claude-opus-4-8', 5, 25, {
+ providerId: 'anthropic',
+ source: 'provider-reference',
+ approximate: true,
+ }),
+ quote('claude-sonnet-4-6', 3, 15, {
+ providerId: 'anthropic',
+ source: 'provider-reference',
+ approximate: true,
+ }),
+ );
+ expect(
+ estimateClaudeSubscriptionTurnValue(
+ [resolvedModel('opus', { inputTokens: 1_000_000 })],
+ 'USD',
+ pricing,
+ ),
+ ).toMatchObject({ amount: 5, kind: 'value-estimate' });
+ expect(
+ estimateClaudeSubscriptionTurnValue(
+ [resolvedModel('claude-sonnet-4-6-20260701', { inputTokens: 1_000_000 })],
+ 'USD',
+ pricing,
+ ),
+ ).toMatchObject({ amount: 3, kind: 'value-estimate' });
+ });
+
+ it('prefers an agent-specific user override for a bare Claude family alias', () => {
+ const canonical = 'claude-sonnet-4-6';
+ const reference = quote(canonical, 3, 15, {
+ providerId: 'anthropic',
+ source: 'provider-reference',
+ approximate: true,
+ });
+ const override = quote(canonical, 9, 45, {
+ providerId: 'anthropic',
+ source: 'user-override',
+ approximate: true,
+ });
+ const pricing = {
+ anthropic: {
+ [canonical]: reference,
+ [`${canonical}\u0000claude-code`]: override,
+ },
+ };
+
+ expect(
+ estimateClaudeSubscriptionTurnValue(
+ [resolvedModel('sonnet', { inputTokens: 1_000_000 })],
+ 'USD',
+ pricing,
+ ),
+ ).toMatchObject({ amount: 9, kind: 'value-estimate' });
+ });
+
it('does not estimate non-Anthropic, already-costed, unknown, or zero-token entries', () => {
expect(
estimateClaudeSubscriptionTurnValue(
@@ -526,10 +827,11 @@ describe('subscription value and usage details', () => {
resolvedModel('claude-unknown-9', { inputTokens: 1_000_000 }),
],
'USD',
+ {},
),
).toBeNull();
expect(
- estimateClaudeSubscriptionTurnValue([resolvedModel('claude-opus-4-8')], 'USD'),
+ estimateClaudeSubscriptionTurnValue([resolvedModel('claude-opus-4-8')], 'USD', {}),
).toBeNull();
});
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index 8c1fbd1ba2..a96be1e68e 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -23,6 +23,23 @@ vi.mock('../../localDb/client/current', () => ({
vi.mock('../modelPricing', () => ({
getModelPricing: vi.fn(),
isModelPricingRefreshInFlight: vi.fn(() => false),
+ readModelPriceOverridesSnapshot: vi.fn(() => ({})),
+ getClaudeSubscriptionValuePrice: (
+ model: string,
+ pricing: Record<string, Record<string, unknown>> | null | undefined,
+ at?: string | Date,
+ ) =>
+ model === 'claude-sonnet-5'
+ ? {
+ providerId: 'anthropic',
+ modelId: model,
+ currency: 'USD',
+ source: 'subscription-reference',
+ approximate: true,
+ inputPerMtok: String(at).slice(0, 10) < '2026-09-01' ? 2 : 3,
+ outputPerMtok: String(at).slice(0, 10) < '2026-09-01' ? 10 : 15,
+ }
+ : pricing?.anthropic?.[model],
getCodexSubscriptionValuePrice: (
model: string,
pricing: Record<string, Record<string, unknown>> | null | undefined,
@@ -39,6 +56,21 @@ vi.mock('../modelPricing', () => ({
outputPerMtok: 8,
}
: undefined),
+ getCodexProviderSubscriptionValuePrice: (
+ providerId: string,
+ model: string,
+ ) =>
+ providerId === 'anthropic' && model === 'claude-sonnet-5'
+ ? {
+ providerId: 'anthropic',
+ modelId: model,
+ currency: 'USD',
+ source: 'subscription-reference',
+ approximate: true,
+ inputPerMtok: 2,
+ outputPerMtok: 10,
+ }
+ : undefined,
getSubscriptionDirectValuePrice: (model: string) =>
model === 'xai/grok-4.3'
? {
@@ -159,6 +191,7 @@ function makeDeps(overrides: Partial<UsageHistoryDeps> = {}): UsageHistoryDeps {
getAllSpendDays: async () => [],
getModelUsageSince: async () => [],
getModelPricing: async () => null,
+ getModelPriceOverridesSnapshot: () => ({}),
isModelPricingRefreshInFlight: () => false,
todayKey: () => TODAY,
...overrides,
@@ -318,6 +351,37 @@ describe('readUsageHistoryWith', () => {
expect(api?.subscriptionEstimateMoney.amount).toBe(0);
});
+ it('resolves subscription reference prices for each usage day', async () => {
+ const result = await readUsageHistoryWith(
+ makeDeps({
+ todayKey: () => '2026-09-02',
+ getModelUsageSince: async () => [
+ modelRow(
+ '2026-08-31',
+ 'claude-code',
+ claudeSubscriptionUsageModelKey('claude-sonnet-5'),
+ actual(0),
+ { inputTokens: 1_000_000 },
+ ),
+ modelRow(
+ '2026-09-01',
+ 'claude-code',
+ claudeSubscriptionUsageModelKey('claude-sonnet-5'),
+ actual(0),
+ { inputTokens: 1_000_000 },
+ ),
+ ],
+ }),
+ );
+
+ expect(result.modelDaily.map((row) => row.subscriptionEstimateMoney.amount)).toEqual([
+ regionalUsdAmount(2),
+ regionalUsdAmount(3),
+ ]);
+ expect(result.models[0].estimatedMoney?.amount).toBeCloseTo(regionalUsdAmount(5));
+ expect(result.totals.last30DaysEstimatedValue.amount).toBeCloseTo(regionalUsdAmount(5));
+ });
+
it('keeps current-region subscription estimates when history uses another currency', async () => {
const historicalCurrency = DEFAULT_USAGE_CURRENCY === 'CNY' ? 'USD' : 'CNY';
const estimateAmount = regionalUsdAmount(2);
diff --git a/apps/desktop/src/main/usage/modelPriceOverrideStore.ts b/apps/desktop/src/main/usage/modelPriceOverrideStore.ts
new file mode 100644
index 0000000000..e12209175f
--- /dev/null
+++ b/apps/desktop/src/main/usage/modelPriceOverrideStore.ts
@@ -0,0 +1,579 @@
+/**
+ * Per-(provider instance, runtime, model id) local reference-price patches.
+ *
+ * The JSON file is an internal persistence detail. Users edit it only through Settings.
+ * Records are sparse and keep the remote reference used when they were saved; if that
+ * reference later changes, the local patch wins and the UI exposes a conflict/reset state.
+ */
+
+import type { AgentKind, ModelRegistry } from '@cindy/model-providers';
+
+import { modelPricingKey, providerReferencePriceQuote } from '../../shared/modelPriceQuote.js';
+import type {
+ ModelPriceOverrideDesiredQuote,
+ ModelPriceOverrideTarget,
+ ModelPriceOverrideValues,
+ ModelPriceOverrideView,
+} from '../../shared/modelPriceOverride.js';
+import type {
+ ModelPriceQuote,
+ ModelPricingCatalog,
+ MoneyCurrency,
+} from '../../shared/regionalMoney.js';
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { currentLedgerCurrency } from './ledgerCurrency.js';
+
+const log = desktopMakerLogger.child('model-price-overrides');
+const STORE_VERSION = 1;
+const MAX_ENTRIES = 4096;
+
+interface ComparablePrice {
+ currency: MoneyCurrency;
+ inputPerMtok: number;
+ outputPerMtok: number;
+ cacheReadPerMtok: number | null;
+ cacheCreatePerMtok: number | null;
+ inputTokenPriceBands?: ModelPriceQuote['inputTokenPriceBands'];
+}
+
+interface StoredModelPriceOverride extends ModelPriceOverrideTarget {
+ values: ModelPriceOverrideValues;
+ baseReference: ComparablePrice | null;
+ updatedAt: string;
+}
+
+interface ModelPriceOverridePrefs {
+ version: typeof STORE_VERSION;
+ entries: Record<string, StoredModelPriceOverride>;
+}
+
+const DEFAULTS: ModelPriceOverridePrefs = { version: STORE_VERSION, entries: {} };
+
+function isAgent(value: unknown): value is AgentKind {
+ return value === 'claude-code' || value === 'codex';
+}
+
+function isCurrency(value: unknown): value is MoneyCurrency {
+ return value === 'USD' || value === 'CNY';
+}
+
+function finiteNonNegative(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
+}
+
+function overrideKey(target: ModelPriceOverrideTarget): string {
+ return JSON.stringify([target.providerId, target.agent, target.modelId]);
+}
+
+function normalizeNullablePrice(value: unknown): number | null | undefined {
+ return value === null || finiteNonNegative(value) ? value : undefined;
+}
+
+function normalizeValues(value: unknown): ModelPriceOverrideValues | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const raw = value as Record<string, unknown>;
+ const values: ModelPriceOverrideValues = {};
+ if (isCurrency(raw.currency)) values.currency = raw.currency;
+ if (finiteNonNegative(raw.inputPerMtok)) values.inputPerMtok = raw.inputPerMtok;
+ if (finiteNonNegative(raw.outputPerMtok)) values.outputPerMtok = raw.outputPerMtok;
+ const cacheRead = normalizeNullablePrice(raw.cacheReadPerMtok);
+ const cacheCreate = normalizeNullablePrice(raw.cacheCreatePerMtok);
+ if (cacheRead !== undefined) values.cacheReadPerMtok = cacheRead;
+ if (cacheCreate !== undefined) values.cacheCreatePerMtok = cacheCreate;
+ return Object.keys(values).length > 0 ? values : null;
+}
+
+function normalizeComparable(value: unknown): ComparablePrice | null | undefined {
+ if (value === null) return null;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const raw = value as Record<string, unknown>;
+ if (
+ !isCurrency(raw.currency) ||
+ !finiteNonNegative(raw.inputPerMtok) ||
+ !finiteNonNegative(raw.outputPerMtok)
+ ) {
+ return undefined;
+ }
+ const inputTokenPriceBands = Array.isArray(raw.inputTokenPriceBands)
+ ? raw.inputTokenPriceBands
+ .map((value) => normalizeComparableBand(value))
+ .filter((value): value is NonNullable<typeof value> => value !== undefined)
+ : undefined;
+ return {
+ currency: raw.currency,
+ inputPerMtok: raw.inputPerMtok,
+ outputPerMtok: raw.outputPerMtok,
+ cacheReadPerMtok: finiteNonNegative(raw.cacheReadPerMtok) ? raw.cacheReadPerMtok : null,
+ cacheCreatePerMtok: finiteNonNegative(raw.cacheCreatePerMtok) ? raw.cacheCreatePerMtok : null,
+ ...(inputTokenPriceBands?.length ? { inputTokenPriceBands } : {}),
+ };
+}
+
+function normalizeComparableBand(
+ value: unknown,
+): NonNullable<ModelPriceQuote['inputTokenPriceBands']>[number] | undefined {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const raw = value as Record<string, unknown>;
+ if (
+ !finiteNonNegative(raw.minInputTokens) ||
+ (raw.maxInputTokens !== undefined &&
+ (!finiteNonNegative(raw.maxInputTokens) || raw.maxInputTokens <= raw.minInputTokens))
+ ) {
+ return undefined;
+ }
+ const band: NonNullable<ModelPriceQuote['inputTokenPriceBands']>[number] = {
+ minInputTokens: raw.minInputTokens,
+ ...(raw.maxInputTokens !== undefined ? { maxInputTokens: raw.maxInputTokens as number } : {}),
+ };
+ for (const field of [
+ 'inputPerMtok',
+ 'outputPerMtok',
+ 'cacheReadPerMtok',
+ 'cacheCreatePerMtok',
+ ] as const) {
+ if (finiteNonNegative(raw[field])) band[field] = raw[field];
+ }
+ return band;
+}
+
+function normalize(raw: unknown): ModelPriceOverridePrefs {
+ const entries: Record<string, StoredModelPriceOverride> = {};
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { version: STORE_VERSION, entries: {} };
+ }
+ const source = (raw as { entries?: unknown }).entries;
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
+ return { version: STORE_VERSION, entries: {} };
+ }
+ let count = 0;
+ for (const value of Object.values(source as Record<string, unknown>)) {
+ if (count >= MAX_ENTRIES) break;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
+ const record = value as Record<string, unknown>;
+ const values = normalizeValues(record.values);
+ const baseReference = normalizeComparable(record.baseReference);
+ if (
+ typeof record.providerId !== 'string' ||
+ !record.providerId ||
+ record.providerId.length > 256 ||
+ !isAgent(record.agent) ||
+ typeof record.modelId !== 'string' ||
+ !record.modelId ||
+ record.modelId.length > 256 ||
+ !values ||
+ baseReference === undefined ||
+ typeof record.updatedAt !== 'string'
+ ) {
+ continue;
+ }
+ const normalized: StoredModelPriceOverride = {
+ providerId: record.providerId,
+ agent: record.agent,
+ modelId: record.modelId,
+ values,
+ baseReference,
+ updatedAt: record.updatedAt,
+ };
+ entries[overrideKey(normalized)] = normalized;
+ count += 1;
+ }
+ return { version: STORE_VERSION, entries };
+}
+
+const store = createOverrideSettingsFile<ModelPriceOverridePrefs>({
+ filePath: () => ownerScopedUserDataPath('model-price-overrides.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'model-price-overrides',
+});
+
+function comparable(quote: ModelPriceQuote | undefined): ComparablePrice | null {
+ if (!quote) return null;
+ return {
+ currency: quote.currency,
+ inputPerMtok: quote.inputPerMtok,
+ outputPerMtok: quote.outputPerMtok,
+ cacheReadPerMtok: quote.cacheReadPerMtok ?? null,
+ cacheCreatePerMtok: quote.cacheCreatePerMtok ?? null,
+ ...(quote.inputTokenPriceBands ? { inputTokenPriceBands: quote.inputTokenPriceBands } : {}),
+ };
+}
+
+function sameComparable(a: ComparablePrice | null, b: ComparablePrice | null): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+function sparseValues(
+ desired: ModelPriceOverrideDesiredQuote,
+ reference: ComparablePrice | null,
+): ModelPriceOverrideValues {
+ if (!reference) return { ...desired };
+ const values: ModelPriceOverrideValues = {};
+ const currencyChanged = desired.currency !== reference.currency;
+ if (currencyChanged) values.currency = desired.currency;
+ // Currency changes cannot reuse any numeric value from the reference quote: doing so would
+ // relabel (for example) USD long-context bands as CNY without an exchange conversion. Persist
+ // the complete user-entered quote so mergedQuote rewrites every inherited band in the new unit.
+ if (currencyChanged) {
+ values.inputPerMtok = desired.inputPerMtok;
+ values.outputPerMtok = desired.outputPerMtok;
+ values.cacheReadPerMtok = desired.cacheReadPerMtok ?? null;
+ values.cacheCreatePerMtok = desired.cacheCreatePerMtok ?? null;
+ return values;
+ }
+ if (desired.inputPerMtok !== reference.inputPerMtok) {
+ values.inputPerMtok = desired.inputPerMtok;
+ }
+ if (desired.outputPerMtok !== reference.outputPerMtok) {
+ values.outputPerMtok = desired.outputPerMtok;
+ }
+ if ((desired.cacheReadPerMtok ?? null) !== reference.cacheReadPerMtok) {
+ values.cacheReadPerMtok = desired.cacheReadPerMtok ?? null;
+ }
+ if ((desired.cacheCreatePerMtok ?? null) !== reference.cacheCreatePerMtok) {
+ values.cacheCreatePerMtok = desired.cacheCreatePerMtok ?? null;
+ }
+ return values;
+}
+
+function mergedQuote(
+ target: ModelPriceOverrideTarget,
+ reference: ModelPriceQuote | undefined,
+ values: ModelPriceOverrideValues | undefined,
+ baseReference?: ComparablePrice | null,
+): ModelPriceQuote | undefined {
+ if (!values) return reference;
+ const savedBaseQuote = baseReference
+ ? {
+ providerId: target.providerId,
+ modelId: target.modelId,
+ source: reference?.source ?? ('provider-reference' as const),
+ approximate: reference?.approximate ?? true,
+ currency: baseReference.currency,
+ inputPerMtok: baseReference.inputPerMtok,
+ outputPerMtok: baseReference.outputPerMtok,
+ ...(baseReference.cacheReadPerMtok !== null
+ ? { cacheReadPerMtok: baseReference.cacheReadPerMtok }
+ : {}),
+ ...(baseReference.cacheCreatePerMtok !== null
+ ? { cacheCreatePerMtok: baseReference.cacheCreatePerMtok }
+ : {}),
+ ...(baseReference.inputTokenPriceBands
+ ? { inputTokenPriceBands: baseReference.inputTokenPriceBands }
+ : {}),
+ }
+ : undefined;
+ // A same-currency update can drop the long-context bands the patch was saved
+ // against (typical of a fidelity downgrade to a band-less fallback catalog).
+ // Discarding the bands would flatten long-context estimates, but freezing the
+ // whole saved snapshot would also stop un-overridden base prices from following
+ // the remote. Split the difference: base prices keep following the new
+ // reference, while each saved band keeps its relative multiplier and is
+ // re-anchored onto the new baselines.
+ const reAnchorBandValue = (
+ bandValue: number | undefined,
+ savedBaseValue: number | undefined,
+ referenceValue: number | undefined,
+ ): number | undefined => {
+ if (bandValue === undefined) return undefined;
+ return savedBaseValue !== undefined && savedBaseValue > 0 && referenceValue !== undefined
+ ? (bandValue / savedBaseValue) * referenceValue
+ : bandValue;
+ };
+ const bandPreservingReference =
+ savedBaseQuote?.inputTokenPriceBands !== undefined &&
+ reference &&
+ values.currency === undefined &&
+ savedBaseQuote.currency === reference.currency &&
+ reference.inputTokenPriceBands === undefined
+ ? {
+ ...reference,
+ inputTokenPriceBands: savedBaseQuote.inputTokenPriceBands.map((band) => ({
+ ...band,
+ inputPerMtok: reAnchorBandValue(
+ band.inputPerMtok,
+ savedBaseQuote.inputPerMtok,
+ reference.inputPerMtok,
+ ),
+ outputPerMtok: reAnchorBandValue(
+ band.outputPerMtok,
+ savedBaseQuote.outputPerMtok,
+ reference.outputPerMtok,
+ ),
+ cacheReadPerMtok: reAnchorBandValue(
+ band.cacheReadPerMtok,
+ savedBaseQuote.cacheReadPerMtok,
+ reference.cacheReadPerMtok,
+ ),
+ cacheCreatePerMtok: reAnchorBandValue(
+ band.cacheCreatePerMtok,
+ savedBaseQuote.cacheCreatePerMtok,
+ reference.cacheCreatePerMtok,
+ ),
+ })),
+ }
+ : undefined;
+ // A sparse numeric patch was entered in the saved base currency. If the remote
+ // route later changes currency or loses its reference price, merging it into the
+ // new/empty quote would silently relabel or discard the user's number. Keep using
+ // the saved reference as the merge base until the user accepts/reset the conflict.
+ const mergeReference =
+ bandPreservingReference ??
+ (savedBaseQuote &&
+ (!reference ||
+ (values.currency === undefined && savedBaseQuote.currency !== reference.currency))
+ ? savedBaseQuote
+ : reference);
+ const currency = values.currency ?? mergeReference?.currency;
+ const inputPerMtok = values.inputPerMtok ?? mergeReference?.inputPerMtok;
+ const outputPerMtok = values.outputPerMtok ?? mergeReference?.outputPerMtok;
+ if (!currency || inputPerMtok === undefined || outputPerMtok === undefined) return undefined;
+ const cacheReadPerMtok =
+ values.cacheReadPerMtok === null
+ ? undefined
+ : (values.cacheReadPerMtok ?? mergeReference?.cacheReadPerMtok);
+ const cacheCreatePerMtok =
+ values.cacheCreatePerMtok === null
+ ? undefined
+ : (values.cacheCreatePerMtok ?? mergeReference?.cacheCreatePerMtok);
+ const projectBandValue = (
+ bandValue: number | undefined,
+ referenceValue: number | undefined,
+ overrideValue: number,
+ ): number | undefined => {
+ if (bandValue === undefined) return undefined;
+ // A base-price edit does not erase the provider's long-context pricing curve. Preserve each
+ // inherited tier's relative multiplier for both same-currency edits and currency switches;
+ // otherwise editing the baseline would flatten every tier to the same price.
+ return referenceValue !== undefined && referenceValue > 0
+ ? (bandValue / referenceValue) * overrideValue
+ : overrideValue;
+ };
+ const inputTokenPriceBands = mergeReference?.inputTokenPriceBands?.map((band) => {
+ const merged = { ...band };
+ if (values.inputPerMtok !== undefined) {
+ merged.inputPerMtok = projectBandValue(
+ band.inputPerMtok,
+ mergeReference.inputPerMtok,
+ values.inputPerMtok,
+ );
+ }
+ if (values.outputPerMtok !== undefined) {
+ merged.outputPerMtok = projectBandValue(
+ band.outputPerMtok,
+ mergeReference.outputPerMtok,
+ values.outputPerMtok,
+ );
+ }
+ if (values.cacheReadPerMtok === null) delete merged.cacheReadPerMtok;
+ else if (values.cacheReadPerMtok !== undefined) {
+ merged.cacheReadPerMtok = projectBandValue(
+ band.cacheReadPerMtok,
+ mergeReference.cacheReadPerMtok,
+ values.cacheReadPerMtok,
+ );
+ }
+ if (values.cacheCreatePerMtok === null) delete merged.cacheCreatePerMtok;
+ else if (values.cacheCreatePerMtok !== undefined) {
+ merged.cacheCreatePerMtok = projectBandValue(
+ band.cacheCreatePerMtok,
+ mergeReference.cacheCreatePerMtok,
+ values.cacheCreatePerMtok,
+ );
+ }
+ return merged;
+ });
+ return {
+ providerId: target.providerId,
+ modelId: target.modelId,
+ currency,
+ source: 'user-override',
+ approximate: true,
+ inputPerMtok,
+ outputPerMtok,
+ ...(inputTokenPriceBands ? { inputTokenPriceBands } : {}),
+ ...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),
+ ...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),
+ };
+}
+
+function currencyCanProjectToLedger(
+ currency: MoneyCurrency,
+ ledgerCurrency: MoneyCurrency,
+): boolean {
+ return currency === ledgerCurrency || (currency === 'USD' && ledgerCurrency === 'CNY');
+}
+
+function allowedCurrenciesForLedger(ledgerCurrency: MoneyCurrency): MoneyCurrency[] {
+ return ledgerCurrency === 'USD' ? ['USD'] : ['USD', 'CNY'];
+}
+
+function readEntries(): Record<string, StoredModelPriceOverride> {
+ store.invalidateIfChanged();
+ return store.read().entries;
+}
+
+export function readModelPriceOverrideView(
+ target: ModelPriceOverrideTarget,
+ registry: ModelRegistry | null | undefined,
+ ledgerCurrency: MoneyCurrency = currentLedgerCurrency(),
+): ModelPriceOverrideView {
+ const remoteReference = providerReferencePriceQuote(target.providerId, target.modelId, registry, {
+ agent: target.agent,
+ });
+ const reference =
+ remoteReference && currencyCanProjectToLedger(remoteReference.currency, ledgerCurrency)
+ ? remoteReference
+ : undefined;
+ const record = readEntries()[overrideKey(target)];
+ const merged = mergedQuote(target, reference, record?.values, record?.baseReference);
+ return {
+ target,
+ editable: target.providerId !== 'xd',
+ reference: reference ?? null,
+ effective:
+ merged && currencyCanProjectToLedger(merged.currency, ledgerCurrency)
+ ? merged
+ : (reference ?? null),
+ override: record?.values ?? null,
+ conflict: Boolean(record && !sameComparable(record.baseReference, comparable(remoteReference))),
+ registryUpdatedAt: registry?.updatedAt ?? null,
+ allowedCurrencies: allowedCurrenciesForLedger(ledgerCurrency),
+ };
+}
+
+export function setModelPriceOverride(
+ target: ModelPriceOverrideTarget,
+ desired: ModelPriceOverrideDesiredQuote,
+ registry: ModelRegistry | null | undefined,
+): void {
+ if (target.providerId === 'xd') {
+ throw new Error('Cindy AI Gateway pricing cannot be overridden');
+ }
+ const reference = providerReferencePriceQuote(target.providerId, target.modelId, registry, {
+ agent: target.agent,
+ });
+ const baseReference = comparable(reference);
+ const values = sparseValues(desired, baseReference);
+ const entries = { ...readEntries() };
+ const key = overrideKey(target);
+ if (Object.keys(values).length === 0) {
+ if (key in entries) {
+ delete entries[key];
+ store.writePatch({ entries });
+ }
+ return;
+ }
+ if (!(key in entries) && Object.keys(entries).length >= MAX_ENTRIES) {
+ throw new Error('model price override limit reached');
+ }
+ entries[key] = {
+ ...target,
+ values,
+ baseReference,
+ updatedAt: new Date().toISOString(),
+ };
+ store.writePatch({ entries });
+}
+
+export function clearModelPriceOverride(target: ModelPriceOverrideTarget): void {
+ const entries = { ...readEntries() };
+ const key = overrideKey(target);
+ if (!(key in entries)) return;
+ delete entries[key];
+ store.writePatch({ entries });
+}
+
+/**
+ * Custom-provider deletion cleanup. The caller serializes this with provider config mutations;
+ * the returned closure restores only this provider's removed records while preserving unrelated
+ * override writes.
+ */
+export function stageProviderModelPriceOverridesClear(providerId: string): () => boolean {
+ const entries = readEntries();
+ const removed = Object.fromEntries(
+ Object.entries(entries).filter(([, record]) => record.providerId === providerId),
+ );
+ if (Object.keys(removed).length === 0) return () => true;
+ store.writePatch({
+ entries: Object.fromEntries(
+ Object.entries(entries).filter(([, record]) => record.providerId !== providerId),
+ ),
+ });
+ return () => {
+ try {
+ store.writePatch({ entries: { ...readEntries(), ...removed } });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+}
+
+/**
+ * 覆盖记录的一次性快照。历史用量聚合按 model-day 逐行取价,每行都走
+ * `readEntries()` 会重复 stat 覆盖文件(Windows/慢盘上数百上千次同步磁盘访问);
+ * 聚合开始时读一次快照、贯穿整轮复用。
+ */
+export type ModelPriceOverridesSnapshot = Readonly<Record<string, StoredModelPriceOverride>>;
+
+export function readModelPriceOverridesSnapshot(): ModelPriceOverridesSnapshot {
+ return readEntries();
+}
+
+/**
+ * 把持久化的稀疏覆盖合并到调用方给定的参考价上(典型:按历史日期 `at` 解析出的
+ * 参考价)。目录里烘焙的 user-override 报价是按当前日期合并的,历史估值不能直接
+ * 回用——未覆盖字段必须跟随查询时点的参考价。无该目标的覆盖记录时返回 undefined。
+ * 批量取价的调用方应传入同一份 `entries` 快照,避免逐行重读覆盖文件。
+ */
+export function mergeStoredModelPriceOverride(
+ target: ModelPriceOverrideTarget,
+ reference: ModelPriceQuote | undefined,
+ entries: ModelPriceOverridesSnapshot = readEntries(),
+): ModelPriceQuote | undefined {
+ const record = entries[overrideKey(target)];
+ if (!record) return undefined;
+ return mergedQuote(record, reference, record.values, record.baseReference);
+}
+
+export function applyModelPriceOverrides(
+ pricing: ModelPricingCatalog,
+ registry: ModelRegistry | null | undefined,
+ ledgerCurrency: MoneyCurrency = currentLedgerCurrency(),
+): ModelPricingCatalog {
+ const next: ModelPricingCatalog = Object.fromEntries(
+ Object.entries(pricing).map(([providerId, quotes]) => [
+ providerId,
+ Object.fromEntries(
+ Object.entries(quotes).filter(
+ ([, quote]) =>
+ quote.source === 'gateway' ||
+ currencyCanProjectToLedger(quote.currency, ledgerCurrency),
+ ),
+ ),
+ ]),
+ );
+ for (const record of Object.values(readEntries())) {
+ if (record.providerId === 'xd') continue;
+ const reference = providerReferencePriceQuote(record.providerId, record.modelId, registry, {
+ agent: record.agent,
+ });
+ const quote = mergedQuote(record, reference, record.values, record.baseReference);
+ if (!quote || !currencyCanProjectToLedger(quote.currency, ledgerCurrency)) continue;
+ (next[record.providerId] ??= {})[modelPricingKey(record.modelId, record.agent)] = quote;
+ }
+ return next;
+}
+
+export const __testing = {
+ normalize,
+ overrideKey,
+ sparseValues,
+ sameComparable,
+ mergedQuote,
+ currencyCanProjectToLedger,
+};
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index 11df6668e4..f77d198f8a 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -16,6 +16,8 @@ import {
gatewayLedgerCurrency,
gatewayPricingCatalog,
getModelPriceQuote,
+ providerReferencePriceQuote,
+ registryPricingCatalog,
subscriptionDirectPriceQuote,
} from '../../shared/modelPriceQuote.js';
import type { ModelAccessGatewayModel } from '../../shared/modelAccess.js';
@@ -31,6 +33,15 @@ import { setActiveLedgerCurrency } from './ledgerCurrency.js';
import { createLogger } from '../logger.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';
+import { getActiveCatalog } from '../maker-host/active-catalog.js';
+import {
+ applyModelPriceOverrides,
+ mergeStoredModelPriceOverride,
+ type ModelPriceOverridesSnapshot,
+} from './modelPriceOverrideStore.js';
+
+export type { ModelPriceOverridesSnapshot } from './modelPriceOverrideStore.js';
+export { readModelPriceOverridesSnapshot } from './modelPriceOverrideStore.js';
export { getModelPriceQuote } from '../../shared/modelPriceQuote.js';
export type {
@@ -111,6 +122,45 @@ function isNonNegativeFinite(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
}
+function validateInputTokenPriceBands(
+ value: unknown,
+): ModelPriceQuote['inputTokenPriceBands'] {
+ if (!Array.isArray(value)) return undefined;
+ const bands: NonNullable<ModelPriceQuote['inputTokenPriceBands']> = [];
+ for (const raw of value.slice(0, 32)) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;
+ const band = raw as Record<string, unknown>;
+ if (
+ !isNonNegativeFinite(band.minInputTokens) ||
+ (band.maxInputTokens !== undefined &&
+ (!isNonNegativeFinite(band.maxInputTokens) ||
+ band.maxInputTokens <= band.minInputTokens))
+ ) {
+ continue;
+ }
+ const next: NonNullable<ModelPriceQuote['inputTokenPriceBands']>[number] = {
+ minInputTokens: band.minInputTokens,
+ ...(band.maxInputTokens !== undefined
+ ? { maxInputTokens: band.maxInputTokens as number }
+ : {}),
+ };
+ let hasPrice = false;
+ for (const field of [
+ 'inputPerMtok',
+ 'outputPerMtok',
+ 'cacheReadPerMtok',
+ 'cacheCreatePerMtok',
+ ] as const) {
+ if (isNonNegativeFinite(band[field])) {
+ next[field] = band[field];
+ hasPrice = true;
+ }
+ }
+ if (hasPrice) bands.push(next);
+ }
+ return bands.length > 0 ? bands : undefined;
+}
+
function validateQuote(
value: unknown,
providerId: string,
@@ -144,6 +194,10 @@ function validateQuote(
if (isNonNegativeFinite(quote.cacheCreatePerMtok)) {
next.cacheCreatePerMtok = quote.cacheCreatePerMtok;
}
+ const inputTokenPriceBands = validateInputTokenPriceBands(quote.inputTokenPriceBands);
+ if (inputTokenPriceBands) {
+ next.inputTokenPriceBands = inputTokenPriceBands;
+ }
if (
typeof quote.costDiscount === 'number' &&
Number.isFinite(quote.costDiscount) &&
@@ -264,6 +318,23 @@ function broadcastPricing(pricing: ModelPricingCatalog | null): void {
}
}
+function effectivePricingCatalog(gatewayPricing: ModelPricingCatalog | null): ModelPricingCatalog {
+ const registry = getActiveCatalog().modelRegistry;
+ const reference = registryPricingCatalog(registry);
+ return applyModelPriceOverrides(
+ {
+ ...reference,
+ ...(gatewayPricing?.xd ? { xd: gatewayPricing.xd } : {}),
+ },
+ registry,
+ );
+}
+
+export function broadcastEffectiveModelPricing(): void {
+ const scope = currentScope();
+ broadcastPricing(effectivePricingCatalog(cacheScope === scope ? cache : null));
+}
+
/**
* 与模型同步同快照更新 XD quote。models 非空但没有标准 input/output 价格时,
* 价格投影会被清空,不复活旧模型价格。
@@ -288,7 +359,7 @@ export function replaceGatewayModelPricing(
setActiveLedgerCurrency(gatewayAccountCurrency);
hydratedScopes.add(scope);
void writeDiskCache(scope, pricing, gatewayAccountCurrency, cacheAt);
- broadcastPricing(pricing);
+ broadcastPricing(effectivePricingCatalog(pricing));
return pricing;
}
@@ -314,8 +385,8 @@ export function isModelPricingRefreshInFlight(): boolean {
export async function getModelPricing(): Promise<ModelPricingCatalog | null> {
const scope = currentScope();
- if (cacheScope === scope) return cache;
- return hydrateFromDisk(scope);
+ const gatewayPricing = cacheScope === scope ? cache : await hydrateFromDisk(scope);
+ return effectivePricingCatalog(gatewayPricing);
}
/**
@@ -373,15 +444,124 @@ export async function getModelPricingForModel(
return pricing;
}
+/**
+ * Codex 订阅轮的估算价,按显式来源 provider 取该 provider 的 registry 参考价
+ * (含用户价格覆盖)。openai 之外的订阅来源(如内置 anthropic 的 Claude.ai 订阅)
+ * 也走各自的日期定价路由,不能一律套 OpenAI 价表。
+ */
+export function getCodexProviderSubscriptionValuePrice(
+ providerId: string,
+ modelId: string,
+ pricing: ModelPricingCatalog | null | undefined,
+ at?: string | Date,
+ overrides?: ModelPriceOverridesSnapshot,
+): ModelPriceQuote | undefined {
+ const effective = getModelPriceQuote(pricing, providerId, modelId, 'codex');
+ if (effective?.source === 'user-override') {
+ if (at === undefined) return effective;
+ // 目录里烘焙的 user-override 是按当前日期合并的;历史窗口跨过参考价生效边界时,
+ // 未覆盖字段必须按 at 时点的参考价重新合并,不能直接回用当前合并结果。
+ return (
+ mergeStoredModelPriceOverride(
+ { providerId, agent: 'codex', modelId: effective.modelId },
+ providerReferencePriceQuote(
+ providerId,
+ effective.modelId,
+ getActiveCatalog().modelRegistry,
+ { agent: 'codex', at },
+ ),
+ overrides,
+ ) ?? effective
+ );
+ }
+ const reference = providerReferencePriceQuote(
+ providerId,
+ modelId,
+ getActiveCatalog().modelRegistry,
+ { agent: 'codex', at },
+ );
+ return reference ?? (at === undefined ? effective : undefined);
+}
+
export function getCodexSubscriptionValuePrice(
modelId: string,
pricing: ModelPricingCatalog | null | undefined,
+ at?: string | Date,
+ overrides?: ModelPriceOverridesSnapshot,
): ModelPriceQuote | undefined {
- return getModelPriceQuote(pricing, 'openai', modelId);
+ return getCodexProviderSubscriptionValuePrice('openai', modelId, pricing, at, overrides);
}
-export function getSubscriptionDirectValuePrice(modelId: string): ModelPriceQuote | undefined {
- return subscriptionDirectPriceQuote(modelId);
+export function getClaudeSubscriptionValuePrice(
+ modelId: string,
+ pricing: ModelPricingCatalog | null | undefined,
+ at?: string | Date,
+ overrides?: ModelPriceOverridesSnapshot,
+): ModelPriceQuote | undefined {
+ const effective = getModelPriceQuote(pricing, 'anthropic', modelId, 'claude-code');
+ if (effective?.source === 'user-override') {
+ if (at === undefined) return effective;
+ // 同 getCodexSubscriptionValuePrice:历史估值按 at 时点参考价重新合并稀疏覆盖。
+ return (
+ mergeStoredModelPriceOverride(
+ { providerId: 'anthropic', agent: 'claude-code', modelId: effective.modelId },
+ providerReferencePriceQuote(
+ 'anthropic',
+ effective.modelId,
+ getActiveCatalog().modelRegistry,
+ { agent: 'claude-code', at },
+ ),
+ overrides,
+ ) ?? effective
+ );
+ }
+ const reference = providerReferencePriceQuote(
+ 'anthropic',
+ modelId,
+ getActiveCatalog().modelRegistry,
+ { agent: 'claude-code', at },
+ );
+ return reference ?? (at === undefined ? effective : undefined);
+}
+
+export function getSubscriptionDirectValuePrice(
+ modelId: string,
+ agent?: 'claude-code' | 'codex',
+ pricing?: ModelPricingCatalog | null,
+ at?: string | Date,
+ overrides?: ModelPriceOverridesSnapshot,
+): ModelPriceQuote | undefined {
+ const registry = getActiveCatalog().modelRegistry;
+ const fallback = subscriptionDirectPriceQuote(
+ modelId,
+ registry,
+ agent,
+ at,
+ );
+ const routingQuote = fallback ?? subscriptionDirectPriceQuote(modelId, registry, agent);
+ if (!routingQuote) return undefined;
+ const effective = getModelPriceQuote(pricing, routingQuote.providerId, modelId, agent);
+ const quote =
+ effective?.source === 'user-override'
+ ? at === undefined || agent === undefined
+ ? effective
+ : // 同上:历史窗口内的订阅直连估值也要按 at 时点参考价重新合并稀疏覆盖。
+ (mergeStoredModelPriceOverride(
+ { providerId: effective.providerId, agent, modelId: effective.modelId },
+ providerReferencePriceQuote(effective.providerId, effective.modelId, registry, {
+ agent,
+ at,
+ }),
+ overrides,
+ ) ?? effective)
+ : fallback;
+ if (!quote) return undefined;
+ return {
+ ...quote,
+ modelId,
+ source:
+ quote.source === 'provider-reference' ? 'subscription-reference' : quote.source,
+ };
}
/** 启动只读磁盘快照;真正的新价格仍由 /models 同步整体替换。 */
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index 5bc5f519e1..a05cbfed3d 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -7,7 +7,6 @@ import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
import {
gatewayLedgerCurrency,
getModelPriceQuote,
- providerReferencePriceQuote,
} from '../../shared/modelPriceQuote.js';
import {
addRegionalMoney,
@@ -33,14 +32,29 @@ export interface TurnTokenDeltas {
export type BillingRoute = 'xd-gateway' | 'provider-api' | 'subscription' | 'unknown';
+/**
+ * 将显式选择的 provider 映射为计费来源。`access.kind` 是目录已有的产品语义,
+ * 不能把所有显式 provider 都推断成按量 API:OpenAI / xAI 等内置 OAuth 来源
+ * 本身是订阅,SDK 即使上报 cost 也不能写进实际支出。
+ */
+export function billingRouteForExplicitProvider(
+ providerId: string | null,
+ accessKind: 'subscription' | 'api' | 'managed' | null | undefined,
+): BillingRoute | null {
+ if (!providerId) return null;
+ if (providerId === 'xd') return 'xd-gateway';
+ // 保留旧目录 / LKG 缺 access 时对 Anthropic 的历史订阅判定。
+ if (providerId === 'anthropic' || accessKind === 'subscription') return 'subscription';
+ return 'provider-api';
+}
+
export interface TurnPricingContext {
providerId: string | null;
billingRoute: BillingRoute;
region: CindyRegion;
}
-
-export type TurnCostSource = 'sdk' | 'gateway' | 'sdk-fallback' | 'subscription';
+export type TurnCostSource = 'sdk' | 'gateway' | 'reference' | 'sdk-fallback' | 'subscription';
export interface TurnCostResolution {
model: string;
@@ -72,11 +86,33 @@ export function computeGatewayTurnCost(
price: ModelPriceQuote | undefined,
): number | null {
if (!price) return null;
- const cacheReadPrice = price.cacheReadPerMtok ?? price.inputPerMtok;
- const cacheCreatePrice = price.cacheCreatePerMtok ?? price.inputPerMtok;
+ const totalInputTokens =
+ tokens.inputTokens + tokens.cacheReadTokens + tokens.cacheCreateTokens;
+ const band = price.inputTokenPriceBands
+ ?.filter(
+ (candidate) =>
+ totalInputTokens >= candidate.minInputTokens &&
+ (candidate.maxInputTokens === undefined ||
+ totalInputTokens < candidate.maxInputTokens),
+ )
+ .sort((a, b) => b.minInputTokens - a.minInputTokens)[0];
+ // Provider reference bands describe the complete set of ranges for which the
+ // provider published a price. Falling back to the baseline outside every band
+ // would silently extend a bounded quote (for example <200k) to the model's
+ // whole context window. Gateway bands remain overlays because its legacy
+ // threshold fields intentionally omit the baseline range.
+ if (price.inputTokenPriceBands?.length && !band && price.source !== 'gateway') {
+ return null;
+ }
+ const inputPrice = band?.inputPerMtok ?? price.inputPerMtok;
+ const outputPrice = band?.outputPerMtok ?? price.outputPerMtok;
+ const cacheReadPrice =
+ band?.cacheReadPerMtok ?? price.cacheReadPerMtok ?? inputPrice;
+ const cacheCreatePrice =
+ band?.cacheCreatePerMtok ?? price.cacheCreatePerMtok ?? inputPrice;
return (
- (tokens.inputTokens * price.inputPerMtok +
- tokens.outputTokens * price.outputPerMtok +
+ (tokens.inputTokens * inputPrice +
+ tokens.outputTokens * outputPrice +
tokens.cacheReadTokens * cacheReadPrice +
tokens.cacheCreateTokens * cacheCreatePrice) /
1_000_000
@@ -105,17 +141,22 @@ export function computePriceQuoteTurnMoney(
? price.costDiscount
: 0;
const amount = standardAmount * (1 - discount);
- const valueEstimate = price.source === 'subscription-reference';
+ const valueEstimate =
+ price.source === 'subscription-reference' ||
+ price.source === 'provider-reference' ||
+ price.source === 'user-override';
+ const estimateReasons =
+ price.source === 'subscription-reference'
+ ? (['subscription-value', 'reference-price'] as const)
+ : valueEstimate || price.approximate
+ ? (['reference-price'] as const)
+ : undefined;
const money: RegionalMoney = {
amount: Math.max(0, amount),
currency: price.currency,
approximate: price.approximate || valueEstimate,
kind: valueEstimate ? 'value-estimate' : 'actual-cost',
- ...(valueEstimate
- ? { estimateReasons: ['subscription-value', 'reference-price'] }
- : price.approximate
- ? { estimateReasons: ['reference-price'] }
- : {}),
+ ...(estimateReasons ? { estimateReasons: [...estimateReasons] } : {}),
};
// Gateway 报价的币种就是该账号的实际结算币种,原样记账才能与账单对账 —— 不做任何换算。
// 否则以 USD 结算的账号在 CN 构建上,turn 会被 USD_TO_CNY_FIXED_RATE 折成 CNY,而同一
@@ -138,7 +179,15 @@ export function resolveTurnCost(args: {
const { rawModel, tokens, sdkCostDelta, pricing, context } = args;
const model = normalizeModelIdForPricing(rawModel);
- if (context.billingRoute === 'subscription' || isSubscriptionDirectModel(model)) {
+ // An explicit provider API route is authoritative. User-defined providers may legitimately
+ // expose namespaced model ids such as `xai/grok-4.5`; treating the prefix alone as proof of a
+ // subscription would discard both the provider's SDK cost and the user's price override.
+ // Prefix inference remains the compatibility fallback for routes whose upstream is not an
+ // explicitly selected provider API (for example a bridge sub-agent inside an XD session).
+ if (
+ context.billingRoute === 'subscription' ||
+ (context.billingRoute !== 'provider-api' && isSubscriptionDirectModel(model))
+ ) {
return { model, money: null, source: 'subscription' };
}
@@ -172,11 +221,21 @@ export function resolveTurnCost(args: {
// 第三方供应商 / 未知路由:SDK 值是 USD 口径,投影到账本币种而不是构建区域,
// 否则 USD 结算账号上这些花费会变成 CNY 并被账本守卫丢弃。
const sdkAmount = Math.max(0, sdkCostDelta ?? 0);
- const money = sdkAmount > 0 ? usdToLedgerCurrency(sdkAmount, ledgerCurrency) : null;
+ if (sdkAmount > 0) {
+ return {
+ model,
+ money: usdToLedgerCurrency(sdkAmount, ledgerCurrency),
+ source: context.billingRoute === 'provider-api' ? 'sdk' : 'sdk-fallback',
+ };
+ }
+ const providerQuote =
+ context.billingRoute === 'provider-api'
+ ? getModelPriceQuote(pricing, context.providerId, model, 'claude-code')
+ : undefined;
return {
model,
- money,
- source: context.billingRoute === 'provider-api' ? 'sdk' : 'sdk-fallback',
+ money: providerQuote ? computePriceQuoteTurnMoney(tokens, providerQuote, ledgerCurrency) : null,
+ source: context.billingRoute === 'provider-api' ? 'reference' : 'sdk-fallback',
};
}
@@ -188,7 +247,10 @@ export interface ResolvedModelCost {
}
export interface ClaudeTurnCostResolution {
+ /** Actual provider/Gateway spend only. Never includes reference-price estimates. */
turnMoney: RegionalMoney | null;
+ /** Reference-price value only. Kept out of actual spend/session ledgers. */
+ estimatedTurnMoney: RegionalMoney | null;
perModel: ResolvedModelCost[];
}
@@ -198,7 +260,8 @@ export function resolveClaudeTurnCostSinks(
context: TurnPricingContext,
): ClaudeTurnCostResolution {
const perModel: ResolvedModelCost[] = [];
- const money: RegionalMoney[] = [];
+ const actualMoney: RegionalMoney[] = [];
+ const estimatedMoney: RegionalMoney[] = [];
for (const delta of modelDeltas) {
const tokens: TurnTokenDeltas = {
inputTokens: delta.inputTokensDelta,
@@ -219,11 +282,14 @@ export function resolveClaudeTurnCostSinks(
source: resolved.source,
deltas: tokens,
});
- if (resolved.money && resolved.money.amount > 0) money.push(resolved.money);
+ if (resolved.money && resolved.money.amount > 0) {
+ (resolved.money.kind === 'actual-cost' ? actualMoney : estimatedMoney).push(resolved.money);
+ }
}
- if (money.length === 0) return { turnMoney: null, perModel };
return {
- turnMoney: addRegionalMoney(money),
+ turnMoney: actualMoney.length > 0 ? addRegionalMoney(actualMoney) : null,
+ estimatedTurnMoney:
+ estimatedMoney.length > 0 ? addRegionalMoney(estimatedMoney) : null,
perModel,
};
}
@@ -235,11 +301,12 @@ export function resolveClaudeTurnCostSinks(
export function estimateClaudeSubscriptionTurnValue(
perModel: ResolvedModelCost[],
ledgerCurrency: MoneyCurrency,
+ pricing: ModelPricingCatalog | null | undefined = undefined,
): RegionalMoney | null {
const values: RegionalMoney[] = [];
for (const item of perModel) {
if (!isAnthropicModel(item.model) || item.money?.amount) continue;
- const quote = providerReferencePriceQuote('anthropic', item.model);
+ const quote = getModelPriceQuote(pricing, 'anthropic', item.model, 'claude-code');
if (!quote) continue;
const value = computePriceQuoteTurnMoney(item.deltas, quote, ledgerCurrency);
if (value && value.amount > 0) values.push(value);
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index 20e993e89f..0adeeb1836 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -24,16 +24,17 @@ import { getModelUsageSince, type DailyModelUsageRow } from '../localDb/dailyMod
import { getCurrentDbClientUserId } from '../localDb/client/current';
import { createLogger } from '../logger';
import {
+ getClaudeSubscriptionValuePrice,
+ getCodexProviderSubscriptionValuePrice,
getCodexSubscriptionValuePrice,
getModelPricing,
getSubscriptionDirectValuePrice,
isModelPricingRefreshInFlight,
+ readModelPriceOverridesSnapshot,
+ type ModelPriceOverridesSnapshot,
type ModelPricingMap,
} from './modelPricing';
import { computePriceQuoteTurnMoney } from './turnCostCalculator';
-import {
- getModelPriceQuote,
-} from '../../shared/modelPriceQuote.js';
import { currentLedgerCurrency } from './ledgerCurrency.js';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
@@ -225,6 +226,8 @@ export interface UsageHistoryDeps {
getAllSpendDays(): Promise<Array<{ day: string; money: RegionalMoney }>>;
getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]>;
getModelPricing(): Promise<ModelPricingMap | null>;
+ /** 覆盖记录快照,一次聚合读一份——历史重合并逐行读文件会在慢盘上拖垮 Main 线程。 */
+ getModelPriceOverridesSnapshot(): ModelPriceOverridesSnapshot;
isModelPricingRefreshInFlight(): boolean;
todayKey(): string;
}
@@ -233,6 +236,7 @@ const defaultDeps: UsageHistoryDeps = {
getAllSpendDays,
getModelUsageSince,
getModelPricing,
+ getModelPriceOverridesSnapshot: readModelPriceOverridesSnapshot,
isModelPricingRefreshInFlight,
todayKey: () => localDayKey(),
};
@@ -345,23 +349,27 @@ export function claudeSubscriptionUsageModelKey(model: string): string {
/**
* 订阅行的估算价选取,按 agent 分流:
- * - codex → 订阅直连(chatgpt/ / xai/)静态价 →
- * 既有 getCodexSubscriptionValuePrice(网关价 + OpenAI 静态兜底表)
- * - claude-code → 网关价表精确条目(带 cache 档价)→ Anthropic 家族牌价兜底
- * 两级都 miss → undefined(该行只显示 token,不臆造金额)。
+ * - codex → 订阅直连(chatgpt/ / xai/)registry 参考价 → OpenAI registry 参考价
+ * → Anthropic registry 参考价(Codex 显式选内置 anthropic 的 Claude.ai 订阅轮;
+ * 模型 id 只会命中各自 provider 的路由,依次尝试不会串价)
+ * - claude-code → Anthropic registry 参考价
+ * 各级都 miss → undefined(该行只显示 token,不臆造金额)。
*/
function getSubscriptionValuePriceFor(
agentKind: 'claude-code' | 'codex',
model: string,
pricing: ModelPricingMap | null,
+ at?: string | Date,
+ overrides?: ModelPriceOverridesSnapshot,
): ModelPriceQuote | undefined {
if (agentKind === 'codex') {
return (
- getSubscriptionDirectValuePrice(model) ??
- getCodexSubscriptionValuePrice(model, pricing)
+ getSubscriptionDirectValuePrice(model, 'codex', pricing, at, overrides) ??
+ getCodexSubscriptionValuePrice(model, pricing, at, overrides) ??
+ getCodexProviderSubscriptionValuePrice('anthropic', model, pricing, at, overrides)
);
}
- return getModelPriceQuote(pricing, 'anthropic', model);
+ return getClaudeSubscriptionValuePrice(model, pricing, at, overrides);
}
async function hydrateFromDisk(expectedOptsKey: string): Promise<UsageHistoryPayload | null> {
@@ -567,12 +575,17 @@ export async function readUsageHistoryWith(
}
const days = [...daysMap.values()].sort((a, b) => (a.day < b.day ? -1 : 1));
// pricing 在函数开头已与消费行并行取好(见那里的 race 注释)。
+ // 覆盖记录也在这里读一次快照:缺价检查、模型聚合、每日明细三条遍历共用,
+ // 避免历史重合并按 model-day 逐行 stat 覆盖文件。
+ const priceOverrides = deps.getModelPriceOverridesSnapshot();
const hasMissingPendingSubscriptionPrice = modelRows.some((r) =>
isSubscriptionUsageModel(r.model) &&
!getSubscriptionValuePriceFor(
r.agentKind === 'codex' ? 'codex' : 'claude-code',
displayModelName(r.model),
pricing,
+ r.day,
+ priceOverrides,
),
);
const estimatesPending =
@@ -580,6 +593,7 @@ export async function readUsageHistoryWith(
deps.isModelPricingRefreshInFlight();
const byKey = new Map<string, UsageHistoryModel>();
+ const subscriptionEstimatesByKey = new Map<string, RegionalMoney[]>();
let todayTokens = 0;
let last30DaysTokens = 0;
for (const row of modelRows) {
@@ -617,15 +631,25 @@ export async function readUsageHistoryWith(
agg.outputTokens += row.outputTokens;
agg.cacheReadTokens += row.cacheReadTokens;
agg.cacheCreateTokens += row.cacheCreateTokens;
- }
- for (const [key, m] of byKey) {
- const modelKey = key.slice(key.indexOf('\u0000') + 1);
- if (m.money.amount === 0 && isSubscriptionUsageModel(modelKey)) {
- m.estimatedMoney = computePriceQuoteTurnMoney(
- m,
- getSubscriptionValuePriceFor(m.agentKind, m.model, pricing),
+ if (row.money.amount === 0 && isSubscriptionUsageModel(row.model)) {
+ const estimate = computePriceQuoteTurnMoney(
+ row,
+ getSubscriptionValuePriceFor(agentKind, model, pricing, row.day, priceOverrides),
ledgerCurrency,
);
+ if (estimate?.amount) {
+ const estimates = subscriptionEstimatesByKey.get(key) ?? [];
+ estimates.push(estimate);
+ subscriptionEstimatesByKey.set(key, estimates);
+ }
+ }
+ }
+ for (const [key, m] of byKey) {
+ if (m.money.amount === 0) {
+ const estimates = subscriptionEstimatesByKey.get(key);
+ if (estimates?.length) {
+ m.estimatedMoney = addCompatibleRegionalMoney(estimates, ledgerCurrency);
+ }
}
}
const models = [...byKey.values()];
@@ -640,7 +664,7 @@ export async function readUsageHistoryWith(
apiMoney.amount === 0 && isSubscriptionUsageModel(row.model)
? (computePriceQuoteTurnMoney(
row,
- getSubscriptionValuePriceFor(agentKind, model, pricing),
+ getSubscriptionValuePriceFor(agentKind, model, pricing, row.day, priceOverrides),
ledgerCurrency,
) ?? zeroEstimate())
: zeroEstimate();
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f1a31ef029..1d5f075b38 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4280,6 +4280,19 @@ contextBridge.exposeInMainWorld('electronAPI', {
// configuration-and-overrides.md §4 的「删 override 跟随默认」语义。
| { kind: 'reset'; providerId: string },
): Promise<{ ok: true }> => ipcRenderer.invoke('maker:model-disable:set', input),
+ getModelPriceOverride: (
+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,
+ ): Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView> =>
+ ipcRenderer.invoke('maker:model-price-override:get', target),
+ setModelPriceOverride: (
+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,
+ desired: import('../shared/modelPriceOverride').ModelPriceOverrideDesiredQuote,
+ ): Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView> =>
+ ipcRenderer.invoke('maker:model-price-override:set', target, desired),
+ resetModelPriceOverride: (
+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,
+ ): Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView> =>
+ ipcRenderer.invoke('maker:model-price-override:reset', target),
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session。
openSessionInNewWindow: (sessionId: string): Promise<void> =>
diff --git a/apps/desktop/src/renderer/__tests__/modelDefinitionsDefaults.test.ts b/apps/desktop/src/renderer/__tests__/modelDefinitionsDefaults.test.ts
index ed391a3743..d82418d79e 100644
--- a/apps/desktop/src/renderer/__tests__/modelDefinitionsDefaults.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelDefinitionsDefaults.test.ts
@@ -9,6 +9,7 @@
* 决定(见 draftModelCalibration.test.ts),这里拿不到连接态与来源。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ModelRegistry } from '@cindy/model-providers';
beforeEach(() => {
vi.resetModules();
@@ -132,8 +133,8 @@ describe('getDefaultModelForVendor', () => {
// 占位不是「另一份产品默认」,只是目录还没到位时的同值影子。两者漂移就会出现首帧一个
// 模型、清单到位后换成另一个的跳变。
//
- // 只锁 cc:anthropic 的动态发现清单会被 overlayCindyMeta 用目录 sortOrder 覆盖,
- // 所以 meta 就是 cc tab 排序的权威。codex 侧不能这么锁,理由见下一条。
+ // 只锁 cc:anthropic 的动态发现清单会被 registry 用目录 sortOrder 覆盖,
+ // 所以 registry 就是 cc tab 排序的权威。codex 侧不能这么锁,理由见下一条。
//
// 展示名一起锁住:renderer 刻意不 import BUNDLED_CATALOG(会把整份目录 JSON 打进
// bundle,为一个瞬态 label 不值得),所以 label 只能写在代码里 —— 那就由这条断言保证
@@ -156,7 +157,7 @@ describe('getDefaultModelForVendor', () => {
it('codex 冷启动占位必须是目录里属 codex tab、默认可见、非折扣组的模型', async () => {
// 这里刻意**不锁「排序第一」**:codex tab 的 sortOrder 有两个互相矛盾的来源 ——
// · ChatGPT 订阅清单来自动态发现,按上游 priority 算(Sol→17、Terra→18、Luna→19);
- // · Cindy AI 网关清单按目录 meta 的静态值(Luna=17、Sol=18、Terra=19)。
+ // · Cindy AI 网关清单按 registry 的静态值(Luna=17、Sol=18、Terra=19)。
// 两套顺序对 GPT-5.6 三兄弟正好相反,于是「排序第一」会随用户连的是订阅还是网关而不同。
// 占位按订阅口径取(校准规则优先订阅供应商),锁死目录静态序会锁成另一个模型。
// 这个不一致本身是目录数据问题,待产品裁决后再收紧本条断言。
@@ -176,13 +177,26 @@ describe('getDefaultModelForVendor', () => {
});
interface BundledMetaEntry {
- agents?: string[];
+ agents?: readonly string[];
group?: string;
name?: string;
sortOrder?: number;
defaultEnabled?: boolean;
}
-function bundledMeta(catalog: { cindyModelMeta?: unknown }): Record<string, BundledMetaEntry> {
- return (catalog.cindyModelMeta as { models: Record<string, BundledMetaEntry> }).models;
+function bundledMeta(catalog: { modelRegistry?: ModelRegistry }): Record<string, BundledMetaEntry> {
+ const models: Record<string, BundledMetaEntry> = {};
+ for (const entry of catalog.modelRegistry?.models ?? []) {
+ for (const route of entry.routes) {
+ if (route.providerId !== 'xd') continue;
+ models[route.modelId] = {
+ agents: route.agents,
+ group: entry.group,
+ name: entry.name,
+ sortOrder: entry.sortOrder,
+ defaultEnabled: entry.defaultEnabled,
+ };
+ }
+ }
+ return models;
}
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index f868a60447..5b516cf93d 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -788,7 +788,12 @@ function ModelSelectorContentView({
(currentAgentKind
? resolveCurrentSourceId(providers, currentProviderId, id, currentAgentKind)
: null);
- const quote = getModelPriceQuote(pricing, effectiveProviderId, id);
+ const quote = getModelPriceQuote(
+ pricing,
+ effectiveProviderId,
+ id,
+ currentAgentKind ?? undefined,
+ );
if (effectiveProviderId === 'xd' && (!quote || quote.source === 'gateway')) {
if (!quote && pricing == null) return null;
const effectiveProvider = providers.find((provider) => provider.id === effectiveProviderId);
diff --git a/apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx b/apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx
new file mode 100644
index 0000000000..1031541010
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx
@@ -0,0 +1,360 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { AlertTriangle, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import type { AgentKind, ProviderView } from '@cindy/model-providers';
+
+import { cn } from '@/lib/utils';
+import { toast } from '@/lib/toast';
+
+import type {
+ ModelPriceOverrideDesiredQuote,
+ ModelPriceOverrideView,
+} from '../../../shared/modelPriceOverride';
+import type { UnionModelRow } from './UnifiedModelList';
+
+const AGENT_LABEL: Record<AgentKind, string> = {
+ 'claude-code': 'Claude Code',
+ codex: 'Codex',
+};
+
+interface Props {
+ provider: ProviderView;
+ row: UnionModelRow;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+interface FormState {
+ currency: 'USD' | 'CNY';
+ input: string;
+ output: string;
+ cacheRead: string;
+ cacheCreate: string;
+}
+
+const EMPTY_FORM: FormState = {
+ currency: 'USD',
+ input: '',
+ output: '',
+ cacheRead: '',
+ cacheCreate: '',
+};
+
+function formFromView(view: ModelPriceOverrideView): FormState {
+ const quote = view.effective ?? view.reference;
+ return quote
+ ? {
+ currency: quote.currency,
+ input: String(quote.inputPerMtok),
+ output: String(quote.outputPerMtok),
+ cacheRead: quote.cacheReadPerMtok === undefined ? '' : String(quote.cacheReadPerMtok),
+ cacheCreate: quote.cacheCreatePerMtok === undefined ? '' : String(quote.cacheCreatePerMtok),
+ }
+ : EMPTY_FORM;
+}
+
+function parseRequiredPrice(value: string): number | null {
+ if (!value.trim()) return null;
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
+}
+
+function parseOptionalPrice(value: string): number | null | 'invalid' {
+ if (!value.trim()) return null;
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 'invalid';
+}
+
+export function ModelPriceOverrideDialog({ provider, row, open, onOpenChange }: Props) {
+ const { t } = useTranslation();
+ const [agent, setAgent] = useState<AgentKind>(row.avail[0]);
+ const [view, setView] = useState<ModelPriceOverrideView | null>(null);
+ const [form, setForm] = useState<FormState>(EMPTY_FORM);
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+
+ const model = row.byAgent[agent];
+ const target = useMemo(
+ () => (model ? { providerId: provider.id, agent, modelId: model.id } : null),
+ [agent, model, provider.id],
+ );
+
+ // DESIGN.md §4:弹窗打开时焦点落主输入,而不是 Radix 默认的首个可聚焦元素(关闭按钮)。
+ const primaryInputRef = useRef<HTMLInputElement | null>(null);
+
+ // 弹窗关闭或目标切换后,在途 save/reset 的迟到响应必须整体作废:旧实例捕获的
+ // setView/onOpenChange(false) 会覆盖新目标的表单、甚至直接关掉刚打开的弹窗。
+ const mutationEpochRef = useRef(0);
+ useEffect(() => {
+ mutationEpochRef.current += 1;
+ }, [open, target]);
+ // UnifiedModelList 按行条件渲染本弹窗:换行会卸载重挂、换新实例,但旧实例的
+ // 在途 save/reset 闭包仍握着共享的 onOpenChange。卸载时同样作废 epoch,
+ // 迟到响应不得关掉新实例的弹窗或触发任何副作用。
+ useEffect(
+ () => () => {
+ mutationEpochRef.current += 1;
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (!open) return;
+ if (!row.avail.includes(agent)) setAgent(row.avail[0]);
+ }, [agent, open, row]);
+
+ useEffect(() => {
+ if (!open || !target) return;
+ let cancelled = false;
+ setLoading(true);
+ setView(null);
+ setForm(EMPTY_FORM);
+ void window.electronAPI.maker
+ .getModelPriceOverride(target)
+ .then((next) => {
+ if (cancelled) return;
+ setView(next);
+ setForm(formFromView(next));
+ })
+ .catch(() => {
+ if (!cancelled) toast.error(t('settings.providers.models.priceOverride.loadFailed'));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, target, t]);
+
+ const save = async () => {
+ if (!target || !view || loading) return;
+ const inputPerMtok = parseRequiredPrice(form.input);
+ const outputPerMtok = parseRequiredPrice(form.output);
+ const cacheReadPerMtok = parseOptionalPrice(form.cacheRead);
+ const cacheCreatePerMtok = parseOptionalPrice(form.cacheCreate);
+ if (
+ inputPerMtok === null ||
+ outputPerMtok === null ||
+ cacheReadPerMtok === 'invalid' ||
+ cacheCreatePerMtok === 'invalid'
+ ) {
+ toast.error(t('settings.providers.models.priceOverride.invalid'));
+ return;
+ }
+ const desired: ModelPriceOverrideDesiredQuote = {
+ currency: form.currency,
+ inputPerMtok,
+ outputPerMtok,
+ cacheReadPerMtok,
+ cacheCreatePerMtok,
+ };
+ setSaving(true);
+ const epoch = mutationEpochRef.current;
+ try {
+ const next = await window.electronAPI.maker.setModelPriceOverride(target, desired);
+ if (mutationEpochRef.current !== epoch) return;
+ setView(next);
+ setForm(formFromView(next));
+ toast.success(t('settings.providers.models.priceOverride.saved'));
+ onOpenChange(false);
+ } catch {
+ if (mutationEpochRef.current !== epoch) return;
+ toast.error(t('settings.providers.models.priceOverride.saveFailed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const reset = async () => {
+ if (!target) return;
+ setSaving(true);
+ const epoch = mutationEpochRef.current;
+ try {
+ const next = await window.electronAPI.maker.resetModelPriceOverride(target);
+ if (mutationEpochRef.current !== epoch) return;
+ setView(next);
+ setForm(formFromView(next));
+ toast.success(t('settings.providers.models.priceOverride.resetDone'));
+ } catch {
+ if (mutationEpochRef.current !== epoch) return;
+ toast.error(t('settings.providers.models.priceOverride.saveFailed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const fieldClass = cn(
+ 'h-9 w-full rounded-full border px-3 text-13 tabular-nums outline-none',
+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',
+ 'text-[var(--settings-section-title)] focus:border-[var(--focus-ring)]',
+ );
+
+ return (
+ <Dialog.Root open={open} onOpenChange={onOpenChange}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10001] bg-[var(--overlay-modal)]" />
+ <Dialog.Content
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[10001] w-[520px] max-w-[92vw]',
+ '-translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-xl',
+ 'border border-[var(--cmd-palette-border)] bg-[var(--cmd-palette-bg)]',
+ )}
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ primaryInputRef.current?.focus();
+ }}
+ >
+ <header className="flex items-start justify-between gap-4 px-5 pb-3 pt-4">
+ <div className="min-w-0">
+ <Dialog.Title className="truncate text-15 font-medium text-[var(--settings-section-title)]">
+ {t('settings.providers.models.priceOverride.title', { model: row.name })}
+ </Dialog.Title>
+ <Dialog.Description className="mt-1 text-12 leading-[1.45] text-[var(--settings-section-desc)]">
+ {t('settings.providers.models.priceOverride.description')}
+ </Dialog.Description>
+ </div>
+ <Dialog.Close asChild>
+ <button
+ type="button"
+ aria-label={t('settings.providers.models.priceOverride.close')}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)]"
+ >
+ <X size={15} />
+ </button>
+ </Dialog.Close>
+ </header>
+
+ <div className="flex flex-col gap-4 px-5 pb-5">
+ {row.avail.length > 1 && (
+ <div className="flex rounded-full bg-[var(--surface-chip)] p-0.5">
+ {row.avail.map((candidate) => (
+ <button
+ key={candidate}
+ type="button"
+ disabled={saving}
+ onClick={() => setAgent(candidate)}
+ className={cn(
+ 'h-7 flex-1 rounded-full text-12 font-medium transition-colors disabled:cursor-default',
+ candidate === agent
+ ? 'bg-[var(--surface-elevated)] text-[var(--settings-section-title)]'
+ : 'text-[var(--text-secondary)]',
+ )}
+ >
+ {AGENT_LABEL[candidate]}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {view?.conflict && (
+ <div className="flex gap-2 rounded-lg bg-[var(--warning-bg-soft)] px-3 py-2.5">
+ <AlertTriangle size={15} className="mt-0.5 shrink-0 text-[var(--warning-fg)]" />
+ <span className="text-12 leading-[1.45] text-[var(--text-secondary)]">
+ {t('settings.providers.models.priceOverride.conflict')}
+ </span>
+ </div>
+ )}
+
+ <div
+ className={cn('grid grid-cols-2 gap-3', loading && 'pointer-events-none opacity-60')}
+ >
+ <label className="col-span-2 flex flex-col gap-1.5">
+ <span className="text-12 font-medium text-[var(--text-secondary)]">
+ {t('settings.providers.models.priceOverride.currency')}
+ </span>
+ <select
+ value={form.currency}
+ onChange={(event) =>
+ setForm((current) => ({
+ ...current,
+ currency: event.target.value as 'USD' | 'CNY',
+ }))
+ }
+ className={fieldClass}
+ >
+ {(view?.allowedCurrencies ?? ['USD']).map((currency) => (
+ <option key={currency} value={currency}>
+ {currency}
+ </option>
+ ))}
+ </select>
+ </label>
+ {(
+ [
+ ['input', 'input'],
+ ['output', 'output'],
+ ['cacheRead', 'cacheRead'],
+ ['cacheCreate', 'cacheWrite'],
+ ] as const
+ ).map(([field, label]) => (
+ <label key={field} className="flex flex-col gap-1.5">
+ <span className="text-12 font-medium text-[var(--text-secondary)]">
+ {t(`settings.providers.models.priceOverride.${label}`)}
+ </span>
+ <input
+ ref={field === 'input' ? primaryInputRef : undefined}
+ type="number"
+ min="0"
+ step="any"
+ value={form[field]}
+ placeholder={field.startsWith('cache') ? '—' : '0'}
+ onChange={(event) =>
+ setForm((current) => ({ ...current, [field]: event.target.value }))
+ }
+ className={fieldClass}
+ />
+ </label>
+ ))}
+ </div>
+
+ <p className="text-11 leading-[1.45] text-[var(--text-tertiary)]">
+ {t('settings.providers.models.priceOverride.unit')}
+ {view?.registryUpdatedAt
+ ? ` · ${t('settings.providers.models.priceOverride.registryDate', {
+ date: view.registryUpdatedAt.slice(0, 10),
+ })}`
+ : ''}
+ </p>
+
+ <footer className="flex items-center justify-between border-t border-[var(--border-default)] pt-3">
+ <div>
+ {view?.override && (
+ <button
+ type="button"
+ onClick={() => void reset()}
+ disabled={saving}
+ className="h-8 rounded-full px-3 text-12 font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] disabled:opacity-50"
+ >
+ {t('settings.providers.models.priceOverride.reset')}
+ </button>
+ )}
+ </div>
+ <div className="flex gap-2">
+ <Dialog.Close asChild>
+ <button
+ type="button"
+ className="h-8 rounded-full border border-[var(--settings-btn-secondary-border)] px-3.5 text-12 font-medium text-[var(--settings-btn-secondary-text)] hover:bg-[var(--surface-hover)]"
+ >
+ {t('settings.providers.models.priceOverride.cancel')}
+ </button>
+ </Dialog.Close>
+ <button
+ type="button"
+ onClick={() => void save()}
+ disabled={loading || saving || !view}
+ className="h-8 rounded-full bg-[var(--settings-btn-primary-bg)] px-3.5 text-12 font-medium text-[var(--settings-btn-primary-text)] disabled:opacity-50"
+ >
+ {t('settings.providers.models.priceOverride.save')}
+ </button>
+ </div>
+ </footer>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
index 25cb8a6e5a..b484b51c7f 100644
--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
@@ -50,6 +50,7 @@ import {
setModelVisibility,
useModelVisibilityVersion,
} from '@/state/modelVisibilityPrefs';
+import { ModelPriceOverrideDialog } from './ModelPriceOverrideDialog';
import { isAgentSelectableModel } from '@cindy/model-providers';
import type { AgentKind, CatalogModel, ProviderView } from '@cindy/model-providers';
@@ -290,8 +291,10 @@ export function UnifiedModelList({
// useProviders 快照刷新,期间(可能上百毫秒,含凭证库读取)用本地覆盖顶住 —— 行在
// 分组与「已停用」分区之间的迁移一次到位,不出现回跳帧(规则 7)。新快照到达即清空。
const [pendingDisabled, setPendingDisabled] = useState<Record<string, boolean>>({});
+ const [priceRow, setPriceRow] = useState<UnionModelRow | null>(null);
useEffect(() => {
setPendingDisabled({});
+ setPriceRow(null);
}, [provider]);
// 折叠态:分组用 ModelCategory 作 key,「已停用」分区用 DISABLED_GROUP_KEY(默认展开)。
@@ -484,6 +487,12 @@ export function UnifiedModelList({
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ {provider.id !== 'xd' &&
+ !isCapabilityRow(row, provider.source === 'user') && (
+ <DropdownMenuItem onClick={() => setPriceRow(row)}>
+ {t('settings.providers.models.priceOverride.menu')}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={() => setRowDisabled(row, true)}>
{t('settings.providers.models.disableModel')}
</DropdownMenuItem>
@@ -825,6 +834,16 @@ export function UnifiedModelList({
);
})()}
</div>
+ {priceRow && (
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={priceRow}
+ open
+ onOpenChange={(next) => {
+ if (!next) setPriceRow(null);
+ }}
+ />
+ )}
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ModelPriceOverrideDialog.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ModelPriceOverrideDialog.test.tsx
new file mode 100644
index 0000000000..ff94acdf4d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/ModelPriceOverrideDialog.test.tsx
@@ -0,0 +1,333 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { CatalogModel, ProviderView } from '@cindy/model-providers';
+
+import type { ModelPriceOverrideView } from '../../../../shared/modelPriceOverride';
+import { ModelPriceOverrideDialog } from '../ModelPriceOverrideDialog';
+import type { UnionModelRow } from '../UnifiedModelList';
+
+const translate = (key: string) => key;
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: translate }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+const provider = {
+ id: 'openrouter',
+ name: 'OpenRouter',
+ connected: true,
+} as unknown as ProviderView;
+
+function row(modelId: string): UnionModelRow {
+ const model = {
+ id: modelId,
+ name: modelId,
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ } as CatalogModel;
+ return {
+ id: modelId,
+ name: modelId,
+ byAgent: { codex: model },
+ avail: ['codex'],
+ };
+}
+
+function priceView(
+ modelId: string,
+ agent: 'claude-code' | 'codex' = 'codex',
+ hasOverride = false,
+): ModelPriceOverrideView {
+ return {
+ target: { providerId: 'openrouter', agent, modelId },
+ editable: true,
+ reference: {
+ providerId: 'openrouter',
+ modelId,
+ currency: 'USD',
+ source: 'provider-reference',
+ approximate: false,
+ inputPerMtok: 1,
+ outputPerMtok: 4,
+ },
+ effective: {
+ providerId: 'openrouter',
+ modelId,
+ currency: 'USD',
+ source: 'provider-reference',
+ approximate: false,
+ inputPerMtok: 1,
+ outputPerMtok: 4,
+ },
+ override: hasOverride ? { currency: 'USD', inputPerMtok: 2, outputPerMtok: 8 } : null,
+ conflict: false,
+ registryUpdatedAt: null,
+ allowedCurrencies: ['USD'],
+ };
+}
+
+describe('ModelPriceOverrideDialog', () => {
+ const getModelPriceOverride = vi.fn();
+ const setModelPriceOverride = vi.fn();
+ const resetModelPriceOverride = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getModelPriceOverride.mockReset();
+ setModelPriceOverride.mockReset();
+ resetModelPriceOverride.mockReset();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: {
+ getModelPriceOverride,
+ setModelPriceOverride,
+ resetModelPriceOverride,
+ },
+ };
+ });
+
+ it('clears and disables the stale form when loading a new target fails', async () => {
+ getModelPriceOverride
+ .mockResolvedValueOnce(priceView('model-a'))
+ .mockRejectedValueOnce(new Error('catalog unavailable'));
+
+ const { getByRole, rerender } = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-a')}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+
+ const save = getByRole('button', {
+ name: 'settings.providers.models.priceOverride.save',
+ });
+ await waitFor(() => expect(save.hasAttribute('disabled')).toBe(false));
+ expect(document.querySelector<HTMLInputElement>('input[type="number"]')?.value).toBe('1');
+
+ rerender(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-b')}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+
+ await waitFor(() => expect(getModelPriceOverride).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(save.hasAttribute('disabled')).toBe(true));
+ expect(document.querySelector<HTMLInputElement>('input[type="number"]')?.value).toBe('');
+
+ fireEvent.click(save);
+ expect(setModelPriceOverride).not.toHaveBeenCalled();
+ });
+
+ it('uses pill geometry for the currency selector and price inputs', async () => {
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-a'));
+
+ render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-a')}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+
+ await waitFor(() => expect(getModelPriceOverride).toHaveBeenCalledOnce());
+ const controls = Array.from(document.querySelectorAll('select, input[type="number"]'));
+ expect(controls).toHaveLength(5);
+ for (const control of controls) {
+ expect(control.classList.contains('rounded-full')).toBe(true);
+ expect(control.classList.contains('rounded-lg')).toBe(false);
+ }
+ });
+
+ it('does not add an unregistered shadow to the runtime segmented control', async () => {
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-a'));
+ const claudeModel = row('model-a').byAgent.codex!;
+ const dualRuntimeRow: UnionModelRow = {
+ ...row('model-a'),
+ byAgent: { 'claude-code': claudeModel, codex: claudeModel },
+ avail: ['claude-code', 'codex'],
+ };
+
+ const { getByRole } = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={dualRuntimeRow}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+
+ await waitFor(() => expect(getModelPriceOverride).toHaveBeenCalledOnce());
+ expect(getByRole('button', { name: 'Claude Code' }).classList.contains('shadow-sm')).toBe(false);
+ expect(getByRole('button', { name: 'Codex' }).classList.contains('shadow-sm')).toBe(false);
+ });
+
+ it('prevents switching runtime while a reset response is pending', async () => {
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-a', 'claude-code', true));
+ let finishReset: ((view: ModelPriceOverrideView) => void) | undefined;
+ resetModelPriceOverride.mockReturnValueOnce(
+ new Promise<ModelPriceOverrideView>((resolve) => {
+ finishReset = resolve;
+ }),
+ );
+ const claudeModel = row('model-a').byAgent.codex!;
+ const dualRuntimeRow: UnionModelRow = {
+ ...row('model-a'),
+ byAgent: { 'claude-code': claudeModel, codex: claudeModel },
+ avail: ['claude-code', 'codex'],
+ };
+
+ const { getByRole } = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={dualRuntimeRow}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+
+ const reset = await waitFor(() =>
+ getByRole('button', { name: 'settings.providers.models.priceOverride.reset' }),
+ );
+ fireEvent.click(reset);
+ await waitFor(() => expect(resetModelPriceOverride).toHaveBeenCalledOnce());
+
+ const codex = getByRole('button', { name: 'Codex' });
+ expect(codex.hasAttribute('disabled')).toBe(true);
+ fireEvent.click(codex);
+ expect(getModelPriceOverride).toHaveBeenCalledOnce();
+
+ finishReset?.(priceView('model-a', 'claude-code'));
+ await waitFor(() => expect(codex.hasAttribute('disabled')).toBe(false));
+ });
+
+ it('moves initial focus to the primary price input', async () => {
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-a'));
+ const { getByLabelText } = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-a')}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ getByLabelText('settings.providers.models.priceOverride.input'),
+ ),
+ );
+ });
+
+ it('invalidates a pending save when the dialog instance unmounts', async () => {
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-a'));
+ let finishSave: ((view: ModelPriceOverrideView) => void) | undefined;
+ setModelPriceOverride.mockReturnValueOnce(
+ new Promise<ModelPriceOverrideView>((resolve) => {
+ finishSave = resolve;
+ }),
+ );
+ const onOpenChangeA = vi.fn();
+ const first = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-a')}
+ open
+ onOpenChange={onOpenChangeA}
+ />,
+ );
+ const save = await waitFor(() =>
+ first.getByRole('button', { name: 'settings.providers.models.priceOverride.save' }),
+ );
+ fireEvent.click(save);
+ await waitFor(() => expect(setModelPriceOverride).toHaveBeenCalledOnce());
+
+ // 生产路径:UnifiedModelList 换行时条件渲染会卸载 A、另挂全新实例 B。
+ first.unmount();
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-b'));
+ const second = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-b')}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ await waitFor(() => expect(getModelPriceOverride).toHaveBeenCalledTimes(2));
+
+ // A 的迟到响应落地:不得触发旧实例的 onOpenChange(false),B 的表单不受影响。
+ finishSave?.(priceView('model-a', 'codex', true));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(onOpenChangeA).not.toHaveBeenCalled();
+ expect(
+ (second.getByLabelText('settings.providers.models.priceOverride.input') as HTMLInputElement)
+ .value,
+ ).toBe('1');
+ });
+
+ it('discards a late save response after the dialog is closed and reopened', async () => {
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-a'));
+ let finishSave: ((view: ModelPriceOverrideView) => void) | undefined;
+ setModelPriceOverride.mockReturnValueOnce(
+ new Promise<ModelPriceOverrideView>((resolve) => {
+ finishSave = resolve;
+ }),
+ );
+ const onOpenChange = vi.fn();
+ const { getByRole, getByLabelText, rerender } = render(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-a')}
+ open
+ onOpenChange={onOpenChange}
+ />,
+ );
+ const save = await waitFor(() =>
+ getByRole('button', { name: 'settings.providers.models.priceOverride.save' }),
+ );
+ fireEvent.click(save);
+ await waitFor(() => expect(setModelPriceOverride).toHaveBeenCalledOnce());
+
+ // 保存尚未返回时关闭弹窗,随即打开模型 B。
+ rerender(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-a')}
+ open={false}
+ onOpenChange={onOpenChange}
+ />,
+ );
+ getModelPriceOverride.mockResolvedValueOnce(priceView('model-b'));
+ rerender(
+ <ModelPriceOverrideDialog
+ provider={provider}
+ row={row('model-b')}
+ open
+ onOpenChange={onOpenChange}
+ />,
+ );
+ await waitFor(() => expect(getModelPriceOverride).toHaveBeenCalledTimes(2));
+
+ // A 的迟到响应(带 override 2/8)落地:不得关闭 B 的弹窗,也不得覆写 B 的表单。
+ finishSave?.(priceView('model-a', 'codex', true));
+ const saveB = getByRole('button', {
+ name: 'settings.providers.models.priceOverride.save',
+ });
+ await waitFor(() => expect(saveB.hasAttribute('disabled')).toBe(false));
+ expect(
+ (getByLabelText('settings.providers.models.priceOverride.input') as HTMLInputElement).value,
+ ).toBe('1');
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 128111be29..ae14e332df 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1421,7 +1421,29 @@
"capabilityGroupHint": "Not shown in the chat model picker; used only by features like image generation.",
"accessWriteFailed": "Couldn't save the change. Please try again.",
"disabledGroup": "Disabled",
- "enableAllModels": "Enable All"
+ "enableAllModels": "Enable All",
+ "priceOverride": {
+ "menu": "Edit API Price Estimate",
+ "title": "{{model}} API Price Estimate",
+ "description": "Used only to estimate usage on your own API or subscription route. This does not change the provider’s bill.",
+ "currency": "Currency",
+ "input": "Input",
+ "output": "Output",
+ "cacheRead": "Cache read",
+ "cacheWrite": "Cache write",
+ "unit": "Price per 1M tokens. Leave cache fields blank when they are not billed separately.",
+ "registryDate": "Reference updated {{date}}",
+ "conflict": "The remote reference price changed. Your local estimate is still in use; review it or reset to the new reference.",
+ "reset": "Reset to Current Reference",
+ "resetDone": "Restored the current reference price",
+ "save": "Save",
+ "cancel": "Cancel",
+ "close": "Close",
+ "saved": "API price estimate saved",
+ "invalid": "Enter valid non-negative input and output prices",
+ "loadFailed": "Couldn’t load the price estimate. Please try again.",
+ "saveFailed": "Couldn’t save the price estimate. Please try again."
+ }
},
"genericOAuth": {
"subtitle": "Subscription sign-in (OAuth)",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a110e920cf..04db03876d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1420,7 +1420,29 @@
"capabilityGroupHint": "チャットのモデル選択には表示されず、画像生成などの機能でのみ使用されます。",
"accessWriteFailed": "変更を保存できませんでした。もう一度お試しください。",
"disabledGroup": "無効",
- "enableAllModels": "すべて有効にする"
+ "enableAllModels": "すべて有効にする",
+ "priceOverride": {
+ "menu": "API 料金見積もりを編集",
+ "title": "{{model}} の API 料金見積もり",
+ "description": "自分の API またはサブスクリプション経路の使用量見積もりにのみ使われ、プロバイダーの実際の請求は変わりません。",
+ "currency": "通貨",
+ "input": "入力",
+ "output": "出力",
+ "cacheRead": "キャッシュ読み取り",
+ "cacheWrite": "キャッシュ書き込み",
+ "unit": "100 万トークンあたりの料金。キャッシュが個別課金されない場合は空欄にしてください。",
+ "registryDate": "参考料金の更新日 {{date}}",
+ "conflict": "リモートの参考料金が更新されました。ローカル見積もりは引き続き優先されます。確認するか新しい参考料金に戻してください。",
+ "reset": "現在の参考料金に戻す",
+ "resetDone": "現在の参考料金に戻しました",
+ "save": "保存",
+ "cancel": "キャンセル",
+ "close": "閉じる",
+ "saved": "API 料金見積もりを保存しました",
+ "invalid": "0 以上の有効な入力・出力料金を入力してください",
+ "loadFailed": "料金見積もりを読み込めませんでした。もう一度お試しください。",
+ "saveFailed": "料金見積もりを保存できませんでした。もう一度お試しください。"
+ }
},
"genericOAuth": {
"subtitle": "サブスクリプション認証(OAuth)",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 354de0fe88..33fac30bf7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1420,7 +1420,29 @@
"capabilityGroupHint": "대화 모델 선택에는 표시되지 않으며, 이미지 생성 등 기능에서만 사용됩니다.",
"accessWriteFailed": "변경 사항을 저장하지 못했습니다. 다시 시도해 주세요.",
"disabledGroup": "비활성화됨",
- "enableAllModels": "모두 활성화"
+ "enableAllModels": "모두 활성화",
+ "priceOverride": {
+ "menu": "API 가격 추정치 편집",
+ "title": "{{model}} API 가격 추정치",
+ "description": "내 API 또는 구독 경로의 사용량을 추정할 때만 사용되며 제공자의 실제 청구 금액은 변경하지 않습니다.",
+ "currency": "통화",
+ "input": "입력",
+ "output": "출력",
+ "cacheRead": "캐시 읽기",
+ "cacheWrite": "캐시 쓰기",
+ "unit": "100만 토큰당 가격입니다. 캐시가 별도로 과금되지 않으면 비워 두세요.",
+ "registryDate": "참고 가격 업데이트 {{date}}",
+ "conflict": "원격 참고 가격이 변경되었습니다. 로컬 추정치는 계속 우선 적용됩니다. 검토하거나 새 참고 가격으로 재설정하세요.",
+ "reset": "현재 참고 가격으로 재설정",
+ "resetDone": "현재 참고 가격으로 복원했습니다",
+ "save": "저장",
+ "cancel": "취소",
+ "close": "닫기",
+ "saved": "API 가격 추정치를 저장했습니다",
+ "invalid": "0 이상의 올바른 입력 및 출력 가격을 입력하세요",
+ "loadFailed": "가격 추정치를 불러오지 못했습니다. 다시 시도하세요.",
+ "saveFailed": "가격 추정치를 저장하지 못했습니다. 다시 시도하세요."
+ }
},
"genericOAuth": {
"subtitle": "구독 인증 로그인 (OAuth)",
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 9ab83c4dac..35bbe49655 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1420,7 +1420,29 @@
"capabilityGroupHint": "不会出现在对话模型选择中,仅供图像生成等功能使用",
"accessWriteFailed": "停用设置未能保存,请重试",
"disabledGroup": "已停用",
- "enableAllModels": "全部启用"
+ "enableAllModels": "全部启用",
+ "priceOverride": {
+ "menu": "编辑 API 估价",
+ "title": "{{model}} API 估价",
+ "description": "仅用于估算你自己的 API 或订阅通道用量,不会改变供应商的实际账单。",
+ "currency": "币种",
+ "input": "输入",
+ "output": "输出",
+ "cacheRead": "缓存读取",
+ "cacheWrite": "缓存写入",
+ "unit": "每 100 万 token 的价格;缓存不单独计费时留空。",
+ "registryDate": "参考价更新于 {{date}}",
+ "conflict": "线上参考价已更新,你的本地估价仍会保留并优先生效。请检查或恢复为新的参考价。",
+ "reset": "恢复当前参考价",
+ "resetDone": "已恢复当前参考价",
+ "save": "保存",
+ "cancel": "取消",
+ "close": "关闭",
+ "saved": "API 估价已保存",
+ "invalid": "请输入有效且不小于 0 的输入、输出价格",
+ "loadFailed": "API 估价加载失败,请重试",
+ "saveFailed": "API 估价保存失败,请重试"
+ }
},
"genericOAuth": {
"subtitle": "订阅授权登录(OAuth)",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 086da185d3..c9257aeb09 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4039,6 +4039,16 @@ interface ElectronAPI {
// reset = 恢复默认:删除该供应商整组停用 override(含指向已下架模型的陈旧条目)。
| { kind: 'reset'; providerId: string },
) => Promise<{ ok: true }>;
+ getModelPriceOverride: (
+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,
+ ) => Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView>;
+ setModelPriceOverride: (
+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,
+ desired: import('../shared/modelPriceOverride').ModelPriceOverrideDesiredQuote,
+ ) => Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView>;
+ resetModelPriceOverride: (
+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,
+ ) => Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView>;
// 「在新窗口打开」会话多开
openSessionInNewWindow: (sessionId: string) => Promise<void>;
diff --git a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
index 77a723d2e1..fb37670994 100644
--- a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
+++ b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, it } from 'vitest';
+import type { ModelRegistry } from '@cindy/model-providers';
import type { ModelAccessGatewayModel } from '../modelAccess.js';
-import { gatewayPricingCatalog } from '../modelPriceQuote.js';
+import {
+ gatewayPricingCatalog,
+ providerReferencePriceQuote,
+ registryPricingCatalog,
+} from '../modelPriceQuote.js';
function model(
id: string,
@@ -67,3 +72,127 @@ describe('gatewayPricingCatalog', () => {
});
});
});
+
+describe('registryPricingCatalog', () => {
+ it('preserves the bounds of a single reference-price interval', () => {
+ const registry: ModelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models: [
+ {
+ id: 'xai/grok-code-fast',
+ name: 'Grok Code Fast',
+ routes: [
+ {
+ providerId: 'xai',
+ modelId: 'grok-code-fast',
+ agents: ['codex'],
+ referencePrices: [
+ {
+ currency: 'USD',
+ variant: 'standard',
+ maxInputTokens: 200_000,
+ inputPerMtok: 0.2,
+ outputPerMtok: 1.5,
+ effectiveFrom: '2026-01-01',
+ source: {
+ kind: 'provider-official',
+ url: 'https://example.test/pricing',
+ verifiedAt: '2026-07-31',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ expect(providerReferencePriceQuote('xai', 'grok-code-fast', registry)).toMatchObject({
+ inputTokenPriceBands: [
+ {
+ minInputTokens: 0,
+ maxInputTokens: 200_000,
+ inputPerMtok: 0.2,
+ outputPerMtok: 1.5,
+ },
+ ],
+ });
+ });
+
+ it('never treats a public XD reference as the Cindy Gateway sale price', () => {
+ const registry: ModelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models: [
+ {
+ id: 'test/model',
+ name: 'Test Model',
+ routes: [
+ {
+ providerId: 'xd',
+ modelId: 'test-model',
+ agents: ['claude-code'],
+ referencePrices: [
+ {
+ currency: 'USD',
+ variant: 'standard',
+ inputPerMtok: 1,
+ outputPerMtok: 2,
+ effectiveFrom: '2026-01-01',
+ source: {
+ kind: 'provider-official',
+ url: 'https://example.test/pricing',
+ verifiedAt: '2026-07-31',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ expect(registryPricingCatalog(registry)).toEqual({});
+ });
+
+ it('preserves the currency declared by a provider reference price', () => {
+ const registry: ModelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models: [
+ {
+ id: 'test/cny-model',
+ name: 'CNY Model',
+ routes: [
+ {
+ providerId: 'custom-cn',
+ modelId: 'cny-model',
+ agents: ['codex'],
+ referencePrices: [
+ {
+ currency: 'CNY',
+ variant: 'standard',
+ inputPerMtok: 7,
+ outputPerMtok: 21,
+ effectiveFrom: '2026-01-01',
+ source: {
+ kind: 'provider-official',
+ url: 'https://example.test/pricing',
+ verifiedAt: '2026-07-31',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ expect(registryPricingCatalog(registry)['custom-cn']?.['cny-model']).toMatchObject({
+ currency: 'CNY',
+ inputPerMtok: 7,
+ outputPerMtok: 21,
+ });
+ });
+});
diff --git a/apps/desktop/src/shared/claudeSubscriptionValue.ts b/apps/desktop/src/shared/claudeSubscriptionValue.ts
deleted file mode 100644
index c25d7f9546..0000000000
--- a/apps/desktop/src/shared/claudeSubscriptionValue.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * claudeSubscriptionValue — Claude 订阅(Anthropic OAuth)会话的「本会话价值」估值定价。
- *
- * 订阅会话没有真实 API 账单(SDK 自报 cost=0),chip 上显示的 $ 是「这轮用量按
- * Anthropic API 牌价折算值多少钱」的参考价值,与 `sessions.total_cost_usd`(真实
- * spend)严格分离 —— 口径与 Codex 订阅估值(shared/codexSubscriptionValue.ts)一致。
- *
- * 选价顺序(main/register.ts 消费):
- * 1. LiteLLM 网关价表的精确 model id 条目(带 cache 读写档价,最准)
- * 2. 本表按模型家族兜底(网关离线 / 冷启动 / 无该行时)
- * 两级都 miss → 本轮不显示估值(绝不用 0 或错价误导)。
- */
-
-import { claudeModelFamily } from './claudeSubscriptionUsage';
-
-/** 与 main/usage/modelPricing 的 ModelPrice 同形(shared 不 import main,自declare)。 */
-export interface ClaudeSubscriptionValuePrice {
- inputUsdPerMtok: number;
- outputUsdPerMtok: number;
- cacheReadUsdPerMtok?: number;
- cacheCreateUsdPerMtok?: number;
-}
-
-/**
- * Anthropic 公开牌价(USD / Mtok),按模型家族。cacheRead = 0.1x input,
- * cacheCreate = 1.25x input(5m TTL 档),与 platform.claude.com 定价页一致。
- * 家族维度(而非精确版本号)是有意的:版本迭代(4-8 → 4-9)通常沿用同代牌价,
- * 精确价优先走网关价表,这里只兜底。
- */
-export const CLAUDE_SUBSCRIPTION_VALUE_PRICING_BY_FAMILY: Record<
- string,
- ClaudeSubscriptionValuePrice
-> = {
- fable: { inputUsdPerMtok: 10, outputUsdPerMtok: 50, cacheReadUsdPerMtok: 1, cacheCreateUsdPerMtok: 12.5 },
- mythos: { inputUsdPerMtok: 10, outputUsdPerMtok: 50, cacheReadUsdPerMtok: 1, cacheCreateUsdPerMtok: 12.5 },
- opus: { inputUsdPerMtok: 5, outputUsdPerMtok: 25, cacheReadUsdPerMtok: 0.5, cacheCreateUsdPerMtok: 6.25 },
- sonnet: { inputUsdPerMtok: 3, outputUsdPerMtok: 15, cacheReadUsdPerMtok: 0.3, cacheCreateUsdPerMtok: 3.75 },
- haiku: { inputUsdPerMtok: 1, outputUsdPerMtok: 5, cacheReadUsdPerMtok: 0.1, cacheCreateUsdPerMtok: 1.25 },
-};
-
-/** 归一化 model id → 家族兜底价;未识别家族 → undefined(调用方跳过本轮估值)。 */
-export function getClaudeSubscriptionValueFallbackPrice(
- normalizedModel: string,
-): ClaudeSubscriptionValuePrice | undefined {
- const family = claudeModelFamily(normalizedModel);
- if (!family) return undefined;
- return CLAUDE_SUBSCRIPTION_VALUE_PRICING_BY_FAMILY[family];
-}
diff --git a/apps/desktop/src/shared/codexSubscriptionValue.ts b/apps/desktop/src/shared/codexSubscriptionValue.ts
index 5f9abefa55..810b60f4b4 100644
--- a/apps/desktop/src/shared/codexSubscriptionValue.ts
+++ b/apps/desktop/src/shared/codexSubscriptionValue.ts
@@ -1,6 +1,6 @@
import type { TurnUsageDetails } from './turnUsageDetails';
-/** Price shape used only for Codex OAuth subscription value estimates. */
+/** Historical price shape used only to repair already-persisted Codex estimates. */
export interface CodexSubscriptionValuePrice {
inputUsdPerMtok: number;
outputUsdPerMtok: number;
@@ -9,10 +9,11 @@ export interface CodexSubscriptionValuePrice {
}
/**
- * Codex OAuth subscription sessions do not have a real API bill. This table is
- * the reference "session value" display price, not `sessions.total_cost_usd`.
+ * Historical rates that earlier app versions could have used when persisting
+ * the stale cache-as-input estimate. Live estimates no longer read this table:
+ * they use the versioned model registry and local visual overrides.
*/
-export const CODEX_SUBSCRIPTION_VALUE_PRICING: Record<string, CodexSubscriptionValuePrice> = {
+const PERSISTED_CODEX_ESTIMATE_PRICING: Record<string, CodexSubscriptionValuePrice> = {
// GPT-5.6 (2026-07-09 GA): cache read = 10% input; 自 5.6 起 cache write 按官方
// 1.25x uncached input 计费 (此前 GPT 系列自动缓存写入不加价, 故老条目不挂该档)。
'gpt-5.6-sol': { inputUsdPerMtok: 5, cacheReadUsdPerMtok: 0.5, cacheCreateUsdPerMtok: 6.25, outputUsdPerMtok: 30 },
@@ -47,7 +48,7 @@ export function estimateCodexSubscriptionValueFromTurnUsage(
const model = detailsModel !== 'unknown'
? detailsModel
: normalizeCodexSubscriptionValueModelId(modelOverride);
- const price = CODEX_SUBSCRIPTION_VALUE_PRICING[model];
+ const price = PERSISTED_CODEX_ESTIMATE_PRICING[model];
if (!price) return null;
const inputTokens = Math.max(0, details.inputTokens || 0);
const outputTokens = Math.max(0, details.outputTokens || 0);
@@ -81,7 +82,7 @@ export function resolveStaleCodexSubscriptionValueEstimate(
const model = detailsModel !== 'unknown'
? detailsModel
: normalizeCodexSubscriptionValueModelId(modelOverride);
- const price = CODEX_SUBSCRIPTION_VALUE_PRICING[model];
+ const price = PERSISTED_CODEX_ESTIMATE_PRICING[model];
if (!price) return null;
const inputTokens = Math.max(0, details.inputTokens || 0);
diff --git a/apps/desktop/src/shared/modelPriceOverride.ts b/apps/desktop/src/shared/modelPriceOverride.ts
new file mode 100644
index 0000000000..e96f2b0e3c
--- /dev/null
+++ b/apps/desktop/src/shared/modelPriceOverride.ts
@@ -0,0 +1,38 @@
+import type { AgentKind } from '@cindy/model-providers';
+
+import type { ModelPriceQuote, MoneyCurrency } from './regionalMoney.js';
+
+export interface ModelPriceOverrideTarget {
+ providerId: string;
+ agent: AgentKind;
+ modelId: string;
+}
+
+/** Sparse local patch. Missing fields continue to follow the current remote reference price. */
+export interface ModelPriceOverrideValues {
+ currency?: MoneyCurrency;
+ inputPerMtok?: number;
+ outputPerMtok?: number;
+ cacheReadPerMtok?: number | null;
+ cacheCreatePerMtok?: number | null;
+}
+
+export interface ModelPriceOverrideDesiredQuote {
+ currency: MoneyCurrency;
+ inputPerMtok: number;
+ outputPerMtok: number;
+ cacheReadPerMtok?: number | null;
+ cacheCreatePerMtok?: number | null;
+}
+
+export interface ModelPriceOverrideView {
+ target: ModelPriceOverrideTarget;
+ editable: boolean;
+ reference: ModelPriceQuote | null;
+ effective: ModelPriceQuote | null;
+ override: ModelPriceOverrideValues | null;
+ conflict: boolean;
+ registryUpdatedAt: string | null;
+ /** Currencies that can be projected into the active account ledger without guessing FX. */
+ allowedCurrencies: MoneyCurrency[];
+}
diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.ts
index 7ff5ff6f90..a73855d10e 100644
--- a/apps/desktop/src/shared/modelPriceQuote.ts
+++ b/apps/desktop/src/shared/modelPriceQuote.ts
@@ -1,7 +1,10 @@
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
+import {
+ resolveModelReferencePrice,
+ type AgentKind,
+ type ModelRegistry,
+} from '@cindy/model-providers';
-import { getClaudeSubscriptionValueFallbackPrice } from './claudeSubscriptionValue.js';
-import { CODEX_SUBSCRIPTION_VALUE_PRICING } from './codexSubscriptionValue.js';
import type { ModelAccessGatewayModel } from './modelAccess.js';
import {
gatewayCurrencyForRegion,
@@ -11,21 +14,6 @@ import {
} from './regionalMoney.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from './subscriptionModels.js';
-const XAI_SUBSCRIPTION_VALUE_PRICING: Record<
- string,
- {
- inputPerMtok: number;
- outputPerMtok: number;
- cacheReadPerMtok?: number;
- cacheCreatePerMtok?: number;
- }
-> = {
- 'grok-4.5': { inputPerMtok: 2, outputPerMtok: 6, cacheReadPerMtok: 0.5 },
- 'grok-4.3': { inputPerMtok: 3, outputPerMtok: 15 },
- 'grok-4.20': { inputPerMtok: 3, outputPerMtok: 15 },
- 'grok-code-fast': { inputPerMtok: 0.2, outputPerMtok: 1.5 },
-};
-
function isNonNegativeFinite(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
}
@@ -40,6 +28,57 @@ function normalizedCostDiscount(value: unknown): number | undefined {
: undefined;
}
+function gatewayInputTokenPriceBands(
+ model: ModelAccessGatewayModel,
+): ModelPriceQuote['inputTokenPriceBands'] {
+ const explicit = model.tieredPricing
+ ?.map((tier) => {
+ const inputPerMtok = perMtok(tier.inputCostPerToken);
+ const outputPerMtok = perMtok(tier.outputCostPerToken);
+ const cacheReadPerMtok = perMtok(tier.cacheReadInputTokenCost);
+ const cacheCreatePerMtok = perMtok(tier.cacheCreationInputTokenCost);
+ if (
+ inputPerMtok === undefined &&
+ outputPerMtok === undefined &&
+ cacheReadPerMtok === undefined &&
+ cacheCreatePerMtok === undefined
+ ) {
+ return null;
+ }
+ return {
+ minInputTokens: tier.range[0],
+ maxInputTokens: tier.range[1],
+ ...(inputPerMtok !== undefined ? { inputPerMtok } : {}),
+ ...(outputPerMtok !== undefined ? { outputPerMtok } : {}),
+ ...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),
+ ...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),
+ };
+ })
+ .filter((tier): tier is NonNullable<typeof tier> => tier !== null);
+ if (explicit?.length) return explicit;
+
+ const thresholdBands = [
+ {
+ minInputTokens: 200_001,
+ inputPerMtok: perMtok(model.inputCostPerTokenAbove200kTokens),
+ outputPerMtok: perMtok(model.outputCostPerTokenAbove200kTokens),
+ cacheReadPerMtok: perMtok(model.cacheReadInputTokenCostAbove200kTokens),
+ },
+ {
+ minInputTokens: 272_001,
+ inputPerMtok: perMtok(model.inputCostPerTokenAbove272kTokens),
+ outputPerMtok: perMtok(model.outputCostPerTokenAbove272kTokens),
+ cacheReadPerMtok: perMtok(model.cacheReadInputTokenCostAbove272kTokens),
+ },
+ ].filter(
+ (tier) =>
+ tier.inputPerMtok !== undefined ||
+ tier.outputPerMtok !== undefined ||
+ tier.cacheReadPerMtok !== undefined,
+ );
+ return thresholdBands.length > 0 ? thresholdBands : undefined;
+}
+
/** Gateway 原生币种优先;旧服务端未声明时才按构建 region 回退。 */
/** 该条目是否会产生报价(与币种无关;目录币种裁决与覆盖率统计共用此判定)。 */
export function isPricedGatewayModel(model: ModelAccessGatewayModel): boolean {
@@ -75,6 +114,7 @@ export function gatewayModelPriceQuote(
// quote 保留标准价供模型选择器展示原价;所有 Gateway 模型统一把
// costDiscount 带入计费计算,CatalogModel.cost 继续承载折后展示价。
const costDiscount = normalizedCostDiscount(model.costDiscount);
+ const inputTokenPriceBands = gatewayInputTokenPriceBands(model);
return {
providerId: 'xd',
modelId,
@@ -85,6 +125,7 @@ export function gatewayModelPriceQuote(
outputPerMtok,
...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),
...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),
+ ...(inputTokenPriceBands ? { inputTokenPriceBands } : {}),
...(costDiscount !== undefined ? { costDiscount } : {}),
};
}
@@ -117,96 +158,160 @@ export function gatewayPricingCatalog(
return Object.keys(xd).length > 0 ? { xd } : {};
}
-function subscriptionQuote(
+function referenceQuote(
providerId: string,
modelId: string,
price: {
+ currency: MoneyCurrency;
inputPerMtok: number;
outputPerMtok: number;
cacheReadPerMtok?: number;
cacheCreatePerMtok?: number;
+ inputTokenPriceBands?: ModelPriceQuote['inputTokenPriceBands'];
},
): ModelPriceQuote {
return {
providerId,
modelId,
- currency: 'USD',
- source: 'subscription-reference',
+ source: 'provider-reference',
approximate: true,
...price,
};
}
+function referencePriceCalendarDate(value: string | Date | undefined): string {
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
+ return value.slice(0, 10);
+ }
+ return new Date().toISOString().slice(0, 10);
+}
+
export function providerReferencePriceQuote(
providerId: string,
modelId: string,
+ registry: ModelRegistry | null | undefined,
+ options: {
+ agent?: AgentKind;
+ inputTokens?: number;
+ at?: string | Date;
+ variant?: 'standard' | 'priority' | 'batch' | 'fast';
+ } = {},
): ModelPriceQuote | undefined {
- if (providerId === 'anthropic') {
- const price = getClaudeSubscriptionValueFallbackPrice(modelId);
- if (!price) return undefined;
- return subscriptionQuote(providerId, modelId, {
- inputPerMtok: price.inputUsdPerMtok,
- outputPerMtok: price.outputUsdPerMtok,
- ...(price.cacheReadUsdPerMtok !== undefined
- ? { cacheReadPerMtok: price.cacheReadUsdPerMtok }
+ const resolved = resolveModelReferencePrice(registry, providerId, modelId, options);
+ if (!resolved) return undefined;
+ const day = referencePriceCalendarDate(options.at);
+ const variant = options.variant ?? 'standard';
+ const inputTokenPriceBands = resolved.route.referencePrices
+ ?.filter(
+ (price) =>
+ price.variant === variant &&
+ price.currency === resolved.price.currency &&
+ day >= price.effectiveFrom &&
+ (price.effectiveUntil === undefined || day < price.effectiveUntil),
+ )
+ .map((price) => ({
+ minInputTokens: price.minInputTokens ?? 0,
+ ...(price.maxInputTokens !== undefined
+ ? { maxInputTokens: price.maxInputTokens }
: {}),
- ...(price.cacheCreateUsdPerMtok !== undefined
- ? { cacheCreatePerMtok: price.cacheCreateUsdPerMtok }
- : {}),
- });
- }
- if (providerId === 'openai') {
- const bareModel = modelId.startsWith(CHATGPT_MODEL_PREFIX)
- ? modelId.slice(CHATGPT_MODEL_PREFIX.length)
- : modelId;
- const price = CODEX_SUBSCRIPTION_VALUE_PRICING[bareModel];
- if (!price) return undefined;
- return subscriptionQuote(providerId, modelId, {
- inputPerMtok: price.inputUsdPerMtok,
- outputPerMtok: price.outputUsdPerMtok,
- ...(price.cacheReadUsdPerMtok !== undefined
- ? { cacheReadPerMtok: price.cacheReadUsdPerMtok }
+ inputPerMtok: price.inputPerMtok,
+ outputPerMtok: price.outputPerMtok,
+ ...(price.cacheReadPerMtok !== undefined
+ ? { cacheReadPerMtok: price.cacheReadPerMtok }
: {}),
- ...(price.cacheCreateUsdPerMtok !== undefined
- ? { cacheCreatePerMtok: price.cacheCreateUsdPerMtok }
+ ...(price.cacheWritePerMtok !== undefined
+ ? { cacheCreatePerMtok: price.cacheWritePerMtok }
: {}),
- });
- }
- if (providerId === 'xai') {
- const bareModel = modelId.startsWith(XAI_MODEL_PREFIX)
- ? modelId.slice(XAI_MODEL_PREFIX.length)
- : modelId;
- const price = XAI_SUBSCRIPTION_VALUE_PRICING[bareModel];
- return price ? subscriptionQuote(providerId, modelId, price) : undefined;
+ }))
+ .sort((a, b) => a.minInputTokens - b.minInputTokens);
+ return referenceQuote(providerId, modelId, {
+ currency: resolved.price.currency,
+ inputPerMtok: resolved.price.inputPerMtok,
+ outputPerMtok: resolved.price.outputPerMtok,
+ ...(resolved.price.cacheReadPerMtok !== undefined
+ ? { cacheReadPerMtok: resolved.price.cacheReadPerMtok }
+ : {}),
+ ...(resolved.price.cacheWritePerMtok !== undefined
+ ? { cacheCreatePerMtok: resolved.price.cacheWritePerMtok }
+ : {}),
+ ...(inputTokenPriceBands && inputTokenPriceBands.length > 0
+ ? { inputTokenPriceBands }
+ : {}),
+ });
+}
+
+export function registryPricingCatalog(
+ registry: ModelRegistry | null | undefined,
+): ModelPricingCatalog {
+ const catalog: ModelPricingCatalog = {};
+ if (!registry) return catalog;
+ for (const entry of registry.models) {
+ for (const route of entry.routes) {
+ // XD/Cindy AI 的售价只认登录账号对应的 Gateway /models 响应。公共 registry
+ // 只提供用户自带 API/OAuth 的参考价,绝不能在 Gateway 离线时伪装成 XD 售价。
+ if (route.providerId === 'xd') continue;
+ const quote = providerReferencePriceQuote(route.providerId, route.modelId, registry);
+ if (!quote) continue;
+ (catalog[route.providerId] ??= {})[route.modelId] = quote;
+ }
}
- return undefined;
+ return catalog;
+}
+
+export function modelPricingKey(modelId: string, agent?: AgentKind): string {
+ return agent ? `${modelId}\u0000${agent}` : modelId;
}
export function getModelPriceQuote(
pricing: ModelPricingCatalog | null | undefined,
providerId: string | null | undefined,
modelId: string,
+ agent?: AgentKind,
): ModelPriceQuote | undefined {
const normalizedProvider = providerId?.trim();
const normalizedModel = modelId.trim();
if (!normalizedProvider || !normalizedModel) return undefined;
- return (
- pricing?.[normalizedProvider]?.[normalizedModel] ??
- providerReferencePriceQuote(normalizedProvider, normalizedModel)
- );
+ const providerPricing = pricing?.[normalizedProvider];
+ if (!providerPricing) return undefined;
+ const exactQuote = (candidate: string): ModelPriceQuote | undefined =>
+ (agent ? providerPricing[modelPricingKey(candidate, agent)] : undefined) ??
+ providerPricing[candidate];
+ const exact = exactQuote(normalizedModel);
+ if (exact) return exact;
+ if (normalizedProvider === 'openai' && normalizedModel.startsWith(CHATGPT_MODEL_PREFIX)) {
+ const bareModel = normalizedModel.slice(CHATGPT_MODEL_PREFIX.length);
+ return exactQuote(bareModel);
+ }
+ if (normalizedProvider === 'anthropic') {
+ // Claude Code may report a dated wire id although the registry route uses the stable id.
+ const undatedModel = normalizedModel.replace(/-\d{8}$/, '');
+ if (undatedModel !== normalizedModel) {
+ const undated = exactQuote(undatedModel);
+ if (undated) return undated;
+ }
+ // Historical Claude sessions can report a bare family alias. The pricing catalog preserves
+ // server registry order, so the first matching route is the server-curated current family.
+ if (normalizedModel === 'opus' || normalizedModel === 'sonnet' || normalizedModel === 'haiku') {
+ const familyPrefix = `claude-${normalizedModel}-`;
+ for (const key of Object.keys(providerPricing)) {
+ const routeModel = key.split('\u0000', 1)[0];
+ if (!routeModel.startsWith(familyPrefix)) continue;
+ // Select the server-curated canonical family route first, then resolve that route through
+ // exactQuote so an agent-specific user override wins over its generic reference quote.
+ const familyQuote = exactQuote(routeModel);
+ if (familyQuote) return familyQuote;
+ }
+ }
+ }
+ return undefined;
}
/**
* 从报价目录推断当前账号的 Gateway 结算币种。
*
- * 结算币种由服务端按账号所属租户下发,不保证等于客户端发行区域:多数账号跟随区域
- * (cn=CNY / global=USD),但也存在以 USD 结算的账号运行在 CN 构建上的正常情形。
- * 所以凡是需要判断"这个账号按什么币种记账"的地方都应问本函数,既不看 region,
- * 也不需要判断账号属于哪类租户。
- *
- * 同一账号的目录币种是统一的,所以任取一条即可;目录为空或出现混合币种(目录本身不可信)
- * 时返回 null,由调用方回落到构建默认值。与 main 侧 modelPricing.getGatewayAccountCurrency
- * 的判定口径一致。
+ * 结算币种由服务端按账号所属租户下发,不保证等于客户端发行区域。目录为空或出现
+ * 混合币种时返回 null,由调用方回落到当前活动账本币种。
*/
export function gatewayLedgerCurrency(
pricing: ModelPricingCatalog | null | undefined,
@@ -215,12 +320,24 @@ export function gatewayLedgerCurrency(
return currencies.size === 1 ? (currencies.values().next().value ?? null) : null;
}
-export function subscriptionDirectPriceQuote(modelId: string): ModelPriceQuote | undefined {
+export function subscriptionDirectPriceQuote(
+ modelId: string,
+ registry: ModelRegistry | null | undefined,
+ agent?: AgentKind,
+ at?: string | Date,
+): ModelPriceQuote | undefined {
+ let quote: ModelPriceQuote | undefined;
if (modelId.startsWith(CHATGPT_MODEL_PREFIX)) {
- return providerReferencePriceQuote('openai', modelId);
- }
- if (modelId.startsWith(XAI_MODEL_PREFIX)) {
- return providerReferencePriceQuote('xai', modelId);
+ quote = providerReferencePriceQuote('openai', modelId, registry, { agent, at });
+ } else if (modelId.startsWith(XAI_MODEL_PREFIX)) {
+ quote = providerReferencePriceQuote('xai', modelId, registry, { agent, at });
}
- return undefined;
+ return quote
+ ? {
+ ...quote,
+ modelId,
+ source:
+ quote.source === 'provider-reference' ? 'subscription-reference' : quote.source,
+ }
+ : undefined;
}
diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.ts
index 43b76f2a5e..2da306eb81 100644
--- a/apps/desktop/src/shared/regionalMoney.ts
+++ b/apps/desktop/src/shared/regionalMoney.ts
@@ -25,12 +25,28 @@ export interface ModelPriceQuote {
providerId: string;
modelId: string;
currency: MoneyCurrency;
- source: 'gateway' | 'provider-reference' | 'subscription-reference';
+ source:
+ | 'gateway'
+ | 'provider-reference'
+ | 'subscription-reference'
+ | 'user-override';
approximate: boolean;
inputPerMtok: number;
outputPerMtok: number;
cacheReadPerMtok?: number;
cacheCreatePerMtok?: number;
+ /**
+ * Context-length pricing bands. minInputTokens is inclusive and maxInputTokens
+ * is exclusive; omitted prices inherit the quote's baseline field.
+ */
+ inputTokenPriceBands?: Array<{
+ minInputTokens: number;
+ maxInputTokens?: number;
+ inputPerMtok?: number;
+ outputPerMtok?: number;
+ cacheReadPerMtok?: number;
+ cacheCreatePerMtok?: number;
+ }>;
/** Gateway 声明的折扣比例;计费金额按原价 × (1 - costDiscount)。 */
costDiscount?: number;
}
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 7ee54110ab..9260c2a6e1 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -139,6 +139,10 @@
Anthropic Messages API / wire protocol 的用户可见名称。四语统一保留官方英文名称,避免与普通的“消息”概念混译;先登记为 proposed,待产品术语评审后固化。
+### API Price Estimate
+
+用户为自有 API、OAuth 或订阅通道维护的本地 token 单价估算;只影响 Cindy 的用量价值估算,不代表供应商实际账单,也不覆盖 Cindy AI Gateway 的服务端实售价。先登记为 proposed,待产品术语评审后固化。
+
### Global region
企业认证与业务服务所在区域的用户可见名称,用于组织登录检测到 Global 服务区域时的确认文案;它描述连接的服务区域,不是对当前安装版本的标签,也不同于项目配置里的 generic global scope。先按现有四语文案登记为 proposed。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index fb1bab5199..5c208396d8 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -1191,6 +1191,17 @@
},
"note": "issue #882:模型管理/新对话选择器的分类标签,对应网关的文档压缩类模型(如 ai-gateway-doc)。此前被硬编码为笼统的 other 分类。"
},
+ {
+ "id": "api-price-estimate",
+ "status": "proposed",
+ "en": "API Price Estimate",
+ "translations": {
+ "zh-CN": "API 估价",
+ "ja": "API 料金見積もり",
+ "ko": "API 가격 추정치"
+ },
+ "note": "用户为自有 API、OAuth 或订阅通道维护的本地 token 单价估算;只影响 Cindy 的用量价值估算,不代表供应商实际账单,也不覆盖 Cindy AI Gateway 的服务端实售价。先登记为 proposed,待产品术语评审后固化。"
+ },
{
"id": "context-window",
"status": "proposed",
diff --git a/packages/model-providers/catalog/model-registry.json b/packages/model-providers/catalog/model-registry.json
new file mode 100644
index 0000000000..f513373c25
--- /dev/null
+++ b/packages/model-providers/catalog/model-registry.json
@@ -0,0 +1,1660 @@
+{
+ "schemaVersion": 1,
+ "updatedAt": "2026-08-01T00:00:00.000Z",
+ "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": "high",
+ "sortOrder": 18,
+ "supportsFastMode": true,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ },
+ "codex": {
+ "contextWindow": 372000,
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-5.6-sol",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 30,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-07-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.6-sol",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 10,
+ "outputPerMtok": 45,
+ "cacheReadPerMtok": 1,
+ "cacheWritePerMtok": 12.5,
+ "minInputTokens": 272001,
+ "effectiveFrom": "2026-07-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.6-sol",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.6-sol",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 19,
+ "supportsFastMode": true,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ },
+ "codex": {
+ "contextWindow": 372000,
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-5.6-terra",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 15,
+ "cacheReadPerMtok": 0.25,
+ "cacheWritePerMtok": 3.125,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-07-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.6-terra",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 22.5,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "minInputTokens": 272001,
+ "effectiveFrom": "2026-07-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.6-terra",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.6-terra",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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"],
+ "sortOrder": 17,
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-5.6-luna",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1,
+ "outputPerMtok": 6,
+ "cacheReadPerMtok": 0.1,
+ "cacheWritePerMtok": 1.25,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-07-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.6-luna",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2,
+ "outputPerMtok": 9,
+ "cacheReadPerMtok": 0.2,
+ "cacheWritePerMtok": 2.5,
+ "minInputTokens": 272001,
+ "effectiveFrom": "2026-07-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.6-luna",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.6-luna",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "openai/gpt-5.5",
+ "name": "GPT-5.5",
+ "status": "active",
+ "group": "gpt",
+ "description": "OpenAI Codex (GPT-5.5) for coding tasks",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 20,
+ "supportsFastMode": true,
+ "defaultEnabled": false,
+ "perAgent": {
+ "claude-code": {
+ "contextWindow": 1050000,
+ "supportsFastMode": false
+ },
+ "codex": {
+ "contextWindow": 272000
+ }
+ },
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-5.5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 30,
+ "cacheReadPerMtok": 0.5,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-04-23",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.5",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 10,
+ "outputPerMtok": 45,
+ "cacheReadPerMtok": 1,
+ "minInputTokens": 272001,
+ "effectiveFrom": "2026-04-23",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.5",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.5",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "openai/gpt-5.4",
+ "name": "GPT-5.4",
+ "status": "active",
+ "group": "gpt",
+ "description": "OpenAI Codex (GPT-5.4) for coding tasks",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 21,
+ "supportsFastMode": true,
+ "defaultEnabled": false,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ }
+ },
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-5.4",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 15,
+ "cacheReadPerMtok": 0.25,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-03-05",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.4",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 22.5,
+ "cacheReadPerMtok": 0.5,
+ "minInputTokens": 272001,
+ "effectiveFrom": "2026-03-05",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.4",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.4",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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": 400000,
+ "maxOutputTokens": 128000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 22,
+ "supportsFastMode": true,
+ "defaultEnabled": false,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ }
+ },
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-5.4-mini",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 0.75,
+ "outputPerMtok": 4.5,
+ "cacheReadPerMtok": 0.075,
+ "effectiveFrom": "2026-03-17",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.4-mini",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.4-mini",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 1,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-fable-5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 10,
+ "outputPerMtok": 50,
+ "cacheReadPerMtok": 1,
+ "cacheWritePerMtok": 12.5,
+ "cacheWrite1hPerMtok": 20,
+ "effectiveFrom": "2026-06-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-fable-5",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "id": "anthropic/claude-mythos-5",
+ "name": "Mythos 5",
+ "status": "active",
+ "group": "anthropic",
+ "contextWindow": 1000000,
+ "maxOutputTokens": 128000,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-mythos-5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 10,
+ "outputPerMtok": 50,
+ "cacheReadPerMtok": 1,
+ "cacheWritePerMtok": 12.5,
+ "cacheWrite1hPerMtok": 20,
+ "effectiveFrom": "2026-06-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 0,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-opus-5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 25,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "cacheWrite1hPerMtok": 10,
+ "effectiveFrom": "2026-07-24",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "fast",
+ "inputPerMtok": 10,
+ "outputPerMtok": 50,
+ "effectiveFrom": "2026-07-24",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-opus-5",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 2,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-opus-4-8",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 25,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "cacheWrite1hPerMtok": 10,
+ "effectiveFrom": "2026-05-28",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "fast",
+ "inputPerMtok": 10,
+ "outputPerMtok": 50,
+ "effectiveFrom": "2026-05-28",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-opus-4-8",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 3,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-opus-4-7",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 25,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "cacheWrite1hPerMtok": 10,
+ "effectiveFrom": "2026-04-16",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-opus-4-7",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 4,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-opus-4-6",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 25,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "cacheWrite1hPerMtok": 10,
+ "effectiveFrom": "2026-02-05",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-opus-4-6",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 5,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-opus-4-5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 5,
+ "outputPerMtok": 25,
+ "cacheReadPerMtok": 0.5,
+ "cacheWritePerMtok": 6.25,
+ "cacheWrite1hPerMtok": 10,
+ "effectiveFrom": "2025-11-01",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-opus-4-5",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 6,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-sonnet-5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2,
+ "outputPerMtok": 10,
+ "cacheReadPerMtok": 0.2,
+ "cacheWritePerMtok": 2.5,
+ "cacheWrite1hPerMtok": 4,
+ "effectiveFrom": "2026-06-30",
+ "effectiveUntil": "2026-09-01",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 3,
+ "outputPerMtok": 15,
+ "cacheReadPerMtok": 0.3,
+ "cacheWritePerMtok": 3.75,
+ "cacheWrite1hPerMtok": 6,
+ "effectiveFrom": "2026-09-01",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-sonnet-5",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 7,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-sonnet-4-6",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 3,
+ "outputPerMtok": 15,
+ "cacheReadPerMtok": 0.3,
+ "cacheWritePerMtok": 3.75,
+ "cacheWrite1hPerMtok": 6,
+ "effectiveFrom": "2026-02-17",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-sonnet-4-6",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 3,
+ "outputPerMtok": 15,
+ "cacheReadPerMtok": 0.3,
+ "cacheWritePerMtok": 3.75,
+ "cacheWrite1hPerMtok": 6,
+ "effectiveFrom": "2025-09-29",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-sonnet-4-5",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": false,
+ "routes": [
+ {
+ "providerId": "anthropic",
+ "modelId": "claude-haiku-4-5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1,
+ "outputPerMtok": 5,
+ "cacheReadPerMtok": 0.1,
+ "cacheWritePerMtok": 1.25,
+ "cacheWrite1hPerMtok": 2,
+ "effectiveFrom": "2025-10-01",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "verifiedAt": "2026-07-31"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "claude-haiku-4-5",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 49,
+ "routes": [
+ {
+ "providerId": "xai",
+ "modelId": "xai/grok-4.5",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2,
+ "outputPerMtok": 6,
+ "cacheReadPerMtok": 0.3,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-07-08",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 4,
+ "outputPerMtok": 12,
+ "cacheReadPerMtok": 0.6,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-07-08",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 51,
+ "perAgent": {
+ "codex": {
+ "efforts": ["low", "medium", "high"]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xai",
+ "modelId": "xai/grok-4.3",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1.25,
+ "outputPerMtok": 2.5,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-05-15",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 5,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-05-15",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1,
+ "outputPerMtok": 2,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-05-15",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2,
+ "outputPerMtok": 4,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-05-15",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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": [],
+ "sortOrder": 52,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xai",
+ "modelId": "xai/grok-4.20-multi-agent-0309",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1.25,
+ "outputPerMtok": 2.5,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-03-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 5,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-03-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1.25,
+ "outputPerMtok": 2.5,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-03-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 5,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-03-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1.25,
+ "outputPerMtok": 2.5,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-03-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 5,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-03-09",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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": "high",
+ "sortOrder": 98,
+ "defaultEnabled": false,
+ "perAgent": {
+ "codex": {
+ "efforts": ["low", "medium", "high"]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xai",
+ "modelId": "xai/grok-4.20",
+ "agents": ["claude-code", "codex"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1.25,
+ "outputPerMtok": 2.5,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-04-07",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2.5,
+ "outputPerMtok": 5,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-04-07",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 1,
+ "outputPerMtok": 2,
+ "cacheReadPerMtok": 0.2,
+ "maxInputTokens": 200000,
+ "effectiveFrom": "2026-05-15",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/migration/may-15-retirement",
+ "verifiedAt": "2026-08-01"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 2,
+ "outputPerMtok": 4,
+ "cacheReadPerMtok": 0.4,
+ "minInputTokens": 200000,
+ "effectiveFrom": "2026-05-15",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/migration/may-15-retirement",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "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,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 8,
+ "supportsFastMode": true,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ },
+ "codex": {
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "codex/gpt-5.6-sol",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 9,
+ "supportsFastMode": true,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ },
+ "codex": {
+ "efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "codex/gpt-5.6-terra",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "xd/codex-gpt-5.5",
+ "name": "GPT-5.5",
+ "group": "gpt-budget",
+ "description": "GPT-5.5 for coding tasks",
+ "contextWindow": 272000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 10,
+ "supportsFastMode": true,
+ "defaultEnabled": false,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "codex/gpt-5.5",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "xd/codex-gpt-5.4",
+ "name": "GPT-5.4",
+ "group": "gpt-budget",
+ "description": "GPT-5.4 for coding tasks",
+ "contextWindow": 272000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "sortOrder": 11,
+ "supportsFastMode": true,
+ "defaultEnabled": false,
+ "perAgent": {
+ "claude-code": {
+ "supportsFastMode": false
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "codex/gpt-5.4",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "high",
+ "sortOrder": 30,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "gemini-3.5-flash",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "high",
+ "sortOrder": 31,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "gemini-3.1-pro-preview",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "id": "google/gemini-3-flash-preview",
+ "name": "Gemini 3 Flash",
+ "group": "google",
+ "description": "Google Gemini 3 Flash Preview — fast multimodal reasoning",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "high",
+ "sortOrder": 32,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "gemini-3-flash-preview",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "id": "bytedance-seed/seed-2.1-pro",
+ "name": "Seed 2.1 Pro",
+ "group": "china",
+ "contextWindow": 256000,
+ "efforts": ["minimal", "low", "medium", "high"],
+ "defaultEffort": "minimal",
+ "supportsFastMode": false,
+ "perAgent": {
+ "claude-code": {
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "low"
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "bytedance-seed/seed-2.1-pro",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "qwen/qwen3.8-max-preview",
+ "name": "Qwen 3.8 Max Preview",
+ "group": "china",
+ "contextWindow": 983616,
+ "efforts": ["low", "high", "xhigh"],
+ "defaultEffort": "xhigh",
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "qwen/qwen3.8-max-preview",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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,
+ "efforts": [],
+ "sortOrder": 40,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "qwen/qwen3.7-max",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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"]
+ }
+ ]
+ },
+ {
+ "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": 202752,
+ "efforts": [],
+ "sortOrder": 42,
+ "supportsFastMode": false,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "z-ai/glm-5.1",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "id": "z-ai/glm-5.2",
+ "name": "GLM-5.2",
+ "group": "china",
+ "description": "Zhipu GLM-5.2 agentic coding model; 1M context",
+ "contextWindow": 1000000,
+ "efforts": ["minimal", "high", "max"],
+ "defaultEffort": "max",
+ "sortOrder": 43,
+ "supportsFastMode": false,
+ "perAgent": {
+ "claude-code": {
+ "efforts": ["high", "max"],
+ "defaultEffort": "max"
+ }
+ },
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "z-ai/glm-5.2",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "deepseek/deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "group": "china",
+ "description": "DeepSeek V4 Pro reasoning model; only high/max effective (low/medium→high, xhigh→max)",
+ "contextWindow": 1048576,
+ "efforts": ["high", "max"],
+ "defaultEffort": "high",
+ "sortOrder": 44,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "deepseek/deepseek-v4-pro",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "deepseek/deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash",
+ "group": "china",
+ "description": "DeepSeek V4 Flash efficiency-optimized MoE; only high/max effective",
+ "contextWindow": 1048576,
+ "efforts": ["high", "max"],
+ "defaultEffort": "high",
+ "sortOrder": 45,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "deepseek/deepseek-v4-flash",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "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"],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 0.2,
+ "outputPerMtok": 1.25,
+ "cacheReadPerMtok": 0.02,
+ "effectiveFrom": "2026-03-17",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-5.4-nano",
+ "verifiedAt": "2026-08-01"
+ }
+ }
+ ]
+ },
+ {
+ "providerId": "xd",
+ "modelId": "gpt-5.4-nano",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "xd/codex-gpt-5.4-mini",
+ "name": "GPT-5.4-Mini",
+ "group": "gpt-budget",
+ "sortOrder": 103,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "codex/gpt-5.4-mini",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "moonshotai/kimi-k3",
+ "name": "Kimi K3",
+ "group": "china",
+ "contextWindow": 1000000,
+ "efforts": ["low", "high", "max"],
+ "defaultEffort": "max",
+ "sortOrder": 41,
+ "supportsFastMode": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "moonshotai/kimi-k3",
+ "agents": ["claude-code", "codex"]
+ }
+ ]
+ },
+ {
+ "id": "qwen/qwen3.6-plus",
+ "name": "Qwen 3.6 Plus",
+ "group": "china",
+ "sortOrder": 105,
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xd",
+ "modelId": "qwen/qwen3.6-plus",
+ "agents": ["claude-code"]
+ }
+ ]
+ },
+ {
+ "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"]
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 1e34c31c39..db1db14bbc 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -5,10 +5,7 @@
"id": "xai",
"name": "xAI",
"source": "builtin",
- "agents": [
- "claude-code",
- "codex"
- ],
+ "agents": ["claude-code", "codex"],
"auth": {
"method": "oauth"
},
@@ -30,9 +27,7 @@
"claude-code": {
"upstream": "https://api.x.ai/v1",
"authStrategy": "oauth-passthrough",
- "modelPrefixes": [
- "xai/"
- ]
+ "modelPrefixes": ["xai/"]
},
"codex": {
"upstream": "https://api.x.ai/v1",
@@ -40,15 +35,8 @@
"modelIdRewrite": {
"stripPrefix": "xai/"
},
- "headerDelete": [
- "chatgpt-account-id",
- "openai-beta",
- "originator",
- "session_id"
- ],
- "modelPrefixes": [
- "xai/"
- ]
+ "headerDelete": ["chatgpt-account-id", "openai-beta", "originator", "session_id"],
+ "modelPrefixes": ["xai/"]
}
},
"models": {
@@ -60,11 +48,7 @@
"sortOrder": 49,
"description": "xAI Grok 4.5 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)",
"contextWindow": 500000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
+ "efforts": ["low", "medium", "high"],
"defaultEffort": "high",
"status": "active"
},
@@ -72,51 +56,83 @@
"id": "xai/grok-4.3",
"name": "Grok 4.3",
"group": "grok",
- "sortOrder": 50,
+ "sortOrder": 51,
"description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)",
"contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "effortDisplayNames": {
- "xhigh": "Extra High"
- },
+ "efforts": ["low", "medium", "high"],
"defaultEffort": "high",
"status": "active"
},
{
- "id": "xai/grok-4.20",
+ "id": "xai/grok-build-0.1",
+ "name": "Grok Build 0.1",
+ "group": "grok",
+ "sortOrder": 50,
+ "description": "xAI agentic coding model,256k 上下文(SuperGrok 订阅直连)",
+ "contextWindow": 256000,
+ "efforts": [],
+ "defaultEffort": null,
+ "status": "active",
+ "defaultEnabled": false
+ },
+ {
+ "id": "xai/grok-4.20-multi-agent-0309",
+ "name": "Grok 4.20 Multi-Agent",
+ "group": "grok",
+ "sortOrder": 52,
+ "description": "xAI Grok 4.20 multi-agent model,1M 上下文(SuperGrok 订阅直连)",
+ "contextWindow": 1000000,
+ "efforts": [],
+ "defaultEffort": null,
+ "status": "active",
+ "defaultEnabled": false
+ },
+ {
+ "id": "xai/grok-4.20-0309-reasoning",
"name": "Grok 4.20 Reasoning",
"group": "grok",
- "sortOrder": 51,
- "description": "xAI Grok 4.20 推理版(SuperGrok 订阅直连)",
+ "sortOrder": 53,
+ "description": "xAI Grok 4.20 reasoning model,1M 上下文(SuperGrok 订阅直连)",
"contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "effortDisplayNames": {
- "xhigh": "Extra High"
- },
- "defaultEffort": "high",
+ "efforts": [],
+ "defaultEffort": null,
+ "status": "active",
+ "defaultEnabled": false
+ },
+ {
+ "id": "xai/grok-4.20-0309-non-reasoning",
+ "name": "Grok 4.20 Non-Reasoning",
+ "group": "grok",
+ "sortOrder": 54,
+ "description": "xAI Grok 4.20 non-reasoning model,1M 上下文(SuperGrok 订阅直连)",
+ "contextWindow": 1000000,
+ "efforts": [],
+ "defaultEffort": null,
"status": "active",
"defaultEnabled": false
},
+ {
+ "id": "xai/grok-4.20",
+ "name": "Grok 4.20 Legacy Alias",
+ "group": "grok",
+ "sortOrder": 98,
+ "description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high", "xhigh"],
+ "defaultEffort": "high",
+ "status": "deprecated",
+ "defaultEnabled": false
+ },
{
"id": "xai/grok-code-fast",
- "name": "Grok Code Fast",
+ "name": "Grok Code Fast (Deprecated)",
"group": "grok",
- "sortOrder": 52,
- "description": "xAI 编码模型 grok-code-fast,不支持思维深度调节(SuperGrok 订阅直连)",
+ "sortOrder": 99,
+ "description": "旧版兼容 alias;新会话请使用 grok-build-0.1",
"contextWindow": 256000,
"efforts": [],
"defaultEffort": null,
- "status": "active",
+ "status": "deprecated",
"defaultEnabled": false
}
],
@@ -128,11 +144,7 @@
"sortOrder": 49,
"description": "xAI Grok 4.5 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)",
"contextWindow": 500000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
+ "efforts": ["low", "medium", "high"],
"defaultEffort": "high",
"status": "active"
},
@@ -140,43 +152,83 @@
"id": "xai/grok-4.3",
"name": "Grok 4.3",
"group": "grok",
- "sortOrder": 50,
+ "sortOrder": 51,
"description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)",
"contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
+ "efforts": ["low", "medium", "high"],
"defaultEffort": "high",
"status": "active"
},
{
- "id": "xai/grok-4.20",
+ "id": "xai/grok-build-0.1",
+ "name": "Grok Build 0.1",
+ "group": "grok",
+ "sortOrder": 50,
+ "description": "xAI agentic coding model,256k 上下文(SuperGrok 订阅直连)",
+ "contextWindow": 256000,
+ "efforts": [],
+ "defaultEffort": null,
+ "status": "active",
+ "defaultEnabled": false
+ },
+ {
+ "id": "xai/grok-4.20-multi-agent-0309",
+ "name": "Grok 4.20 Multi-Agent",
+ "group": "grok",
+ "sortOrder": 52,
+ "description": "xAI Grok 4.20 multi-agent model,1M 上下文(SuperGrok 订阅直连)",
+ "contextWindow": 1000000,
+ "efforts": [],
+ "defaultEffort": null,
+ "status": "active",
+ "defaultEnabled": false
+ },
+ {
+ "id": "xai/grok-4.20-0309-reasoning",
"name": "Grok 4.20 Reasoning",
"group": "grok",
- "sortOrder": 51,
- "description": "xAI Grok 4.20 推理版(SuperGrok 订阅直连)",
+ "sortOrder": 53,
+ "description": "xAI Grok 4.20 reasoning model,1M 上下文(SuperGrok 订阅直连)",
"contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "high",
+ "efforts": [],
+ "defaultEffort": null,
"status": "active",
"defaultEnabled": false
},
+ {
+ "id": "xai/grok-4.20-0309-non-reasoning",
+ "name": "Grok 4.20 Non-Reasoning",
+ "group": "grok",
+ "sortOrder": 54,
+ "description": "xAI Grok 4.20 non-reasoning model,1M 上下文(SuperGrok 订阅直连)",
+ "contextWindow": 1000000,
+ "efforts": [],
+ "defaultEffort": null,
+ "status": "active",
+ "defaultEnabled": false
+ },
+ {
+ "id": "xai/grok-4.20",
+ "name": "Grok 4.20 Legacy Alias",
+ "group": "grok",
+ "sortOrder": 98,
+ "description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
+ "contextWindow": 1000000,
+ "efforts": ["low", "medium", "high"],
+ "defaultEffort": "high",
+ "status": "deprecated",
+ "defaultEnabled": false
+ },
{
"id": "xai/grok-code-fast",
- "name": "Grok Code Fast",
+ "name": "Grok Code Fast (Deprecated)",
"group": "grok",
- "sortOrder": 52,
- "description": "xAI 编码模型 grok-code-fast,不支持思维深度调节(SuperGrok 订阅直连)",
+ "sortOrder": 99,
+ "description": "旧版兼容 alias;新会话请使用 grok-build-0.1",
"contextWindow": 256000,
"efforts": [],
"defaultEffort": null,
- "status": "active",
+ "status": "deprecated",
"defaultEnabled": false
}
]
@@ -1310,713 +1362,5 @@
}
}
}
- ],
- "cindyModelMeta": {
- "version": 1,
- "models": {
- "claude-opus-5": {
- "agents": [
- "claude-code"
- ],
- "name": "Opus 5",
- "group": "anthropic",
- "description": "Latest Opus for ambitious work",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 0,
- "supportsFastMode": false
- },
- "claude-fable-5": {
- "agents": [
- "claude-code"
- ],
- "name": "Fable 5",
- "group": "anthropic",
- "description": "Most capable, supports xhigh effort",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 1,
- "supportsFastMode": false
- },
- "claude-opus-4-8": {
- "agents": [
- "claude-code"
- ],
- "name": "Opus 4.8",
- "group": "anthropic",
- "description": "Most capable, supports xhigh effort",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 2,
- "supportsFastMode": false
- },
- "claude-opus-4-7": {
- "agents": [
- "claude-code"
- ],
- "name": "Opus 4.7",
- "group": "anthropic",
- "description": "Most capable, supports xhigh effort",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 3,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "claude-opus-4-6": {
- "agents": [
- "claude-code"
- ],
- "name": "Opus 4.6",
- "group": "anthropic",
- "description": "Most capable for ambitious work",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 4,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "claude-opus-4-5": {
- "agents": [
- "claude-code"
- ],
- "name": "Opus 4.5",
- "group": "anthropic",
- "description": "Earlier Opus generation",
- "contextWindow": 200000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "high",
- "sortOrder": 5,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "claude-sonnet-5": {
- "agents": [
- "claude-code"
- ],
- "name": "Sonnet 5",
- "group": "anthropic",
- "description": "Latest Sonnet — fast and highly capable",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 6,
- "supportsFastMode": false
- },
- "claude-sonnet-4-6": {
- "agents": [
- "claude-code"
- ],
- "name": "Sonnet 4.6",
- "group": "anthropic",
- "description": "Most efficient for everyday tasks",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 7,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "claude-sonnet-4-5": {
- "agents": [
- "claude-code"
- ],
- "name": "Sonnet 4.5",
- "group": "anthropic",
- "description": "Earlier Sonnet generation",
- "contextWindow": 200000,
- "efforts": [],
- "defaultEffort": null,
- "sortOrder": 8,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "claude-haiku-4-5": {
- "agents": [
- "claude-code"
- ],
- "name": "Haiku 4.5",
- "group": "anthropic",
- "description": "Fastest for quick answers",
- "contextWindow": 200000,
- "efforts": [],
- "defaultEffort": null,
- "sortOrder": 9,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "gpt-5.5": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.5",
- "group": "gpt",
- "description": "OpenAI Codex (GPT-5.5) for coding tasks",
- "contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 20,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "contextWindow": 1000000,
- "supportsFastMode": false
- }
- },
- "defaultEnabled": false
- },
- "gpt-5.4": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.4",
- "group": "gpt",
- "description": "OpenAI Codex (GPT-5.4) for coding tasks",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 21,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- }
- },
- "defaultEnabled": false
- },
- "gpt-5.4-mini": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.4-Mini",
- "group": "gpt",
- "description": "Faster, lighter Codex variant — speed-optimized for quick edits",
- "contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 22,
- "supportsFastMode": true,
- "defaultEnabled": false,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- }
- }
- },
- "codex/gpt-5.6-sol": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.6-Sol",
- "group": "gpt-budget",
- "description": "GPT-5.6-Sol for coding tasks",
- "contextWindow": 372000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 8,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- },
- "codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
- }
- }
- },
- "codex/gpt-5.6-terra": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.6-Terra",
- "group": "gpt-budget",
- "description": "GPT-5.6-Terra for coding tasks",
- "contextWindow": 372000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 9,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- },
- "codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
- }
- }
- },
- "codex/gpt-5.5": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.5",
- "group": "gpt-budget",
- "description": "GPT-5.5 for coding tasks",
- "contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 10,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- }
- },
- "defaultEnabled": false
- },
- "codex/gpt-5.4": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.4",
- "group": "gpt-budget",
- "description": "GPT-5.4 for coding tasks",
- "contextWindow": 272000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 11,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- }
- },
- "defaultEnabled": false
- },
- "gpt-5.6-sol": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.6-Sol",
- "group": "gpt",
- "description": "GPT-5.6-Sol for coding tasks",
- "contextWindow": 372000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 18,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- },
- "codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
- }
- }
- },
- "gpt-5.6-terra": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.6-Terra",
- "group": "gpt",
- "description": "GPT-5.6-Terra for coding tasks",
- "contextWindow": 372000,
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh"
- ],
- "defaultEffort": "high",
- "sortOrder": 19,
- "supportsFastMode": true,
- "perAgent": {
- "claude-code": {
- "supportsFastMode": false
- },
- "codex": {
- "efforts": [
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra"
- ]
- }
- }
- },
- "gemini-3.5-flash": {
- "agents": [
- "claude-code"
- ],
- "name": "Gemini 3.5 Flash",
- "group": "google",
- "description": "Google Gemini 3.5 Flash — upgraded Flash with stronger reasoning",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "high",
- "sortOrder": 30,
- "supportsFastMode": false
- },
- "gemini-3.1-pro-preview": {
- "agents": [
- "claude-code"
- ],
- "name": "Gemini 3.1 Pro",
- "group": "google",
- "description": "Google Gemini 3.1 Pro Preview — deepest reasoning, multimodal",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "high",
- "sortOrder": 31,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "gemini-3-flash-preview": {
- "agents": [
- "claude-code"
- ],
- "name": "Gemini 3 Flash",
- "group": "google",
- "description": "Google Gemini 3 Flash Preview — fast multimodal reasoning",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "high",
- "sortOrder": 32,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "bytedance-seed/seed-2.1-pro": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "Seed 2.1 Pro",
- "group": "china",
- "contextWindow": 256000,
- "efforts": [
- "minimal",
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "minimal",
- "supportsFastMode": false,
- "perAgent": {
- "claude-code": {
- "efforts": [
- "low",
- "medium",
- "high"
- ],
- "defaultEffort": "low"
- }
- }
- },
- "qwen/qwen3.8-max-preview": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "Qwen 3.8 Max Preview",
- "group": "china",
- "contextWindow": 983616,
- "efforts": [
- "low",
- "high",
- "xhigh"
- ],
- "defaultEffort": "xhigh",
- "supportsFastMode": false
- },
- "qwen/qwen3.7-max": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "Qwen 3.7 Max",
- "group": "china",
- "description": "Qwen 3.7 Max agentic coding model; thinking is provider-managed",
- "contextWindow": 992000,
- "efforts": [],
- "sortOrder": 40,
- "supportsFastMode": false
- },
- "moonshotai/kimi-k2.6": {
- "agents": [
- "claude-code"
- ],
- "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
- },
- "z-ai/glm-5.1": {
- "agents": [
- "claude-code"
- ],
- "name": "GLM-5.1",
- "group": "china",
- "description": "Zhipu GLM-5.1 agentic coding model; thinking is provider-managed",
- "contextWindow": 202752,
- "efforts": [],
- "sortOrder": 42,
- "supportsFastMode": false,
- "defaultEnabled": false
- },
- "z-ai/glm-5.2": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GLM-5.2",
- "group": "china",
- "description": "Zhipu GLM-5.2 agentic coding model; 1M context",
- "contextWindow": 1000000,
- "efforts": [
- "minimal",
- "high",
- "max"
- ],
- "defaultEffort": "max",
- "sortOrder": 43,
- "supportsFastMode": false,
- "perAgent": {
- "claude-code": {
- "efforts": [
- "high",
- "max"
- ],
- "defaultEffort": "max"
- }
- }
- },
- "deepseek/deepseek-v4-pro": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "DeepSeek V4 Pro",
- "group": "china",
- "description": "DeepSeek V4 Pro reasoning model; only high/max effective (low/medium→high, xhigh→max)",
- "contextWindow": 1048576,
- "efforts": [
- "high",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 44,
- "supportsFastMode": false
- },
- "deepseek/deepseek-v4-flash": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "DeepSeek V4 Flash",
- "group": "china",
- "description": "DeepSeek V4 Flash efficiency-optimized MoE; only high/max effective",
- "contextWindow": 1048576,
- "efforts": [
- "high",
- "max"
- ],
- "defaultEffort": "high",
- "sortOrder": 45,
- "supportsFastMode": false
- },
- "gpt-5.6-luna": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.6-Luna",
- "group": "gpt",
- "sortOrder": 17
- },
- "gpt-5.4-nano": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.4-Nano",
- "group": "gpt",
- "sortOrder": 101,
- "defaultEnabled": false
- },
- "codex/gpt-5.4-mini": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.4-Mini",
- "group": "gpt-budget",
- "sortOrder": 103,
- "defaultEnabled": false
- },
- "moonshotai/kimi-k3": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "Kimi K3",
- "group": "china",
- "contextWindow": 1000000,
- "efforts": [
- "low",
- "high",
- "max"
- ],
- "defaultEffort": "max",
- "sortOrder": 41,
- "supportsFastMode": false
- },
- "qwen/qwen3.6-plus": {
- "agents": [
- "claude-code"
- ],
- "name": "Qwen 3.6 Plus",
- "group": "china",
- "sortOrder": 105,
- "defaultEnabled": false
- },
- "codex/gpt-5.5:auto": {
- "agents": [
- "claude-code",
- "codex"
- ],
- "name": "GPT-5.5-Auto",
- "group": "gpt-budget",
- "sortOrder": 12,
- "defaultEnabled": false
- }
- }
- }
+ ]
}
diff --git a/packages/model-providers/package.json b/packages/model-providers/package.json
index 36b56f4312..c5fdab1822 100644
--- a/packages/model-providers/package.json
+++ b/packages/model-providers/package.json
@@ -27,6 +27,9 @@
"email": "[email protected]"
},
"license": "Apache-2.0",
+ "dependencies": {
+ "@cindy/model-access-protocol": "workspace:*"
+ },
"devDependencies": {
"@types/node": "*",
"typescript": "^5.7.0",
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index 5532b14bf8..f69c5435b5 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -27,7 +27,16 @@ import type { AgentKind, Catalog, CatalogModel } from '../types.js';
const DYNAMIC_PROVIDER_IDS = ['anthropic', 'openai', 'xd'] as const;
/** xai 静态清单(唯一活在目录文件里的模型清单)。 */
-const EXPECTED_XAI_IDS = ['xai/grok-4.5', 'xai/grok-4.3', 'xai/grok-4.20', 'xai/grok-code-fast'];
+const EXPECTED_XAI_IDS = [
+ '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',
+];
function provider(id: string) {
const p = BUNDLED_CATALOG.providers.find((x) => x.id === id);
@@ -35,6 +44,18 @@ function provider(id: string) {
return p;
}
+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) =>
+ candidate.routes.some(
+ (route) => route.providerId === providerId && route.modelId === modelId,
+ ),
+ );
+ if (!entry) throw new Error(`missing registry route ${providerId}/${modelId}`);
+ return entry;
+}
+
/** 造一个最小 CatalogModel(注入 fixture 用)。 */
function model(id: string, extra: Partial<CatalogModel> = {}): CatalogModel {
return {
@@ -196,11 +217,6 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
});
it('ships Codex support metadata for the current XD gateway model set', () => {
- const metadata = BUNDLED_CATALOG.cindyModelMeta as {
- version?: unknown;
- models?: Record<string, unknown>;
- };
- expect(metadata.version).toBe(1);
const expected = {
'qwen/qwen3.7-max': 'Qwen 3.7 Max',
'moonshotai/kimi-k3': 'Kimi K3',
@@ -211,13 +227,15 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
'qwen/qwen3.8-max-preview': 'Qwen 3.8 Max Preview',
};
for (const [id, name] of Object.entries(expected)) {
- expect(metadata.models?.[id], id).toMatchObject({
- agents: ['claude-code', 'codex'],
- name,
- });
+ const entry = registryEntryForRoute('xd', id);
+ const route = entry.routes.find(
+ (candidate) => candidate.providerId === 'xd' && candidate.modelId === id,
+ );
+ expect(entry, id).toMatchObject({ name });
+ expect(route?.agents, id).toEqual(['claude-code', 'codex']);
}
- expect(metadata.models?.['bytedance-seed/seed-2.1-pro']).toMatchObject({
+ expect(registryEntryForRoute('xd', 'bytedance-seed/seed-2.1-pro')).toMatchObject({
efforts: ['minimal', 'low', 'medium', 'high'],
defaultEffort: 'minimal',
supportsFastMode: false,
@@ -228,17 +246,17 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
},
},
});
- expect(metadata.models?.['moonshotai/kimi-k3']).toMatchObject({
+ expect(registryEntryForRoute('xd', 'moonshotai/kimi-k3')).toMatchObject({
efforts: ['low', 'high', 'max'],
defaultEffort: 'max',
supportsFastMode: false,
});
- expect(metadata.models?.['qwen/qwen3.8-max-preview']).toMatchObject({
+ expect(registryEntryForRoute('xd', 'qwen/qwen3.8-max-preview')).toMatchObject({
efforts: ['low', 'high', 'xhigh'],
defaultEffort: 'xhigh',
supportsFastMode: false,
});
- expect(metadata.models?.['z-ai/glm-5.2']).toMatchObject({
+ expect(registryEntryForRoute('xd', 'z-ai/glm-5.2')).toMatchObject({
efforts: ['minimal', 'high', 'max'],
defaultEffort: 'max',
supportsFastMode: false,
@@ -250,7 +268,7 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
},
});
for (const id of ['deepseek/deepseek-v4-pro', 'deepseek/deepseek-v4-flash']) {
- expect(metadata.models?.[id], id).toMatchObject({
+ expect(registryEntryForRoute('xd', id), id).toMatchObject({
efforts: ['high', 'max'],
defaultEffort: 'high',
supportsFastMode: false,
@@ -261,15 +279,20 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
'moonshotai/kimi-k3',
'qwen/qwen3.8-max-preview',
]) {
- expect(metadata.models?.[id], id).not.toHaveProperty('description');
+ expect(registryEntryForRoute('xd', id), id).not.toHaveProperty('description');
}
});
it('enables DeepSeek V4 Flash by default', () => {
- const metadata = BUNDLED_CATALOG.cindyModelMeta as {
- models?: Record<string, { defaultEnabled?: boolean }>;
- };
- expect(metadata.models?.['deepseek/deepseek-v4-flash']?.defaultEnabled).toBeUndefined();
+ expect(
+ 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>;
+ bad.cindyModelMeta = { version: 1, models: {} };
+ expect(() => parseCatalog(bad)).toThrow(/catalog\.cindyModelMeta is not allowed/);
});
it('models are grouped per-agent (no flat array, no rogue agent keys)', () => {
diff --git a/packages/model-providers/src/__tests__/modelRegistry.test.ts b/packages/model-providers/src/__tests__/modelRegistry.test.ts
new file mode 100644
index 0000000000..5d111669bf
--- /dev/null
+++ b/packages/model-providers/src/__tests__/modelRegistry.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, it } from "vitest";
+
+import { BUNDLED_CATALOG } from "../builtin.js";
+import {
+ findModelRegistryRoute,
+ resolveModelReferencePrice,
+} from "../modelRegistry.js";
+
+const registry = BUNDLED_CATALOG.modelRegistry;
+
+describe("model registry", () => {
+ it("resolves exact provider/runtime routes without claiming availability", () => {
+ expect(
+ findModelRegistryRoute(
+ registry,
+ "anthropic",
+ "claude-opus-5",
+ "claude-code",
+ ),
+ ).toMatchObject({
+ entry: { id: "anthropic/claude-opus-5", contextWindow: 1_000_000 },
+ route: { providerId: "anthropic", modelId: "claude-opus-5" },
+ });
+ expect(
+ findModelRegistryRoute(
+ registry,
+ " anthropic ",
+ " claude-opus-5 ",
+ "claude-code",
+ ),
+ ).toMatchObject({
+ route: { providerId: "anthropic", modelId: "claude-opus-5" },
+ });
+ expect(
+ findModelRegistryRoute(
+ registry,
+ "other-provider",
+ "claude-opus-5",
+ "claude-code",
+ ),
+ ).toBeUndefined();
+ });
+
+ it("normalizes the ChatGPT bridge id and selects OpenAI long-context bands", () => {
+ expect(
+ findModelRegistryRoute(registry, "openai", "gpt-5.6-sol", "codex"),
+ ).toMatchObject({
+ entry: {
+ contextWindow: 1_050_000,
+ maxOutputTokens: 128_000,
+ perAgent: { codex: { contextWindow: 372_000 } },
+ },
+ });
+ expect(
+ resolveModelReferencePrice(registry, "openai", "chatgpt/gpt-5.6-sol", {
+ agent: "claude-code",
+ inputTokens: 272_000,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 5, outputPerMtok: 30 });
+ expect(
+ resolveModelReferencePrice(registry, "openai", "gpt-5.6-sol", {
+ agent: "codex",
+ inputTokens: 272_001,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 10, outputPerMtok: 45 });
+ expect(
+ resolveModelReferencePrice(registry, "openai", "gpt-5.4-nano", {
+ agent: "codex",
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 0.2, outputPerMtok: 1.25 });
+ });
+
+ it("selects xAI token bands and time-effective Anthropic prices", () => {
+ expect(
+ resolveModelReferencePrice(registry, "xai", "xai/grok-4.5", {
+ inputTokens: 199_999,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 2, outputPerMtok: 6 });
+ expect(
+ resolveModelReferencePrice(registry, "xai", "xai/grok-4.5", {
+ inputTokens: 200_000,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 4, outputPerMtok: 12 });
+ expect(
+ resolveModelReferencePrice(registry, "xai", "xai/grok-build-0.1", {
+ inputTokens: 200_000,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 2, outputPerMtok: 4 });
+ expect(
+ [
+ "xai/grok-4.20-multi-agent-0309",
+ "xai/grok-4.20-0309-reasoning",
+ "xai/grok-4.20-0309-non-reasoning",
+ ].every((modelId) =>
+ Boolean(findModelRegistryRoute(registry, "xai", modelId, "codex")),
+ ),
+ ).toBe(true);
+ expect(
+ resolveModelReferencePrice(registry, "anthropic", "claude-sonnet-5", {
+ at: "2026-08-31",
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 2, outputPerMtok: 10 });
+ expect(
+ resolveModelReferencePrice(registry, "anthropic", "claude-sonnet-5", {
+ at: "2026-09-01",
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 3, outputPerMtok: 15 });
+ });
+
+ it("normalizes historical Claude aliases before resolving date-effective prices", () => {
+ expect(
+ resolveModelReferencePrice(registry, "anthropic", "sonnet", {
+ agent: "claude-code",
+ at: "2026-03-01",
+ }),
+ ).toMatchObject({
+ route: { modelId: "claude-sonnet-4-6" },
+ price: { inputPerMtok: 3, outputPerMtok: 15 },
+ });
+ expect(
+ resolveModelReferencePrice(
+ registry,
+ "anthropic",
+ "claude-sonnet-4-6-20260701",
+ { agent: "claude-code", at: "2026-08-01" },
+ ),
+ ).toMatchObject({
+ route: { modelId: "claude-sonnet-4-6" },
+ price: { inputPerMtok: 3, outputPerMtok: 15 },
+ });
+ });
+});
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index 59e8cf05c5..7b4201dfc7 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -108,6 +108,53 @@ describe('mergeWithBundled', () => {
expect(merged.providers.find((p) => p.id === 'anthropic')!.models['claude-code']!.length).toBe(1);
});
+ it('keeps a newer bundled modelRegistry when the primary full snapshot is stale', () => {
+ 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 staleRegistry = {
+ ...bundledRegistry,
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ models: [bundledRegistry.models[0]!],
+ };
+ const staleXai = { ...bundledXai, name: 'STALE-XAI' };
+
+ const merged = mergeWithBundled({
+ ...MINIMAL,
+ providers: [...MINIMAL.providers, staleXai],
+ modelRegistry: staleRegistry,
+ });
+
+ expect(merged.modelRegistry).toBe(bundledRegistry);
+ expect(merged.modelRegistry?.models.length).toBeGreaterThan(staleRegistry.models.length);
+ expect(merged.providers.find((provider) => provider.id === 'xai')).toBe(bundledXai);
+ });
+
+ 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 newerRegistry = {
+ ...bundledRegistry,
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ models: [{ ...bundledRegistry.models[0]!, status: 'retired' as const }],
+ };
+ const newerXai = { ...bundledXai, name: 'NEWER-XAI' };
+
+ const merged = mergeWithBundled({
+ ...MINIMAL,
+ providers: [...MINIMAL.providers, newerXai],
+ modelRegistry: newerRegistry,
+ });
+
+ expect(merged.modelRegistry).toBe(newerRegistry);
+ expect(merged.modelRegistry?.models).toHaveLength(1);
+ expect(merged.modelRegistry?.models[0]?.status).toBe('retired');
+ expect(merged.providers.find((provider) => provider.id === 'xai')).toBe(newerXai);
+ });
+
it('orders result by bundled provider order (v2 远端只带 xai 时不得窜位)', () => {
const v2Remote: Catalog = {
version: '2',
@@ -284,6 +331,138 @@ describe('loadCatalog', () => {
expect(bundled).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });
});
+ 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 },
+ {
+ fetchText: vi.fn(async () => JSON.stringify(MINIMAL)),
+ writeCache,
+ },
+ );
+ 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');
+ }),
+ readCache: vi.fn(async (scope) =>
+ scope === url ? JSON.stringify(MINIMAL) : null,
+ ),
+ },
+ );
+ expect(cached).toMatchObject({ source: 'cache', catalog: { version: 'test' } });
+ });
+
+ it('keeps a newer cached modelRegistry when a valid remote Catalog is stale', async () => {
+ const url = 'https://catalog.example.test/providers.json';
+ 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 older: Catalog = {
+ ...MINIMAL,
+ 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
+ )),
+ },
+ };
+ const newer: Catalog = {
+ ...MINIMAL,
+ providers: [...MINIMAL.providers, { ...xai, name: 'NEWER-LKG-XAI' }],
+ modelRegistry: {
+ ...registry,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ 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 loaded = await loadCatalogWithSource(
+ { url },
+ {
+ fetchText: vi.fn(async () => JSON.stringify(older)),
+ readCache: vi.fn(async () => JSON.stringify(newer)),
+ writeCache,
+ },
+ );
+
+ expect(loaded.source).toBe('remote');
+ expect(loaded.catalog.providers[0]?.name).toBe(MINIMAL.providers[0]?.name);
+ expect(loaded.catalog.modelRegistry?.updatedAt).toBe('2026-08-01T00:00:00.000Z');
+ 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');
+ const persisted = JSON.parse(writeCache.mock.calls[0]![1]);
+ expect(persisted.modelRegistry.updatedAt).toBe('2026-08-01T00:00:00.000Z');
+ expect(persisted.providers.find((provider: Provider) => provider.id === 'xai')?.name)
+ .toBe('NEWER-LKG-XAI');
+ });
+
+ it('adopts the newer snapshot returned by a serialized LKG commit', async () => {
+ const url = 'https://catalog.example.test/providers.json';
+ const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
+ const newer: Catalog = {
+ ...MINIMAL,
+ modelRegistry: {
+ ...registry,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ },
+ };
+ const older: Catalog = {
+ ...MINIMAL,
+ modelRegistry: {
+ ...registry,
+ updatedAt: '2026-07-30T00:00:00.000Z',
+ },
+ };
+
+ const loaded = await loadCatalogWithSource(
+ { url },
+ {
+ fetchText: vi.fn(async () => JSON.stringify(older)),
+ writeCache: vi.fn(async () => JSON.stringify(newer)),
+ },
+ );
+
+ expect(loaded.source).toBe('remote');
+ expect(loaded.catalog.modelRegistry?.updatedAt).toBe('2026-08-01T00:00:00.000Z');
+ });
+
+ 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 },
+ {
+ fetchText,
+ readCache: vi.fn(async () => JSON.stringify(MINIMAL)),
+ },
+ );
+ expect(fetchText).not.toHaveBeenCalled();
+ expect(cached.source).toBe('cache');
+
+ const invalid = await loadCatalogWithSource(
+ { url, remoteBudgetMs: 0 },
+ {
+ fetchText,
+ readCache: vi.fn(async () => '{"version":"bad","providers":[]}'),
+ },
+ );
+ expect(invalid).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });
+ });
+
it('dev: reads local path, skips network', async () => {
const fetchText = vi.fn();
const io: CatalogIO = { readFile: vi.fn(async () => JSON.stringify(MINIMAL)), fetchText };
@@ -294,16 +473,22 @@ describe('loadCatalog', () => {
});
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));
+ .mockResolvedValueOnce(
+ JSON.stringify({
+ ...MINIMAL,
+ cindyModelMeta: { version: 1, models: { retired: { contextWindow: 1 } } },
+ }),
+ );
const cat = await loadCatalog(
{
baseUrl: 'https://model-access.example.com',
fallbackBaseUrl: 'https://cdn.example.com/cindy',
now: () => 0,
},
- { fetchText },
+ { fetchText, writeCache },
);
expect(fetchText).toHaveBeenNthCalledWith(
1,
@@ -316,10 +501,21 @@ describe('loadCatalog', () => {
expect.any(Number),
);
expect(cat.version).toBe('test');
+ expect(cat).not.toHaveProperty('cindyModelMeta');
+ expect(writeCache).toHaveBeenCalledWith(
+ 'https://cdn.example.com/cindy/cfg/providers.json',
+ expect.any(String),
+ );
+ expect(JSON.parse(writeCache.mock.calls[0]![1])).not.toHaveProperty('cindyModelMeta');
});
it('falls back from invalid public API payload to legacy OSS before bundled', async () => {
const fetchText = vi.fn()
- .mockResolvedValueOnce('{"version":"broken","providers":[]}')
+ .mockResolvedValueOnce(
+ JSON.stringify({
+ ...MINIMAL,
+ cindyModelMeta: { version: 1, models: {} },
+ }),
+ )
.mockResolvedValueOnce(JSON.stringify(MINIMAL));
const cat = await loadCatalog(
{
@@ -342,6 +538,30 @@ describe('loadCatalog', () => {
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'));
+ const readCache = vi.fn(async (scope: string) =>
+ scope === legacyUrl
+ ? JSON.stringify({
+ ...MINIMAL,
+ cindyModelMeta: { version: 1, models: {} },
+ })
+ : null,
+ );
+ const result = await loadCatalogWithSource(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ now: () => 0,
+ },
+ { fetchText, readCache },
+ );
+ expect(result.source).toBe('cache');
+ expect(result.catalog.version).toBe('test');
+ expect(result.catalog).not.toHaveProperty('cindyModelMeta');
+ });
+
it('shares one remote budget across the public API and legacy OSS fallback', async () => {
const now = vi.fn()
.mockReturnValueOnce(1_000)
@@ -411,6 +631,49 @@ describe('loadCatalog', () => {
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']>>();
+ const fetchText = vi.fn(async (url: string) => {
+ throw new Error(`request failed for ${url}`);
+ });
+
+ 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');
+ });
+
+ 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'))
+ .mockResolvedValueOnce(legacyPayload);
+
+ const result = await loadCatalogWithSource(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ now: () => 0,
+ },
+ { fetchText },
+ );
+
+ expect(result).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });
+ expect((Object.prototype as { polluted?: unknown }).polluted).toBeUndefined();
+ });
+
it('falls back to bundled when fetch fails', async () => {
const io: CatalogIO = {
fetchText: vi.fn(async () => {
@@ -575,8 +838,13 @@ describe('registry visibility & sources(运行时注入 fixture)', () => {
name: 'Custom',
source: 'user',
agents: ['claude-code'],
- auth: { method: 'api-key' },
- routing: { 'claude-code': { upstream: 'https://custom.test', authStrategy: 'api-key' } },
+ auth: { method: 'apiKey' },
+ routing: {
+ 'claude-code': {
+ upstream: 'https://custom.test',
+ authStrategy: 'api-key-header',
+ },
+ },
models: {
'claude-code': [model('flux-image-x', { group: 'custom:custom-p' })],
},
diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.ts
index 3248b85c56..e79d9a4c59 100644
--- a/packages/model-providers/src/builtin.ts
+++ b/packages/model-providers/src/builtin.ts
@@ -7,7 +7,7 @@
* - openai:清单来自 codex 模型注册表(models_cache.json,codex-model-discovery 派生),
* 经 active-catalog 注入 codex 并投影 claude-code bridge;本文件零模型。
* - xd(Cindy AI 网关):清单来自 model-access-server GET /models(网关权威,
- * 元数据由服务端 MODEL_METADATA 表下发);本文件零模型。
+ * 元数据由服务端 modelRegistry 下发);本文件零模型。
* - xai:SuperGrok 订阅 OAuth 没有任何列模型通道(官方未提供),清单是唯一
* 必须静态维护的——活在 `catalog/providers.json`(仓内正本 = OSS 发布物 = dev 直读),
* 此处从 json 引入作 bundled 兜底。
@@ -15,20 +15,21 @@
* 身份卡(id / auth / access / routing / titleModel / 媒体模型清单)是随代码走的事实:
* 改它们必然伴随发版(SDK 集成 / 翻译桥 / 网关协议都是代码),所以写死在这里,
* 不再经 OSS 下发。OSS `cfg/providers.json`(v2)只承载 xai 清单 + presets 模板,
- * 外加服务端消费的 `cindyModelMeta` 段(model-access-server 的网关模型元数据
- * 远程覆盖表,经 MODEL_METADATA_URL 指向同一文件热加载;客户端仅 dev 模式
- * 用它本地覆盖 XD 模型元数据以便自测,packaged 不读)。
+ * 模型元数据与参考价只走同目录下严格版本化的 `model-registry.json`。
*
* ⚠️ 顺序契约:BUILTIN_PROVIDERS 的数组序(anthropic → openai → xai → xd)决定
* 选择器分段顺序与 deriveAvailableModels 的 first-wins 去重优先级,不要改动。
*/
import catalogJson from '../catalog/providers.json' with { type: 'json' };
+import modelRegistryJson from '../catalog/model-registry.json' with { type: 'json' };
+import type { ModelRegistry } from '@cindy/model-access-protocol';
import type { Catalog, Provider } from './types.js';
/** 仓内 v2 目录文件(xai 清单 + presets;同一文件发布到 OSS `cfg/providers.json`)。 */
const catalogFile = catalogJson as unknown as Catalog;
+const bundledModelRegistry = modelRegistryJson as unknown as ModelRegistry;
/**
* 把静态目录条目的上下文窗口标记为**已核实**(不 mutate 入参)。
@@ -203,7 +204,6 @@ export const BUILTIN_PROVIDERS: Provider[] = [
export const BUNDLED_CATALOG: Catalog = {
version: catalogFile.version,
providers: BUILTIN_PROVIDERS,
+ modelRegistry: bundledModelRegistry,
...(catalogFile.presets && catalogFile.presets.length > 0 ? { presets: catalogFile.presets } : {}),
- // cindyModelMeta 随目录透传(消费点见 types.ts:服务端 + 客户端展示元数据基线)。
- ...(catalogFile.cindyModelMeta !== undefined ? { cindyModelMeta: catalogFile.cindyModelMeta } : {}),
};
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index 867d835550..9baab2f5d3 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -5,12 +5,11 @@
* `catalog/providers.json`(v2)只承载 xai 静态清单 + presets 模板——它仍是
* ① OSS `cfg/providers.json` 的发布物 ② dev 直读的仓库文件。anthropic/openai/xd
* 的模型清单运行时动态注入(见 apps/desktop maker-host active-catalog),不再进目录文件。
- * 目录文件顶层另有 `cindyModelMeta` 段:那是服务端 model-access-server 消费的
- * 网关模型元数据覆盖表(与客户端目录共用一份 OSS 文件)。客户端侧 parseCatalog 不校验
- * 内容、随目录透传(见 types.ts Catalog.cindyModelMeta);客户端消费点见 types.ts 注释
- * (anthropic 发现条目的展示元数据基线 + dev 模式 XD 元数据覆盖)。
+ * 所有跨端模型元数据统一进入严格版本化的 `modelRegistry`;目录顶层不接受旁路元数据块。
*/
+import { parseModelRegistry } from '@cindy/model-access-protocol';
+
import type { Catalog, Provider, CatalogModel, AgentKind, Effort, ProviderPreset } from './types.js';
import { withVerifiedStaticWindows } from './builtin.js';
import { findReservedOAuthExtraParam } from './provider-oauth.js';
@@ -504,6 +503,9 @@ export function sortPresetsForLocale(presets: ProviderPreset[], locale: string):
export function parseCatalog(input: string | unknown): Catalog {
const obj: unknown = typeof input === 'string' ? JSON.parse(input) : input;
assert(obj && typeof obj === 'object', 'root is not an object');
+ const allowedRootFields = new Set(['version', 'providers', 'presets', 'modelRegistry']);
+ const unknownRootField = Object.keys(obj).find((field) => !allowedRootFields.has(field));
+ assert(!unknownRootField, `catalog.${unknownRootField} is not allowed`);
const catalog = obj as Catalog;
assert(typeof catalog.version === 'string', 'catalog.version missing');
assert(Array.isArray(catalog.providers) && catalog.providers.length > 0, 'catalog.providers missing/empty');
@@ -513,6 +515,11 @@ export function parseCatalog(input: string | unknown): Catalog {
const presets = sanitizePresets((catalog as { presets?: unknown }).presets);
if (presets.length > 0) catalog.presets = presets;
else delete catalog.presets;
+ if ((catalog as { modelRegistry?: unknown }).modelRegistry !== undefined) {
+ const registry = parseModelRegistry((catalog as { modelRegistry: unknown }).modelRegistry);
+ assert(registry.ok, registry.ok ? '' : registry.error);
+ catalog.modelRegistry = registry.value;
+ }
// 远端下发目录与 bundled 同格式:静态条目的窗口是产品侧写定的真实上限,标记为已核实
// (幂等;条目自己表过态时尊重原值)。动态发现的模型不经这里 —— 见 withVerifiedStaticWindows。
//
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index b81e6a5a56..a99c9a594e 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -53,6 +53,22 @@ export {
loadCatalog,
loadCatalogWithSource,
} from './source.js';
+
+export {
+ findModelRegistryRoute,
+ resolveModelReferencePrice,
+} from './modelRegistry.js';
+export type {
+ ResolvedModelReferencePrice,
+ ResolveModelReferencePriceOptions,
+} from './modelRegistry.js';
+export type {
+ ModelReferencePrice,
+ ModelReferencePriceSource,
+ ModelRegistry,
+ ModelRegistryEntry,
+ ModelRegistryRoute,
+} from '@cindy/model-access-protocol';
export type {
CatalogSourceConfig,
CatalogIO,
diff --git a/packages/model-providers/src/modelRegistry.ts b/packages/model-providers/src/modelRegistry.ts
new file mode 100644
index 0000000000..2dfbd140a5
--- /dev/null
+++ b/packages/model-providers/src/modelRegistry.ts
@@ -0,0 +1,142 @@
+import type {
+ ModelAgent,
+ ModelPriceVariant,
+ ModelReferencePrice,
+ ModelRegistry,
+ ModelRegistryEntry,
+ ModelRegistryRoute,
+} from "@cindy/model-access-protocol";
+
+export interface ResolvedModelReferencePrice {
+ entry: ModelRegistryEntry;
+ route: ModelRegistryRoute;
+ price: ModelReferencePrice;
+}
+
+export interface ResolveModelReferencePriceOptions {
+ agent?: ModelAgent;
+ inputTokens?: number;
+ variant?: ModelPriceVariant;
+ /** ISO date or Date; defaults to the current day. */
+ at?: string | Date;
+}
+
+function calendarDate(value: string | Date | undefined): string {
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
+ if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}/.test(value)) {
+ return value.slice(0, 10);
+ }
+ return new Date().toISOString().slice(0, 10);
+}
+
+function routeModelCandidates(providerId: string, modelId: string): string[] {
+ const ids = [modelId];
+ if (providerId === "openai" && modelId.startsWith("chatgpt/")) {
+ ids.push(modelId.slice("chatgpt/".length));
+ }
+ if (providerId === "anthropic") {
+ const undatedModel = modelId.replace(/-\d{8}$/, "");
+ if (undatedModel !== modelId) ids.push(undatedModel);
+ }
+ return ids;
+}
+
+function matchingModelRegistryRoutes(
+ registry: ModelRegistry | null | undefined,
+ providerId: string,
+ modelId: string,
+ agent?: ModelAgent,
+): Array<{ entry: ModelRegistryEntry; route: ModelRegistryRoute }> {
+ if (!registry) return [];
+ const normalizedProviderId = providerId.trim();
+ const normalizedModelId = modelId.trim();
+ const candidates = new Set(
+ routeModelCandidates(normalizedProviderId, normalizedModelId),
+ );
+ const anthropicFamily =
+ normalizedProviderId === "anthropic" &&
+ (normalizedModelId === "opus" ||
+ normalizedModelId === "sonnet" ||
+ normalizedModelId === "haiku")
+ ? `claude-${normalizedModelId}-`
+ : null;
+ const matches: Array<{
+ entry: ModelRegistryEntry;
+ route: ModelRegistryRoute;
+ }> = [];
+ for (const entry of registry.models) {
+ for (const route of entry.routes) {
+ if (
+ route.providerId === normalizedProviderId &&
+ (candidates.has(route.modelId) ||
+ (anthropicFamily !== null &&
+ route.modelId.startsWith(anthropicFamily))) &&
+ (agent === undefined || route.agents.includes(agent))
+ ) {
+ matches.push({ entry, route });
+ }
+ }
+ }
+ return matches;
+}
+
+export function findModelRegistryRoute(
+ registry: ModelRegistry | null | undefined,
+ providerId: string,
+ modelId: string,
+ agent?: ModelAgent,
+): { entry: ModelRegistryEntry; route: ModelRegistryRoute } | undefined {
+ return matchingModelRegistryRoutes(registry, providerId, modelId, agent)[0];
+}
+
+/**
+ * Resolves the currently effective official reference-price band.
+ *
+ * Availability is intentionally out of scope: callers must still use the active provider
+ * catalog / Gateway model list to decide whether the account can actually invoke the model.
+ */
+export function resolveModelReferencePrice(
+ registry: ModelRegistry | null | undefined,
+ providerId: string,
+ modelId: string,
+ options: ResolveModelReferencePriceOptions = {},
+): ResolvedModelReferencePrice | undefined {
+ const matches = matchingModelRegistryRoutes(
+ registry,
+ providerId,
+ modelId,
+ options.agent,
+ );
+ const day = calendarDate(options.at);
+ const inputTokens = options.inputTokens;
+ const variant = options.variant ?? "standard";
+ for (const matched of matches) {
+ const prices = matched.route.referencePrices
+ ?.filter((price) => {
+ if (price.variant !== variant) return false;
+ if (day < price.effectiveFrom) return false;
+ if (price.effectiveUntil !== undefined && day >= price.effectiveUntil)
+ return false;
+ if (inputTokens === undefined) return (price.minInputTokens ?? 0) === 0;
+ if (
+ price.minInputTokens !== undefined &&
+ inputTokens < price.minInputTokens
+ )
+ return false;
+ if (
+ price.maxInputTokens !== undefined &&
+ inputTokens >= price.maxInputTokens
+ )
+ return false;
+ return true;
+ })
+ .sort(
+ (a, b) =>
+ b.effectiveFrom.localeCompare(a.effectiveFrom) ||
+ (b.minInputTokens ?? 0) - (a.minInputTokens ?? 0),
+ );
+ const price = prices?.[0];
+ if (price) return { ...matched, price };
+ }
+ return undefined;
+}
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index c2fca98608..8a1f17dc26 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -3,11 +3,11 @@
*
* - release:优先从 Model Access 公共匿名接口拉取完整 Catalog;失败时回退旧 OSS 目录。
* - dev:直接读仓库本地文件(`localPath`),改了即时生效、默认不联网。
- * - 兜底优先级:本地(dev) → 公共 API → 旧 OSS → 内置 bundled。
+ * - 兜底优先级:本地(dev) → 公共 API → 上次有效快照(LKG) → 旧 OSS → 内置 bundled。
*
- * 目录每进程加载一次、存内存、**无 TTL**(由 host 的 active-catalog 在启动期 await 一次);
- * 本模块刻意**不做磁盘缓存**——公共 API 与迁移期 OSS 都是远端目录源,bundled 是最终兜底,
- * 无需再引入会让「重启即拉最新」失效的磁盘新鲜窗口。
+ * 目录每进程加载一次、存内存、**无 TTL**(由 host 的 active-catalog 在启动期 await 一次)。
+ * host 可注入按源隔离的 LKG 读写:启动仍先请求最新远端,只有远端失败才读缓存,所以不会
+ * 引入“新鲜窗口”;坏 JSON / 坏 schema 永不覆盖最后一份有效快照。
*
* 本模块不碰文件系统 / 网络 / userData——这些能力由 host 通过 `CatalogIO` 注入,
* 保证包可独立单测,也保证跨平台路径 / CORS 等细节留在 host。
@@ -46,11 +46,18 @@ export interface CatalogIO {
fetchText?: (url: string, timeoutMs: number) => Promise<string>;
/** 读本地文件(dev / localPath);不存在返回 null。 */
readFile?: (path: string) => Promise<string | null>;
+ /** 读取某远端 scope 的上次有效完整快照;不存在返回 null。 */
+ readCache?: (scope: string) => Promise<string | null>;
+ /**
+ * 原子保存某远端 scope 的完整有效快照。实现可在串行区内保留磁盘上的更新快照,
+ * 并返回最终胜出的文本,使调用方内存态与 LKG 使用同一版本。
+ */
+ writeCache?: (scope: string, text: string) => Promise<string | void>;
/** 诊断日志(可选)。 */
log?: (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void;
}
-export type CatalogLoadSource = 'local' | 'remote' | 'bundled';
+export type CatalogLoadSource = 'local' | 'remote' | 'cache' | 'bundled';
export interface CatalogLoadResult {
catalog: Catalog;
@@ -79,6 +86,43 @@ export function resolveFallbackCatalogUrl(cfg: CatalogSourceConfig): string | nu
return trimTrailingSlashes(cfg.fallbackBaseUrl.trim()) + CATALOG_CFG_PATH;
}
+/**
+ * The migration-only OSS snapshot used to carry cindyModelMeta beside the provider
+ * 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 {
+ if (!allowLegacyModelMeta) return parseCatalog(input);
+ const raw: unknown = JSON.parse(input);
+ 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;
+ }
+ return parseCatalog(migrated);
+}
+
+/** Strip credentials and request-only URL parts before diagnostics leave this package. */
+function catalogUrlForLog(value: string): string {
+ try {
+ const parsed = new URL(value);
+ parsed.username = '';
+ parsed.password = '';
+ parsed.search = '';
+ parsed.hash = '';
+ return parsed.toString();
+ } catch {
+ return '[redacted invalid catalog URL]';
+ }
+}
+
+function remoteErrorForLog(error: unknown, remoteUrl: string, logUrl: string): string {
+ return String(error).split(remoteUrl).join(logUrl);
+}
+
/** 只给仍保持 bundled 鉴权与上游路由形状的旧条目迁移 access,不能仅凭 provider id 猜计费。 */
function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access'] {
if (primary.auth.method !== bundled.auth.method) return undefined;
@@ -202,13 +246,23 @@ export function mergeWithBundled(primary: Catalog): Catalog {
for (const preset of primaryPresets) {
if (!bundledPresetIds.has(preset.id)) presets.push(preset);
}
- // cindyModelMeta 仍按整段缺省兜底透传(消费点见 types.ts:服务端 + 客户端展示元数据基线)。
- const cindyModelMeta = primary.cindyModelMeta ?? BUNDLED_CATALOG.cindyModelMeta;
+ // modelRegistry 是带 updatedAt 的完整快照,不做逐字段拼接。远端比 bundled 旧时
+ // 保留新版客户端随包快照,避免复现 presets 曾出现的“旧远端遮掉新本地能力”;
+ // 远端较新时整份生效,继续支持 status=retired、route 删除和价格纠错。
+ const selectedRegistry = selectNewerModelRegistry(primary, BUNDLED_CATALOG);
+ // xAI is the only provider whose model list is a static part of this Catalog snapshot. When
+ // bundled wins the registry revision guard, keep its xAI provider with that same snapshot
+ // instead of combining a new registry with an older remote/LKG list.
+ const providers = selectedRegistry.fromFallback && primary.modelRegistry !== undefined
+ ? merged.map((provider) =>
+ provider.id === 'xai' ? (bundledById.get('xai') ?? provider) : provider,
+ )
+ : merged;
return {
version: primary.version,
- providers: merged,
+ providers,
...(presets && presets.length > 0 ? { presets } : {}),
- ...(cindyModelMeta !== undefined ? { cindyModelMeta } : {}),
+ ...(selectedRegistry.modelRegistry ? { modelRegistry: selectedRegistry.modelRegistry } : {}),
};
}
@@ -216,6 +270,47 @@ function log(io: CatalogIO, level: 'info' | 'warn' | 'error', msg: string, meta?
io.log?.(level, `[model-providers] ${msg}`, meta);
}
+function registryUpdatedAt(catalog: Catalog): number | null {
+ const value = catalog.modelRegistry?.updatedAt;
+ if (!value) return null;
+ const timestamp = Date.parse(value);
+ return Number.isFinite(timestamp) ? timestamp : null;
+}
+
+function selectNewerModelRegistry(
+ primary: Catalog,
+ fallback: Catalog,
+): { modelRegistry: Catalog['modelRegistry']; fromFallback: boolean } {
+ const primaryUpdatedAt = registryUpdatedAt(primary);
+ const fallbackUpdatedAt = registryUpdatedAt(fallback);
+ if (
+ fallback.modelRegistry &&
+ fallbackUpdatedAt !== null &&
+ (primaryUpdatedAt === null || fallbackUpdatedAt > primaryUpdatedAt)
+ ) {
+ return { modelRegistry: fallback.modelRegistry, fromFallback: true };
+ }
+ if (primary.modelRegistry) {
+ return { modelRegistry: primary.modelRegistry, fromFallback: false };
+ }
+ return { modelRegistry: fallback.modelRegistry, fromFallback: fallback.modelRegistry !== undefined };
+}
+
+function newerModelRegistry(primary: Catalog, fallback: Catalog): Catalog['modelRegistry'] {
+ return selectNewerModelRegistry(primary, fallback).modelRegistry;
+}
+
+/**
+ * modelRegistry is the only monotonic revision carried by the Catalog today. If it proves the
+ * LKG is newer, preserve that complete snapshot: combining its registry with older remote xAI
+ * providers/presets would create a catalog version that never existed and can reintroduce retired
+ * models. A future top-level Catalog revision may allow finer-grained arbitration.
+ */
+function preserveNewerCachedCatalog(remote: Catalog, cached: Catalog): Catalog {
+ const modelRegistry = newerModelRegistry(remote, cached);
+ return modelRegistry !== remote.modelRegistry ? cached : remote;
+}
+
/**
* 加载目录并返回实际命中的来源。返回值永远包含一个合法 Catalog(最差也回退内置
* bundled),不抛错。来源标记让手动刷新可以把 bundled fallback 视为失败并保留上次
@@ -223,7 +318,7 @@ function log(io: CatalogIO, level: 'info' | 'warn' | 'error', msg: string, meta?
*
* 顺序:
* 1. dev:cfg.localPath + io.readFile → 读本地、合并 bundled、直接返回(不联网)。
- * 2. 远端依次尝试公共 API、迁移期旧 OSS(除非 disableFetch / 无 URL / 无 fetchText)。
+ * 2. 远端依次尝试公共 API、迁移期旧 OSS;每个远端失败后先尝试它自己的 LKG。
* 3. 任意上述来源均不可用 → 内置 bundled。
*/
export async function loadCatalogWithSource(
@@ -248,30 +343,101 @@ export async function loadCatalogWithSource(
const url = resolveCatalogUrl(cfg);
const fallbackUrl = resolveFallbackCatalogUrl(cfg);
if (!cfg.disableFetch && io.fetchText) {
- const remoteUrls = cfg.url?.trim()
- ? [url].filter((value): value is string => !!value)
- : [url, fallbackUrl].filter((value): value is string => !!value);
+ const remoteSources = cfg.url?.trim()
+ ? url
+ ? [{ url, allowLegacyModelMeta: false }]
+ : []
+ : [
+ ...(url ? [{ url, allowLegacyModelMeta: false }] : []),
+ ...(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 deadline = now() + budgetMs;
- for (const remoteUrl of remoteUrls) {
+ for (const { url: remoteUrl, allowLegacyModelMeta } of remoteSources) {
+ const logUrl = catalogUrlForLog(remoteUrl);
const remainingMs = Math.max(0, deadline - now());
- if (remainingMs === 0) {
- log(io, 'warn', 'remote catalog fallback budget exhausted');
- break;
- }
- try {
- const text = await io.fetchText(remoteUrl, remainingMs);
- const parsed = parseCatalog(text);
- log(io, 'info', 'loaded catalog from remote', { url: remoteUrl });
- return { catalog: mergeWithBundled(parsed), source: 'remote' };
- } catch (err) {
- log(io, 'warn', 'remote catalog read/parse failed, trying fallback', {
- url: remoteUrl,
- err: String(err),
+ if (remainingMs > 0) {
+ try {
+ const text = await io.fetchText(remoteUrl, remainingMs);
+ let parsed = parseRemoteCatalog(text, allowLegacyModelMeta);
+ // Never propagate the retired compatibility block into a newly written LKG.
+ let cacheText = allowLegacyModelMeta ? JSON.stringify(parsed) : text;
+ const remoteRegistryUpdatedAt = registryUpdatedAt(parsed);
+ if (io.readCache) {
+ try {
+ const cachedText = await io.readCache(remoteUrl);
+ if (cachedText !== null) {
+ const cached = parseRemoteCatalog(cachedText, allowLegacyModelMeta);
+ const merged = preserveNewerCachedCatalog(parsed, cached);
+ if (merged !== parsed) {
+ parsed = merged;
+ cacheText = JSON.stringify(merged);
+ log(io, 'warn', 'remote catalog registry is older than LKG; preserving complete newer snapshot', {
+ url: logUrl,
+ remoteUpdatedAt: remoteRegistryUpdatedAt,
+ cachedUpdatedAt: registryUpdatedAt(cached),
+ });
+ }
+ }
+ } catch (err) {
+ 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);
+ if (selected !== parsed) {
+ parsed = selected;
+ 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, 'info', 'loaded catalog from remote', { url: logUrl });
+ return { catalog: mergeWithBundled(parsed), source: 'remote' };
+ } catch (err) {
+ 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,
});
}
+ 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 });
+ return { catalog: mergeWithBundled(parsed), source: 'cache' };
+ }
+ } catch (err) {
+ log(io, 'warn', 'cached catalog read/parse failed, trying fallback', {
+ url: logUrl,
+ err: remoteErrorForLog(err, remoteUrl, logUrl),
+ });
+ }
+ }
}
}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 13dbe687a0..192d9d594a 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -17,6 +17,7 @@
* 本包零运行时依赖:`AgentKind` / `Effort` 在此就地定义(与 maker-core 的同名
* 联合保持一致),不 import maker-core,保证可作为独立能力复用。
*/
+import type { ModelRegistry } from '@cindy/model-access-protocol';
/** 承载模型的 agent runtime —— 与 maker-core AgentKind 对齐。 */
export type AgentKind = 'claude-code' | 'codex';
@@ -503,17 +504,11 @@ export interface Catalog {
*/
presets?: ProviderPreset[];
/**
- * model-access-server 的网关模型元数据远程覆盖表(`{ version: 1, models: {...} }`
- * 信封,schema 归服务端所有故此处不建型)。消费方:
- * - 服务端热加载(XD 网关模型元数据权威);
- * - 客户端 **anthropic 动态发现的元数据基线**(active-catalog 合并时用
- * name/group/sortOrder/description/defaultEnabled 覆盖发现条目;动态通道未下发
- * capability 时,efforts/defaultEffort 作为能力基线;上游显式能力始终优先;
- * version !== 1 整段忽略);
- * - dev 模式下本地覆盖服务端下发的 XD 模型元数据以便自测
- * (apps/desktop model-access devMetaOverlay,packaged 不走该覆盖)。
- */
- cindyModelMeta?: unknown;
+ * Cindy 公共模型注册表:统一承载 canonical id、runtime 路由别名、能力元数据与
+ * 厂商公开参考价。它不决定某个账号实际可用哪些模型,也不覆盖 Cindy AI Gateway
+ * 的实时售卖价;动态发现与 `/api/model-access/models` 仍分别是两类事实的权威。
+ */
+ modelRegistry?: ModelRegistry;
}
/**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b8381ece12..c7a3ae1002 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1179,6 +1179,10 @@ importers:
packages/model-providers:
+ dependencies:
+ '@cindy/model-access-protocol':
+ specifier: workspace:*
+ version: link:../../cindy-protocol/packages/model-access-protocol
devDependencies:
'@types/node':
specifier: '*'
@@ -13793,7 +13797,9 @@ snapshots:
metro-runtime: 0.84.4
transitivePeerDependencies:
- '@babel/core'
+ - bufferutil
- supports-color
+ - utf-8-validate
'@react-native/[email protected]': {}
diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjs
index e591021fa2..f7416eef1b 100644
--- a/scripts/__tests__/restart-desktop-remote.test.mjs
+++ b/scripts/__tests__/restart-desktop-remote.test.mjs
@@ -491,3 +491,19 @@ test("devEnvPrefix passes harness envs through on Windows cmd with quote strippi
test("devEnvPrefix omits harness envs when unset (whitelist stays opt-in)", () => {
assert.equal(devEnvPrefix({}, "darwin"), "");
});
+
+test("devEnvPrefix passes explicit model catalog test controls to Desktop", () => {
+ const prefix = devEnvPrefix(
+ {
+ XDT_MODELS_URL: "http://127.0.0.1:43181/api/model-catalog/catalog",
+ XDT_MODELS_PATH: "/tmp/model catalog.json",
+ XDT_DISABLE_MODELS_FETCH: "1",
+ },
+ "darwin",
+ );
+ assert.equal(
+ prefix,
+ "XDT_MODELS_URL='http://127.0.0.1:43181/api/model-catalog/catalog' " +
+ "XDT_MODELS_PATH='/tmp/model catalog.json' XDT_DISABLE_MODELS_FETCH='1' ",
+ );
+});
diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjs
index e26e6d20fa..1de17301a0 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -521,6 +521,11 @@ export function devEnvPrefix(env = process.env, platform = process.platform) {
// endpoint.local.json 文件路径,均由主进程 clientEndpointsService 消费。
['XDT_ENDPOINTS_CDN', env.XDT_ENDPOINTS_CDN],
['XDT_ENDPOINT_MANIFEST_FILE', env.XDT_ENDPOINT_MANIFEST_FILE],
+ // 模型目录闭环调试覆写。dev 默认仍不联网;只有显式给 URL 时,主进程才允许
+ // 从该地址拉取 Catalog。PATH / DISABLE 同步透传,避免 runner 吞掉已有契约。
+ ['XDT_MODELS_URL', env.XDT_MODELS_URL],
+ ['XDT_MODELS_PATH', env.XDT_MODELS_PATH],
+ ['XDT_DISABLE_MODELS_FETCH', env.XDT_DISABLE_MODELS_FETCH],
// 启动即自动打开 DevTools(main 的 ready-to-show 里消费;见 bootstrap-electron)。
// 给"快捷键/菜单打不开 DevTools"的环境兜底,QA 控制台验证依赖它。
['OPEN_DEVTOOLS', env.OPEN_DEVTOOLS],