Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(byok): apply enterprise discounts to estimates and model prices
fmfsaisaiab06696ebdb0
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 80345c87ec..d08bb4bc03 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -1,3 +1,4 @@+import { effectiveGatewayModelCost } from '../../shared/modelPriceQuote.js';import type { ModelDisplayPricing } from '@cindy/model-providers';import {projectProviderMediaModels,@@ -532,41 +533,6 @@ export function isXdCodexAnthropicBridgeModel(modelId: string): boolean {return xdCodexAnthropicBridgeModelIds.has(normalized);}-function nonNegativeFiniteOrUndefined(value: number | undefined): number | undefined {- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;-}--function effectiveGatewayModelCost(model: XdGatewayModelInfo): CatalogModel['cost'] | undefined {- const input = model.inputCostPerToken;- const output = model.outputCostPerToken;- if (- typeof input !== 'number' ||- !Number.isFinite(input) ||- input < 0 ||- typeof output !== 'number' ||- !Number.isFinite(output) ||- output < 0- ) {- return undefined;- }- const discount =- typeof model.costDiscount === 'number' &&- Number.isFinite(model.costDiscount) &&- model.costDiscount > 0 &&- model.costDiscount <= 1- ? model.costDiscount- : 0;- const multiplier = 1 - discount;- const cacheRead = nonNegativeFiniteOrUndefined(model.cacheReadInputTokenCost);- const cacheWrite = nonNegativeFiniteOrUndefined(model.cacheCreationInputTokenCost);- return {- input: input * 1_000_000 * multiplier,- output: output * 1_000_000 * multiplier,- ...(cacheRead !== undefined ? { cacheRead: cacheRead * 1_000_000 * multiplier } : {}),- ...(cacheWrite !== undefined ? { cacheWrite: cacheWrite * 1_000_000 * multiplier } : {}),- };-}-/** base + custom + discovered augment 的合并缓存;null = 待重算(惰性)。 */let merged: Catalog | null = null;/** 当前 registry 的 Anthropic 路由元数据索引;目录变化时与 merged 一起失效。 */diff --git a/apps/desktop/src/main/model-access/__tests__/byokPricing.test.ts b/apps/desktop/src/main/model-access/__tests__/byokPricing.test.tsindex af3f99577a..b3dfd6a1b3 100644--- a/apps/desktop/src/main/model-access/__tests__/byokPricing.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/byokPricing.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import type { ByokModel, ByokProvider } from '@cindy/model-providers';import { buildByokPricing } from '../byokPricing.js';+import { computePriceQuoteTurnMoney, resolveTurnCost } from '../../usage/turnCostCalculator.js';import { gatewayModelPriceQuote, modelPricingKey } from '../../../shared/modelPriceQuote.js';const model: ByokModel = {id: 'byok/a/chat',@@ -23,7 +24,7 @@ const provider = (entry: ByokModel, id = 'byok-a'): ByokProvider => ({models: [entry],});describe('enterprise reference price projection', () => {- it('keeps provider and engine identity, currency and cache rates without the retail discount', () => {+ it('keeps provider and engine identity, currency and cache rates with the enterprise discount', () => {const catalog = buildByokPricing([provider(model),provider({ ...model, currency: 'USD' }, 'byok-b'),@@ -39,7 +40,7 @@ describe('enterprise reference price projection', () => {cacheReadPerMtok: 0,cacheCreatePerMtok: 1,});- expect(quote).not.toHaveProperty('costDiscount');+ expect(quote.costDiscount).toBe(0.5);expect(catalog['byok-a'][modelPricingKey(model.id, 'codex')]).toEqual(quote);expect(catalog['byok-b'][modelPricingKey(model.id, 'pi')].currency).toBe('USD');});@@ -62,3 +63,44 @@ describe('enterprise reference price projection', () => {).toEqual({});});});++// Regression: the directory discount was discarded before reference money calculation.+// Existing tests asserted that loss. Public build -> resolve verifies money and its kind;+// two completed requests in different tiers expose both missing and double discounts. Tier: unit.+describe('enterprise discounted reference money', () => {+ const tokens = { inputTokens: 100, outputTokens: 20, cacheReadTokens: 40, cacheCreateTokens: 10 };+ const larger = { inputTokens: 200, outputTokens: 30, cacheReadTokens: 50, cacheCreateTokens: 20 };+ const pricedModel = (costDiscount?: number): ByokModel => ({+ ...model, currency: 'USD', costDiscount, agents: ['claude-code'],+ perAgent: { 'claude-code': { wireProtocol: 'anthropic-messages' } },+ cacheReadInputTokenCost: 0.0000005,+ tieredPricing: [+ { range: [0, 200], inputCostPerToken: 0.000002, outputCostPerToken: 0.000006 },+ { range: [200, 1000], inputCostPerToken: 0.000004, outputCostPerToken: 0.000012,+ cacheReadInputTokenCost: 0.000001, cacheCreationInputTokenCost: 0.000002 },+ ],+ });+ const context = { providerId: 'byok-a', billingRoute: 'provider-api', accessKind: 'managed', region: 'global' } as const;++ it.each([undefined, 0, 0.2, 1])('applies discount %s once across input, output, caches and request tiers', (discount) => {+ const pricing = buildByokPricing([provider(pricedModel(discount))]);+ const quote = pricing['byok-a'][modelPricingKey(model.id, 'claude-code')];+ const money = computePriceQuoteTurnMoney(tokens, quote, 'USD');+ expect(money?.amount).toBeCloseTo(0.00035 * (1 - (discount ?? 0)), 10);+ const resolved = resolveTurnCost({+ rawModel: model.id, tokens, pricing, context, sdkCostDelta: 99,+ segments: [tokens, larger],+ });+ expect(resolved.money).toMatchObject({ currency: 'USD', kind: 'value-estimate', approximate: true });+ expect(resolved.money?.amount).toBeCloseTo(0.0016 * (1 - (discount ?? 0)), 10);+ expect(resolved.source).toBe('reference');+ expect(quote.inputPerMtok).toBe(2);+ });++ it.each(['alias', 'missing-price'] as const)('keeps %s token-only even with a reported SDK amount', (scenario) => {+ const entry = pricedModel(0.2);+ const pricing = buildByokPricing([provider(scenario === 'missing-price' ? { ...entry, outputCostPerToken: undefined } : entry)]);+ expect(resolveTurnCost({ rawModel: scenario === 'alias' ? 'upstream-alias' : model.id,+ tokens, pricing, context, sdkCostDelta: 99 }).money).toBeNull();+ });+});diff --git a/apps/desktop/src/main/model-access/__tests__/byokProvider.test.ts b/apps/desktop/src/main/model-access/__tests__/byokProvider.test.tsindex 6295b5430f..9d217f4c58 100644--- a/apps/desktop/src/main/model-access/__tests__/byokProvider.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/byokProvider.test.ts@@ -1,4 +1,7 @@import { describe, expect, it } from 'vitest';+import { buildByokPricing } from '../byokPricing.js';+import { resolveModelPricePresentation } from '../../../renderer/lib/modelPricePresentation.js';+import { modelPriceDetailRows, modelPriceDiscountLabelValues } from '../../../renderer/lib/modelPriceFormat.js';import { buildByokProvider, byokNativeConfigs, mergeByokNativeConfigs } from '../byokProvider.js';const credential = {@@ -208,3 +211,39 @@ it.each(['byok-a/chat', 'gpt-6-sol'])('preserves an explicit per-engine null def}, credential });expect(provider.models.pi?.[0]).toMatchObject({ efforts: ['low', 'high'], defaultEffort: null });});++// Regression: BYOK selection/settings displayed undiscounted reference prices.+// Existing provider tests cover capability projection only. Public directory -> provider/quote+// -> shared picker/settings presentation must retain original, effective and discount. Tier: unit.+it.each([undefined, 0, 0.2, 1])('shows enterprise discount %s consistently in picker/settings details', (costDiscount) => {+ const directory = { id: 'byok-a', name: 'Enterprise', connectionRevision: 1,+ models: [{ ...chatModel, costDiscount, inputCostPerToken: 0.000002, outputCostPerToken: 0.000006,+ cacheReadInputTokenCost: 0.0000005, cacheCreationInputTokenCost: 0.000001 }] };+ const projected = buildByokProvider({ provider: directory, credential });+ expect(projected.models.pi?.[0]).toMatchObject({ currency: 'CNY', costDiscount });+ const presentation = resolveModelPricePresentation({+ providerId: directory.id, modelId: chatModel.id, agent: 'pi',+ providers: [{ ...projected, connected: true }],+ gatewayPricing: null, referencePricing: buildByokPricing([directory]),+ });+ expect(presentation?.kind).toBe('priced');+ if (presentation?.kind !== 'priced') throw new Error('missing enterprise price');+ expect(presentation.current.inputPerMtok).toBeCloseTo(2 * (1 - (costDiscount ?? 0)));+ expect(presentation.current.outputPerMtok).toBeCloseTo(6 * (1 - (costDiscount ?? 0)));+ if (costDiscount) {+ expect(presentation.discount).toBeCloseTo(costDiscount);+ expect(presentation.original?.inputPerMtok).toBe(2);+ expect(modelPriceDiscountLabelValues(presentation.discount!)).toEqual({+ percent: costDiscount === 1 ? '100' : '20', rate: costDiscount === 1 ? '0' : '8',+ });+ expect(modelPriceDetailRows(presentation.current, presentation.original)).toEqual([+ { kind: 'input', value: costDiscount === 1 ? '¥0' : '¥1.6', originalValue: '¥2' },+ { kind: 'output', value: costDiscount === 1 ? '¥0' : '¥4.8', originalValue: '¥6' },+ { kind: 'cacheRead', value: costDiscount === 1 ? '¥0' : '¥0.4', originalValue: '¥0.5' },+ { kind: 'cacheCreate', value: costDiscount === 1 ? '¥0' : '¥0.8', originalValue: '¥1' },+ ]);+ } else {+ expect(presentation.original).toBeUndefined();+ expect(presentation.discount).toBeUndefined();+ }+});diff --git a/apps/desktop/src/main/model-access/byokPricing.ts b/apps/desktop/src/main/model-access/byokPricing.tsindex 9735a5d1af..33b7011a3c 100644--- a/apps/desktop/src/main/model-access/byokPricing.ts+++ b/apps/desktop/src/main/model-access/byokPricing.ts@@ -4,7 +4,7 @@ import type { ModelPricingCatalog } from '../../shared/regionalMoney.js';let pricing: ModelPricingCatalog = {};-/** Enterprise reference prices are separate from Cindy retail prices and discounts. */+/** Enterprise reference prices and discounts stay scoped to their own provider. */export function buildByokPricing(providers: readonly ByokProvider[]): ModelPricingCatalog {const result: ModelPricingCatalog = {};for (const provider of providers) {@@ -13,7 +13,7 @@ export function buildByokPricing(providers: readonly ByokProvider[]): ModelPrici// Missing currency is unknown, not a reason to guess from the client's region.if (!model.currency) continue;const quote = gatewayModelPriceQuote(- { ...model, costDiscount: undefined },+ model,model.currency,false,{diff --git a/apps/desktop/src/main/model-access/byokProvider.ts b/apps/desktop/src/main/model-access/byokProvider.tsindex a0ee52ed4a..e95ea79022 100644--- a/apps/desktop/src/main/model-access/byokProvider.ts+++ b/apps/desktop/src/main/model-access/byokProvider.ts@@ -1,3 +1,4 @@+import { effectiveGatewayModelCost } from '../../shared/modelPriceQuote.js';import {isByokImageMode,BUNDLED_CATALOG,@@ -51,8 +52,6 @@ export function buildByokProvider({ provider, credential }: ByokConnection): Proagent === 'pi' ? declaredEfforts.filter((effort) => effort !== 'ultra') : declaredEfforts;const defaultEffort =defaults.defaultEffort !== undefined ? defaults.defaultEffort : model.defaultEffort;- const price = (value: number | undefined) =>- value === undefined ? undefined : value * 1_000_000;const projected: CatalogModel = {id: model.id,name: model.name ?? model.id,@@ -90,12 +89,9 @@ export function buildByokProvider({ provider, credential }: ByokConnection): Pro},}: {}),- cost: {- input: price(model.inputCostPerToken),- output: price(model.outputCostPerToken),- cacheRead: price(model.cacheReadInputTokenCost),- cacheWrite: price(model.cacheCreationInputTokenCost),- },+ currency: model.currency,+ costDiscount: model.costDiscount,+ cost: effectiveGatewayModelCost(model),};const resolved = applyModelMetadata(projected, resolveModelMetadata(BUNDLED_CATALOG.modelRegistry, provider.id, model.id,diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.tsindex d6d78f0fea..4fb8ee5bed 100644--- a/apps/desktop/src/main/usage/turnCostCalculator.ts+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts@@ -2,6 +2,7 @@* 单轮费用计算。定价先看实际 billing route,再看模型;模型名不再决定来源。*/+import { isByokProviderId } from '@cindy/model-providers';import type { CindyRegion } from '@cindy/maker-shared/brand-identity';import { gatewayLedgerCurrency, getModelPriceQuote } from '../../shared/modelPriceQuote.js';@@ -228,7 +229,8 @@ export function computePriceQuoteTurnMoney(: computeGatewayTurnCost(tokens, price);if (standardAmount == null) return null;const discount =- price.source === 'gateway' &&+ (price.source === 'gateway' ||+ (price.source === 'provider-reference' && isByokProviderId(price.providerId))) &&typeof price.costDiscount === 'number' &&Number.isFinite(price.costDiscount) &&price.costDiscount > 0 &&diff --git a/apps/desktop/src/renderer/lib/modelPricePresentation.ts b/apps/desktop/src/renderer/lib/modelPricePresentation.tsindex 64ab1d3d7b..93f0bb7f53 100644--- a/apps/desktop/src/renderer/lib/modelPricePresentation.ts+++ b/apps/desktop/src/renderer/lib/modelPricePresentation.ts@@ -5,7 +5,7 @@* 复制一份必然漂:* 1. XD 实际报价与非 XD 的 Catalog 参考价是**两份独立快照**,只按行来源选快照,* 相同 modelId 不跨 provider 复用或兜底。- * 2. XD 且报价来自 gateway 时要叠 `CatalogModel.cost`(服务端下发的折后展示价),+ * 2. XD Gateway 与企业 BYOK 报价要叠 `CatalogModel.cost`(服务端下发的折后展示价),* 由 `modelPricePresentation` 与标准价跑比例一致性校验后才认定为折扣。* 3. 非 XD 的 `approximate` 报价在展示时抹掉近似标记(`displayQuote`)——* 参考价本身就是估算,再挂一次「近似」是重复表达。@@ -18,7 +18,7 @@import type { AgentKind } from '@/hooks/useAgentCapabilities';import { modelPricePresentation, type ModelPricePresentation } from '@/lib/modelPriceFormat';-import { getModel, type ProviderView } from '@cindy/model-providers';+import { getModel, isByokProviderId, type ProviderView } from '@cindy/model-providers';import { getModelPriceQuote } from '../../shared/modelPriceQuote';import type { ModelPricingCatalog } from '../../shared/regionalMoney';@@ -54,5 +54,10 @@ export function resolveModelPricePresentation({}if (!quote) return null;const displayQuote = quote.approximate ? { ...quote, approximate: false } : quote;- return modelPricePresentation(displayQuote, undefined);+ const provider =+ isByokProviderId(providerId) && quote.source === 'provider-reference'+ ? providers.find((item) => item.id === providerId)+ : undefined;+ const effectiveCost = provider && agent ? getModel(provider, modelId, agent)?.cost : undefined;+ return modelPricePresentation(displayQuote, effectiveCost);}diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.tsindex 6bd57a3b5c..f0144b0544 100644--- a/apps/desktop/src/shared/modelPriceQuote.ts+++ b/apps/desktop/src/shared/modelPriceQuote.ts@@ -1,6 +1,7 @@import {resolveModelReferencePrice,type AgentKind,+ type CatalogModel,type ModelRegistry,} from '@cindy/model-providers';@@ -30,6 +31,34 @@ function normalizedCostDiscount(value: unknown): number | undefined {: undefined;}+/** Catalog display prices for platform and enterprise Gateway models; quotes retain list prices. */+export function effectiveGatewayModelCost(model: Pick<ModelAccessGatewayModel,+ 'inputCostPerToken' | 'outputCostPerToken' | 'cacheReadInputTokenCost' |+ 'cacheCreationInputTokenCost' | 'costDiscount'>): CatalogModel['cost'] | undefined {+ const input = model.inputCostPerToken;+ const output = model.outputCostPerToken;+ if (+ typeof input !== 'number' ||+ !Number.isFinite(input) ||+ input < 0 ||+ typeof output !== 'number' ||+ !Number.isFinite(output) ||+ output < 0+ ) {+ return undefined;+ }+ const discount = normalizedCostDiscount(model.costDiscount) ?? 0;+ const multiplier = 1 - discount;+ const cacheRead = perMtok(model.cacheReadInputTokenCost);+ const cacheWrite = perMtok(model.cacheCreationInputTokenCost);+ return {+ input: input * 1_000_000 * multiplier,+ output: output * 1_000_000 * multiplier,+ ...(cacheRead !== undefined ? { cacheRead: cacheRead * multiplier } : {}),+ ...(cacheWrite !== undefined ? { cacheWrite: cacheWrite * multiplier } : {}),+ };+}+function gatewayInputTokenPriceBands(model: ModelAccessGatewayModel,): ModelPriceQuote['inputTokenPriceBands'] {diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.tsindex 2bc6825b3a..918fffa0f1 100644--- a/apps/desktop/src/shared/regionalMoney.ts+++ b/apps/desktop/src/shared/regionalMoney.ts@@ -56,7 +56,7 @@ export interface ModelPriceQuote {cacheReadPerMtok?: number;cacheCreatePerMtok?: number;}>;- /** Gateway 声明的折扣比例;计费金额按原价 × (1 - costDiscount)。 */+ /** 平台或企业 Gateway 声明的折扣比例;计费金额按原价 × (1 - costDiscount)。 */costDiscount?: number;/*** 该报价的币种不是上游声明的,而是本地按兜底链推断出来的。