Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge remote-tracking branch 'upstream/main' into integration/pi-live-rebased
Chris5286d4a170f5
diff --cc apps/desktop/src/main/hook-control/turnObserver.tsindex 5c7b87fb77,32600cac6f..9f6c14d361--- a/apps/desktop/src/main/hook-control/turnObserver.ts+++ b/apps/desktop/src/main/hook-control/turnObserver.ts@@@ -236,10 -304,10 +304,10 @@@ export function observeHookTurn// (renderer 同款 raw concat), 不同消息之间空行分隔。// ② claude result 兜底 fallbackTail(刻意不带 agentMeta):// 只含 UI 缺的尾段, 与已流增量原样接上。- // ③ codex item.completed: 该条全文, 覆盖已流增量。+ // ③ codex item.completed / pi message_end:该条全文,覆盖已流增量。// ④ 未知 source: 保守用前缀启发式。const src = (ev as { source?: string }).source;- const meta = (ev as { agentMeta?: { uuid?: unknown } }).agentMeta;+ const meta = (ev as { agentMeta?: { uuid?: unknown; requestId?: unknown } }).agentMeta;const claudeTail = src === 'claude-code' && meta === undefined;const segment = claudeTail? streamTail + data.textdiff --cc apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.tsindex 42cc52ed03,070a1dfc26..560aa149bb--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts@@@ -102,10 -114,11 +123,12 @@@ describe('active-catalog discovered augsetDiscoveredCodexModels([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']);+ expect(openaiIds('pi')).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 远端目录的静态段被忽略(清单来源唯一化:注册表快照就是全部)', () => {@@@ -214,19 -237,22 +247,23 @@@ describe('anthropic 发现条目的 modsupportsFastMode: false,})),);+ expect(anthropicList('pi')).toEqual(anthropicList('claude-code'));- 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',diff --cc apps/desktop/src/main/maker-host/active-catalog.tsindex 8bf54fcb4a,cca69a9e01..4c3f5a6a28--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@@ -142,18 -143,10 +143,16 @@@ const VALID_EFFORTS: ReadonlySet<stringtype Effort = CatalogModel['efforts'][number];function xdGatewayTargetAgents(model: XdGatewayModelInfo): AgentKind[] {- return model.agents && model.agents.length > 0 ? model.agents : ['claude-code'];+ const agents: AgentKind[] = model.agents && model.agents.length > 0+ ? [...model.agents]+ : ['claude-code'];+ // Pi 走网关 anthropic-messages 协议,可达面与 claude-code 相同;服务端目录+ // 尚无 pi 概念时按 claude-code 归属镜像,显式声明 pi 后自然不重复。+ if (agents.includes('claude-code') && !agents.includes('pi')) agents.push('pi');+ return agents;}- 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 };@@@ -336,88 -323,74 +335,77 @@@ interface RegistryMetaFieldssortOrder?: 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);++ // 模型 registry 的路由与 perAgent 覆盖只按 claude-code / codex 建键;Pi 是动态 BYOM,++ // 无 registry per-agent 覆盖,按 agent 无关处理(取条目基线元数据)。++ const registryAgent = agent === 'pi' ? undefined : agent;++ const matched = findModelRegistryRoute(catalog.modelRegistry, providerId, modelId, registryAgent);+ if (!matched) return undefined;+ const { entry } = matched;- const perAgent = entry.perAgent?.[agent];++ const perAgent = registryAgent ? entry.perAgent?.[registryAgent] : undefined;+ 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;- }-- 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 });+ /** Registry 是动态发现缺少能力信息时唯一的产品元数据基线。 */+ function buildEffectiveRegistryMetaIndex(): Map<string, RegistryMetaFields> {+ if (effectiveRegistryMetaIndex) return effectiveRegistryMetaIndex;++ 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 {diff --cc apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 17675104f9,4f202e1fa2..e2eeef8370--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@@ -154,8 -153,9 +154,9 @@@ function sessionRunningError(): Errorfunction createHarness() {let running = false;+ let turnGeneration = 0;let pendingInteraction = false;- let agentKind: 'claude-code' | 'codex' | null = 'claude-code';+ let agentKind: AgentInputCreateOpts['agentKind'] | null = 'claude-code';const projections: AgentInputProjection[] = [];const sendToAgent = vi.fn<AgentInputCoordinatorDeps['sendToAgent']>(async (sessionId, _message, _createOpts, sendOpts) => {diff --cc apps/desktop/src/main/maker-ipc/providerHandlers.tsindex ec8ccf69ff,6fb298b704..fc14bbd25d--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@@ -1110,12 -1101,10 +1269,13 @@@ export function registerProviderHandlerawait 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 || !pricesRestored) {+ const credentialsRestored = restoreProviderCredentials(+ providerId,+ credentialSnapshots,+ );- if (!oauthRestored || !credentialsRestored || !overridesRestored) {++ if (!oauthRestored || !credentialsRestored || !overridesRestored || !pricesRestored) {throwIpcError('INTERNAL','provider deletion failed and existing credentials could not be restored',diff --cc apps/desktop/src/main/maker-ipc/register.tsindex df2bea6d5a,61fa31e406..fbf3b5e667--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -137,8 -136,8 +137,9 @@@ importfindParkedEngineSession,getMessageDeletionTarget,listMessagesForAgentHandoff,+ supersedeRetriedUserTurn,} from '../localDb/ipc/messages.js';+import { messageToCamel } from '../localDb/mapper.js';import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';import {applyAgentSwitchToSessionRow,@@@ -297,10 -296,11 +298,11 @@@ importimport { 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 { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey, piSubscriptionUsageModelKey } 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,@@@ -4277,9 -4190,14 +4341,17 @@@ export function registerMakerIpc(maker// 停用写入的归属校验:入口捕获 / 持久化前复核,异步窗口内切账号即拒,防 A 的// 点击写进 B 的 owner-scoped 偏好文件(PR #744 review 第七轮)。currentOwnerId: () => getCurrentDataOwnerId(),+ readCustomProviderHeadersForMutation,+ storeCustomProviderHeaders,+ removeCustomProviderHeaders,+ 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 --cc apps/desktop/src/main/usage/usageHistory.tsindex 68421f1ec3,0adeeb1836..c2489c7842--- a/apps/desktop/src/main/usage/usageHistory.ts+++ b/apps/desktop/src/main/usage/usageHistory.ts@@@ -343,38 -347,29 +347,43 @@@ export function claudeSubscriptionUsagereturn `${displayModelName(model)}#billing=subscription`;}+/** Pi 订阅轮与其它 agent 共用 billing 后缀,但保留独立 agentKind。 */+export function piSubscriptionUsageModelKey(model: string): string {+ return `${displayModelName(model)}#billing=subscription`;+}+/*** 订阅行的估算价选取,按 agent 分流:- * - codex → 订阅直连(chatgpt/ / xai/)静态价 →- * 既有 getCodexSubscriptionValuePrice(网关价 + OpenAI 静态兜底表)- * - pi → 先按订阅直连估价,再回退 Anthropic 价(Pi 可跨三类 provider)- * - claude-code → 网关价表精确条目(带 cache 档价)→ Anthropic 家族牌价兜底- * 两级都 miss → undefined(该行只显示 token,不臆造金额)。+ * - codex → 订阅直连(chatgpt/ / xai/)registry 参考价 → OpenAI registry 参考价+ * → Anthropic registry 参考价(Codex 显式选内置 anthropic 的 Claude.ai 订阅轮;+ * 模型 id 只会命中各自 provider 的路由,依次尝试不会串价)++ * - pi → 先按订阅直连估价,再依次回退 Codex(OpenAI)与 Anthropic registry 参考价++ * (Pi 可跨三类 provider,按模型 id 路由,依次尝试不会串价)+ * - claude-code → Anthropic registry 参考价+ * 各级都 miss → undefined(该行只显示 token,不臆造金额)。*/function getSubscriptionValuePriceFor(- agentKind: 'claude-code' | 'codex',+ agentKind: 'claude-code' | 'codex' | 'pi',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));}+ if (agentKind === 'pi') {+ return (- getSubscriptionDirectValuePrice(model) ??- getCodexSubscriptionValuePrice(model, pricing) ??- getModelPriceQuote(pricing, 'anthropic', model)++ getSubscriptionDirectValuePrice(model, undefined, pricing, at, overrides) ??++ getCodexSubscriptionValuePrice(model, pricing, at, overrides) ??++ getClaudeSubscriptionValuePrice(model, pricing, at, overrides)+ );+ }- return getModelPriceQuote(pricing, 'anthropic', model);+ return getClaudeSubscriptionValuePrice(model, pricing, at, overrides);}async function hydrateFromDisk(expectedOptsKey: string): Promise<UsageHistoryPayload | null> {@@@ -583,9 -581,11 +595,11 @@@ export async function readUsageHistoryWconst hasMissingPendingSubscriptionPrice = modelRows.some((r) =>isSubscriptionUsageModel(r.model) &&!getSubscriptionValuePriceFor(- r.agentKind === 'codex' ? 'codex' : 'claude-code',+ r.agentKind === 'codex' ? 'codex' : r.agentKind === 'pi' ? 'pi' : 'claude-code',displayModelName(r.model),pricing,+ r.day,+ priceOverrides,),);const estimatesPending =diff --cc apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsxindex 0000000000,1031541010..f4ec646fc4mode 000000,100644..100644--- a/apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx@@@ -1,0 -1,360 +1,361 @@@+ 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',++ pi: 'Pi',+ };++ 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 --cc apps/desktop/src/shared/modelPriceQuote.tsindex 7ff5ff6f90,a73855d10e..25ccd92225--- a/apps/desktop/src/shared/modelPriceQuote.ts+++ b/apps/desktop/src/shared/modelPriceQuote.ts@@@ -140,46 -190,77 +190,82 @@@ function referencePriceCalendarDate(valexport 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);++ // 参考价 registry 的 agent 维度只有 claude-code / codex;Pi(动态 BYOM,按 provider/模型++ // 路由)在此按 agent 无关的参考价解析 —— pi 一律降级为 undefined 传给协议函数。++ const resolved = resolveModelReferencePrice(registry, providerId, modelId, {++ ...options,++ agent: options.agent === 'pi' ? undefined : options.agent,++ });+ 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(diff --cc packages/model-providers/src/types.tsindex 744469ff28,192d9d594a..372aa7dd4c--- a/packages/model-providers/src/types.ts+++ b/packages/model-providers/src/types.ts@@@ -17,9 -17,10 +17,10 @@@* 本包零运行时依赖:`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';+export type AgentKind = 'claude-code' | 'codex' | 'pi';/** 推理强度档位 —— 与 maker-core Effort 对齐。 */export type Effort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';