dsh-cost-meter 1.9.2 → 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1058 +1,1063 @@
1
- import { multiplierPath } from './price-multiplier.js'
2
- /**
3
- * dsh-cost-meter 的 Host 面 Typert 清单(由 typert-loader 自动扫描注册)。
4
- * 手写清单,结构与 @deepseek-ai/dsh-typert-generator 产物一致:
5
- * `./typert` 导出 TYPERT;strict codec 同时提供旧宿主的 schema 和新宿主的 create()。
6
- */
7
-
8
- import { z } from 'zod'
9
-
10
- const num = z.number()
11
- const frozenMoney = Object.fromEntries(['costCny', 'apiCostCny', 'costEur', 'apiCostEur'].map(key => [key, num.optional()]))
12
-
13
- const sessionSchema = z.object({
14
- id: z.string(),
15
- title: z.string().optional(),
16
- at: num.optional(),
17
- input: num,
18
- output: num,
19
- cacheRead: num,
20
- cacheWrite: num,
21
- reasoning: num.optional(),
22
- calls: num,
23
- cost: num,
24
- // API 渠道金额(issue #64):真金白银部分;缺席 = 旧快照按 cost 全额 API。
25
- apiCost: num.optional(),
26
- ...frozenMoney,
27
- byProviderModel: z.record(z.string(), z.object({ input: num, output: num, cacheRead: num, cacheWrite: num, reasoning: num.optional(), calls: num, cost: num, apiCost: num.optional(), ...frozenMoney })).optional(),
28
- })
29
-
30
- const daySchema = z.object({
31
- date: z.string(),
32
- input: num,
33
- output: num,
34
- cacheRead: num,
35
- cacheWrite: num,
36
- reasoning: num.optional(),
37
- calls: num,
38
- cost: num,
39
- apiCost: num.optional(),
40
- ...frozenMoney,
41
- byProviderModel: z.record(z.string(), z.object({ input: num, output: num, cacheRead: num, cacheWrite: num, reasoning: num.optional(), calls: num, cost: num, apiCost: num.optional(), ...frozenMoney })).optional(),
42
- sessions: z.array(sessionSchema),
43
- })
44
-
45
- const externalSummarySchema = z.object({ today: daySchema, month: daySchema, total: daySchema, history: z.array(daySchema) })
46
- const externalUsageSchema = z.object({
47
- fetchedAt: num,
48
- stale: z.boolean(),
49
- sources: z.array(externalSummarySchema.extend({ source: z.string() })),
50
- combined: externalSummarySchema,
51
- })
52
-
53
- // 带所属日期的会话条目(issue #22 按会话排行:不分日期视角)。
54
- const datedSessionSchema = sessionSchema.extend({ date: z.string() })
55
-
56
- const topSessionsSchema = z.object({
57
- sessions: z.array(datedSessionSchema),
58
- })
59
-
60
- export const sessionCostSchema = z.object({
61
- own: sessionSchema,
62
- subagents: sessionSchema,
63
- subagentCount: num,
64
- found: z.boolean(),
65
- })
66
- const turnCostRowSchema = z.object({ provider: z.string(), model: z.string(), bucket: z.string(), tokens: num, requests: num.optional(), rate: num, cost: num, priced: z.boolean(), plan: z.boolean() })
67
- const meteringSchema = z.object({ source: z.literal('billion-context'), requestId: z.string(), attempt: num, complete: z.boolean(), status: z.string(), upstream: z.string() }).optional()
68
- export const turnCostSchema = z.object({
69
- found: z.boolean(), cost: num, apiCost: num, ...frozenMoney,
70
- inherited: z.boolean().optional(),
71
- rows: z.array(turnCostRowSchema),
72
- calls: z.array(z.object({ kind: z.string(), provider: z.string(), model: z.string(), atMs: num, cost: num, apiCost: num, plan: z.boolean(), priced: z.boolean(), longContext: z.boolean(), rows: z.array(turnCostRowSchema), metering: meteringSchema })),
73
- })
74
-
75
- export const statisticsQuerySchema = z.object({
76
- displayCurrency: z.enum(['USD', 'CNY', 'EUR']).optional(),
77
- from: z.string().max(10).optional(), to: z.string().max(10).optional(),
78
- provider: z.string().max(512).optional(), model: z.string().max(512).optional(), sessionId: z.string().max(512).optional(),
79
- basis: z.enum(['api', 'plan', 'total']).optional(), offset: z.number().int().min(0).max(1e7).optional(),
80
- turnOffset: z.number().int().min(0).max(1e7).optional(), background: z.boolean().optional(), generation: z.string().max(96).optional(),
81
- })
82
- const statisticsBuckets = z.object(Object.fromEntries(['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost'].map(key => [key, num])))
83
- export const billingStatisticsSchema = z.object({
84
- from: z.string(), to: z.string(), retainedFrom: z.string(), retainedTo: z.string(), totals: statisticsBuckets,
85
- days: z.array(statisticsBuckets.extend({ date: z.string() })),
86
- models: z.array(statisticsBuckets.extend({ key: z.string(), provider: z.string(), model: z.string(), priced: z.boolean() })),
87
- providers: z.array(z.string()), modelOptions: z.array(z.string()),
88
- sessions: z.array(statisticsBuckets.extend({ id: z.string(), title: z.string() })),
89
- sessionCount: num, offset: num, unassignedCost: num, unmodeledCost: num,
90
- })
91
- const sessionBillingCallSchema = turnCostSchema.shape.calls.element.extend({ sessionId: z.string().default(''), turn: num.nullable(), step: num.nullable(), logSeq: num.nullable().default(null) })
92
- export const sessionBillingSchema = turnCostSchema.extend({ refreshing: z.boolean().default(false), generatedAt: num.default(0), refreshFailed: z.boolean().default(false), totalCalls: num, offset: num, recorded: statisticsBuckets,
93
- calls: z.array(sessionBillingCallSchema),
94
- agents: z.array(statisticsBuckets.extend({ id: z.string(), title: z.string() })).default([]),
95
- kinds: z.array(statisticsBuckets.extend({ kind: z.string(), unpriced: z.boolean() })),
96
- turns: z.array(statisticsBuckets.extend({ sessionId: z.string().default(''), turn: num.nullable(), unpriced: z.boolean() })),
97
- totalTurns: num, turnOffset: num,
98
- callShares: z.array(z.object({ index: num, cost: num, apiCost: num, tokens: num, calls: num, other: z.boolean(), unpriced: z.boolean(), call: sessionBillingCallSchema.nullable().default(null) })).default([]),
99
- stepShares: z.object(Object.fromEntries(['cost', 'calls'].map(key => [key, z.array(statisticsBuckets.extend({ sessionId: z.string().default(''), turn: num.nullable(), step: num.nullable(), other: z.boolean(), unpriced: z.boolean() }))]))),
100
- })
101
- export const turnInspectionQuerySchema = z.object({ sessionId: z.string().min(1).max(512), turn: z.number().int().min(0), offset: z.number().int().min(0).max(1e7).optional() })
102
- export const turnInspectionSchema = z.object({ found: z.boolean(), turn: num, input: z.string(), inputTruncated: z.boolean(), totalTools: num, offset: num,
103
- tools: z.array(z.object({ seq: num, step: num.nullable(), name: z.string(), callId: z.string(), atMs: num, arguments: z.string(), result: z.string(), truncated: z.boolean(), status: z.enum(['pending', 'complete', 'error']) })) })
104
-
105
- export const contextCostsQuerySchema = z.object({ sessionId: z.string().min(1).max(512) })
106
- const trajectoryPartsSchema = z.array(z.object({ bucket: z.string(), cost: num, apiCost: num, tokens: num, unpriced: z.boolean() })).default([])
107
- const trajectoryGroupSchema = z.object({ key: z.string(), kind: z.string(), sessionId: z.string().default(''), title: z.string().default(''), tools: z.array(z.string()), steps: num, calls: num.default(0), cost: num, apiCost: num, unpriced: z.boolean(), parts: trajectoryPartsSchema })
108
- export const trajectoryQuerySchema = contextCostsQuerySchema.extend({ displayCurrency: z.enum(['USD', 'CNY', 'EUR']).optional(), basis: z.enum(['api', 'plan', 'total']).default('total'), offset: z.number().int().min(0).max(1e7).default(0),
109
- operation: z.string().max(80).default(''), operationGroup: z.string().max(4096).default(''), stepKey: z.string().max(2048).default(''), detail: z.enum(['full', 'map']).default('full'), ownOnly: z.boolean().default(false),
110
- background: z.boolean().default(false), generation: z.string().max(96).default(''), order: z.enum(['cost', 'time']).default('time'), group: z.string().max(1024).default(''), agent: z.string().max(512).default('') })
111
- export const trajectorySchema = z.object({ refreshing: z.boolean().default(false), generatedAt: num.default(0), refreshFailed: z.boolean().default(false), cost: num, apiCost: num, totalSteps: num, totalCalls: num.default(0), matchingSteps: num.default(0), order: z.enum(['cost', 'time']).default('time'), offset: num,
112
- shares: z.array(z.object({ key: z.string(), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), cost: num, apiCost: num, unpriced: z.boolean(), other: z.boolean(), count: num })),
113
- tiles: z.array(z.object({ key: z.string(), groupKey: z.string(), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), cost: num, apiCost: num, unpriced: z.boolean(), other: z.boolean(), count: num })).default([]),
114
- groups: z.array(trajectoryGroupSchema), operations: z.array(trajectoryGroupSchema).default([]),
115
- operationGroups: z.array(trajectoryGroupSchema.extend({ operationKey: z.string() })).default([]),
116
- distribution: z.array(z.object({ key: z.string(), steps: num, calls: num, cost: num, apiCost: num, unpriced: z.boolean() })).default([]),
117
- hierarchy: z.array(z.object({ id: z.string(), parentId: z.string(), title: z.string(), cost: num, apiCost: num, ownCost: num, ownApiCost: num, steps: num, calls: num, ownSteps: num, ownCalls: num, unpriced: z.boolean().default(false),
118
- groups: z.array(trajectoryGroupSchema), operations: z.array(trajectoryGroupSchema).default([]) })).default([]),
119
- steps: z.array(z.object({ key: z.string(), groupKey: z.string().default(''), typeKey: z.string().default(''), operationKey: z.string().default(''), operationGroupKey: z.string().default(''), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), atMs: num, calls: num, cost: num, apiCost: num, unpriced: z.boolean(), rows: turnCostSchema.shape.rows, callRefs: sessionBillingSchema.shape.calls.default([]) })) })
120
- export const callInspectionQuerySchema = z.object({ sessionId: z.string().min(1).max(512), seq: z.number().int().min(0), atMs: z.number().finite().positive(), offset: z.number().int().min(0).max(1e7).optional() })
121
- export const callInspectionSchema = z.object({ found: z.boolean(), kind: z.string(), input: z.string(), injected: z.string(), skills: z.string(), precedingTools: z.string(), output: z.string(), reasoning: z.string(), truncated: z.boolean(),
122
- tools: z.array(turnInspectionSchema.shape.tools.element.extend({ durationMs: num.nullable().default(null) })), totalTools: num, offset: num })
123
- const contextRateSchema = z.object(Object.fromEntries(['input', 'cacheRead', 'cacheWrite', 'output', 'reasoning'].map(key => [key, z.number().finite().nonnegative()])))
124
- export const contextCostsSchema = z.object({
125
- status: z.enum(['ready', 'busy', 'unavailable', 'session-unavailable', 'meter-unavailable', 'route-unavailable']),
126
- sessionId: z.string(), generatedAt: num, revision: num, provider: z.string(), model: z.string(), basis: z.enum(['api', 'plan']), priced: z.boolean(),
127
- source: z.enum(['none', 'usage', 'estimate']), linked: z.boolean(), contextTokens: z.number().finite().nonnegative(),
128
- components: z.array(z.object({ key: z.enum(['system', 'tools', 'user', 'inject', 'skill', 'assistant', 'tool', 'other']), tokens: z.number().finite().nonnegative() })),
129
- rates: contextRateSchema.nullable(), longContext: contextRateSchema.extend({ aboveInputTokens: z.number().positive() }).nullable(),
130
- lastCall: turnCostSchema.shape.calls.element.extend({ sessionId: z.string().default(''), turn: num.nullable().default(null), step: num.nullable().default(null) }).nullable(),
131
- })
132
-
133
- const longContextSchema = z.object({
134
- aboveInputTokens: z.number().positive(),
135
- cacheHit: z.number().nonnegative(),
136
- cacheMiss: z.number().nonnegative(),
137
- cacheWrite: z.number().nonnegative().optional(),
138
- output: z.number().nonnegative(),
139
- reasoning: z.number().nonnegative().optional(),
140
- })
141
-
142
- const priceTierSchema = z.object({
143
- cacheHit: num,
144
- cacheMiss: num,
145
- cacheWrite: z.number().nonnegative().optional(),
146
- output: num,
147
- reasoning: num.optional(),
148
- })
149
-
150
- const rateHistorySchema = priceTierSchema.extend({
151
- before: z.string(),
152
- offPeak: priceTierSchema.optional(),
153
- peak: priceTierSchema.optional(),
154
- })
155
-
156
- const multiplierShape = {
157
- multiplier: z.number().finite().nonnegative().optional(),
158
- separateMultipliers: z.boolean().optional(),
159
- multipliers: z.record(z.string().regex(multiplierPath), z.number().finite().nonnegative()).optional(),
160
- }
161
- const providerPriceSchema = z.object({
162
- ...multiplierShape,
163
- cacheHit: num.optional(),
164
- cacheMiss: num.optional(),
165
- input: num.optional(),
166
- cachedInput: num.optional(),
167
- cacheRead: num.optional(),
168
- cacheWrite: z.number().nonnegative().optional(),
169
- cny: priceTierSchema.optional(),
170
- longContext: longContextSchema.optional(),
171
- offPeak: priceTierSchema.optional(),
172
- peak: priceTierSchema.optional(),
173
- cacheCreation5m: num.optional(),
174
- cacheCreation1h: num.optional(),
175
- output: num.optional(),
176
- reasoning: num.optional(),
177
- unpriced: z.boolean().optional(),
178
- billingMode: z.enum(['flat', 'deepseek-peak', 'utc-peak', 'batch']).optional(),
179
- sourceUrl: z.string().optional(),
180
- checkedAt: z.string().optional(),
181
- notes: z.string().optional(),
182
- })
183
-
184
- const catalogEntrySchema = providerPriceSchema.extend({
185
- cacheHit: num.optional(), cacheMiss: num.optional(), legacy: z.boolean().optional(),
186
- offPeak: priceTierSchema.optional(), peak: priceTierSchema.optional(), legacyBase: priceTierSchema.optional(),
187
- rateHistory: z.array(rateHistorySchema).max(16).optional(),
188
- })
189
- const priceCatalogSchema = z.record(z.string(), z.record(z.string(), z.record(z.string(), catalogEntrySchema)))
190
-
191
- const priceSchema = z.object({
192
- ...multiplierShape,
193
- cacheHit: num,
194
- cacheMiss: num,
195
- cacheWrite: z.number().nonnegative().optional(),
196
- longContext: longContextSchema.optional(),
197
- output: num,
198
- reasoning: num.optional(),
199
- billingMode: z.enum(['flat', 'deepseek-peak', 'utc-peak', 'batch']).optional(),
200
- offPeak: priceTierSchema.optional(),
201
- peak: priceTierSchema.optional(),
202
- legacy: z.boolean().optional(),
203
- legacyBase: priceTierSchema.optional(),
204
- rateHistory: z.array(rateHistorySchema).max(16).optional(),
205
- sourceUrl: z.string().optional(),
206
- checkedAt: z.string().optional(),
207
- notes: z.string().optional(),
208
- })
209
-
210
- const configSchema = z.object({
211
- locale: z.enum(['auto', 'zh', 'en']),
212
- position: z.enum(['dock', 'header', 'off']),
213
- sidebar: z.boolean(),
214
- currency: z.string(),
215
- symbol: z.string(),
216
- decimals: num,
217
- exchangeRate: num,
218
- exchangeRateAuto: z.boolean().optional(),
219
- fxRates: z.object({ USD: num, CNY: num, EUR: num }).optional(),
220
- exchangeRateCheckedAt: num.optional(), exchangeRateDate: z.string().optional(),
221
- // 官方价格币种(issue #47):USD(美元官方价) | CNY(人民币官方价,按汇率折算入账)。
222
- pricingCurrency: z.enum(['USD', 'CNY']).optional(),
223
- peakEnabled: z.boolean(),
224
- peakEffectiveAt: z.string(),
225
- peakWindows: z.array(z.object({ start: num, end: num })),
226
- peakHolidays: z.array(z.string()),
227
- peakNotice: z.boolean().optional(),
228
- // 峰/谷切换前弹窗提醒:开关(默认开)/提前分钟数(1-30)/类型(峰|谷|两者)。
229
- peakAlertEnabled: z.boolean().optional(),
230
- peakAlertAhead: num.optional(),
231
- peakAlertTarget: z.enum(['peak', 'offpeak', 'both']).optional(),
232
- peakAlertPosition: z.enum(['corner', 'center']).optional(),
233
- peakAlertWebNotify: z.boolean().optional(),
234
- showSessionId: z.boolean().optional(),
235
- // UI 隐藏开关(issues #45/#46):开启后官方余额/今日消耗金额的对应 UI 区块整体不渲染。
236
- hideOfficialBalance: z.boolean().optional(),
237
- hideBudget: z.boolean().optional(),
238
- hideTodayCost: z.boolean().optional(),
239
- hideSessionCostHeader: z.boolean().optional(),
240
- hideSessionCostDock: z.boolean().optional(),
241
- hideTurnCost: z.boolean().optional(),
242
- sessionCostCompact: z.boolean().optional(),
243
- contextCostsEnabled: z.boolean().optional(),
244
- contextCostsPromptSeen: z.boolean().optional(),
245
- sidebarTodayMetric: z.enum(['cost', 'tokens']).optional(),
246
- // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计。
247
- statisticsBasis: z.enum(['auto', 'api', 'plan', 'total']).optional(),
248
- showTotalWithPlan: z.boolean().optional(),
249
- includeSubagentCost: z.boolean().optional(),
250
- codexQuotaEnabled: z.boolean().optional(),
251
- codexQuotaSidebar: z.boolean().optional(),
252
- // dsh-codex-subscription 兼容:一次性历史归类提示是否永久关闭 / 历史归类完成时刻 ms(0 = 未应用)。
253
- codexCompatPromptDismissed: z.boolean().optional(),
254
- codexCompatHistoryAppliedAt: num.optional(),
255
- sidebarSimple: z.boolean().optional(),
256
- sidebarSimplePromptSeen: z.boolean().optional(),
257
- sidebarModels: z.object({ enabled: z.boolean(), period: z.enum(['today', 'history']), topN: z.number().int().min(1).max(10), summary: z.enum(['total', 'top']), position: z.enum(['first', 'afterBalance', 'last']), defaultOpen: z.boolean(), remember: z.boolean(), tokens: z.boolean(), shares: z.boolean(), refreshSeconds: z.number().int().min(10).max(60), dock: z.boolean() }).strict().optional(),
258
- sidebarStyle: z.enum(['standard', 'compact']).optional(),
259
- priceMatchDismissed: z.array(z.string()).optional(),
260
- // 安装前历史自动导入完成时刻(issue #27,内部标记;0/缺席 = 尚未跑过)。
261
- legacyAutoImportedAt: num.optional(),
262
- peakStyle: z.enum(['compact', 'classic']).optional(),
263
- priceMatch: z.enum(['auto', 'exact']).optional(),
264
- priceOverrides: z.record(z.string(), z.string()).optional(),
265
- priceTableDisplay: z.record(z.string(), z.boolean()).optional(),
266
- // prices 可缺席:轮询路径在客户端已持有同一版本时会省略整张价格表(占载荷
267
- // 56%,实测 157.4/281.5 KB),客户端按 pricesRev 沿用它自己的上一份。
268
- // 显式 RPC 与首次加载一律携带完整 prices,故旧客户端不受影响。
269
- prices: z.object({
270
- custom: z.record(z.string(), priceTierSchema.extend({ ...multiplierShape, currency: z.enum(['USD', 'CNY']), billingMode: z.literal('flat').optional() })).optional(),
271
- // 价表币种标记(issue #47,fetchPrices 写入;zod 默认 strip 未知键,须显式声明才能下发)。
272
- currency: z.enum(['USD', 'CNY']).optional(),
273
- models: z.record(z.string(), priceSchema),
274
- default: priceSchema,
275
- providers: z.record(z.string(), z.object({ models: z.record(z.string(), providerPriceSchema) })).optional(),
276
- }).optional(),
277
- budget: z.object({
278
- enabled: z.boolean(),
279
- amount: num,
280
- period: z.enum(['day', 'month', 'all', 'custom']),
281
- customStart: z.union([z.string(), z.null()]),
282
- customEnd: z.union([z.string(), z.null()]),
283
- detail: z.boolean(),
284
- }),
285
- codingPlans: z.record(z.string(), z.object({
286
- enabled: z.boolean().optional(),
287
- display: z.enum(['sidebar', 'settings', 'both', 'off']).optional(),
288
- refreshMinutes: num.optional(),
289
- apiKey: z.string().optional(),
290
- baseUrl: z.string().optional(),
291
- orgId: z.string().optional(),
292
- workspaceId: z.string().optional(),
293
- factoryPool: z.enum(['standard', 'core', 'both']).optional(),
294
- // SCNet 本地计量专用(issue #26):月度 Credits 额度与订阅起始日;其余厂商无此二键。
295
- planCredits: num.optional(),
296
- planStart: z.string().optional(),
297
- quotaSource: z.enum(['local', 'cli', 'bailian']).optional(),
298
- // 千问 Token Plan 抵扣率覆盖(issue #78):归一模型名 → 三费率;仅千问有此键。
299
- rates: z.record(z.string(), z.object({
300
- input: num,
301
- cachedInput: num,
302
- output: num,
303
- })).optional(),
304
- // 火山方舟双凭据(issue #60):AccessKeyID + SecretAccessKey
305
- accessKeyId: z.string().optional(),
306
- secretAccessKey: z.string().optional(),
307
- // 密钥配置状态(v1.6.8):密钥改由 DSH 凭据库托管后,apiKey/accessKeyId/secretAccessKey
308
- // 恒为空串,前端靠这两个描述性字段渲染 write-only 输入框(永不拿到密钥值本身)。
309
- keyConfigured: z.boolean().optional(),
310
- keySource: z.string().optional(),
311
- })).optional(),
312
- balance: z.object({
313
- display: z.enum(['sidebar', 'settings', 'both', 'off']),
314
- refreshMinutes: num,
315
- showProgressBar: z.boolean().optional(),
316
- budgetCap: z.union([num, z.null()]).optional(),
317
- reconcile: z.boolean().optional(),
318
- // 更新后提醒:余额图框点击刷新引导是否已处理(issue #37,内部标记)。
319
- clickHintSeen: z.boolean().optional(),
320
- }),
321
- goQuota: z.object({
322
- enabled: z.boolean(),
323
- display: z.enum(['sidebar', 'settings', 'both', 'off']),
324
- refreshMinutes: num,
325
- // v1.6.8 起恒为空串:密钥由 DSH 凭据库托管,不再落盘也不再下发。
326
- apiKey: z.string(),
327
- main: z.enum(['rolling', 'weekly', 'monthly']),
328
- detail: z.boolean(),
329
- // 密钥配置状态(v1.6.8):见 codingPlans 同名字段的说明。
330
- keyConfigured: z.boolean().optional(),
331
- keySource: z.string().optional(),
332
- }),
333
- customBalance: z.object({
334
- adapter: z.enum(['custom', 'aliyun', 'tokenrhythm']).optional(),
335
- enabled: z.boolean(),
336
- label: z.string(),
337
- labelEn: z.string().optional(),
338
- display: z.enum(['sidebar', 'settings', 'both', 'off']),
339
- unit: z.enum(['USD', 'CNY', 'EUR', 'CREDITS']).optional(),
340
- convertToDisplayCurrency: z.boolean().optional(),
341
- allowInsecureHttp: z.boolean().optional(),
342
- refreshMinutes: num,
343
- request: z.object({
344
- url: z.string(),
345
- method: z.string().optional(),
346
- headers: z.record(z.string(), z.string()).optional(),
347
- body: z.unknown().optional(),
348
- }),
349
- extract: z.record(z.string(), z.unknown()),
350
- allowedHosts: z.array(z.string()).optional(),
351
- }).optional(),
352
- // 多配置形态(v1.7.0,issue #79):自定义 Provider 余额多条并行,数组为运行期
353
- // 真源;customBalance 单配置键仅为旧客户端兼容保留(= entries[0] 的镜像)。
354
- customBalances: z.array(z.object({
355
- adapter: z.enum(['custom', 'aliyun', 'tokenrhythm']).optional(),
356
- enabled: z.boolean(),
357
- label: z.string(),
358
- labelEn: z.string().optional(),
359
- display: z.enum(['sidebar', 'settings', 'both', 'off']),
360
- unit: z.enum(['USD', 'CNY', 'EUR', 'CREDITS']).optional(),
361
- convertToDisplayCurrency: z.boolean().optional(),
362
- allowInsecureHttp: z.boolean().optional(),
363
- refreshMinutes: num,
364
- request: z.object({
365
- url: z.string(),
366
- method: z.string().optional(),
367
- headers: z.record(z.string(), z.string()).optional(),
368
- body: z.unknown().optional(),
369
- }),
370
- extract: z.record(z.string(), z.unknown()),
371
- allowedHosts: z.array(z.string()).optional(),
372
- })).optional(),
373
- gatewayQuotas: z.object({
374
- sources: z.array(z.object({
375
- id: z.string(),
376
- type: z.literal('cliproxyapi'),
377
- label: z.string(),
378
- baseURL: z.string(),
379
- enabled: z.boolean(),
380
- display: z.enum(['sidebar', 'settings', 'both', 'off']),
381
- refreshMinutes: num,
382
- includeProviders: z.array(z.string()),
383
- allowedHosts: z.array(z.string()),
384
- allowInsecureHttp: z.boolean(),
385
- // 只显示 Antigravity 的 Gemini 原生组(过滤 Claude/GPT 第三方模型池);缺省不开启。
386
- antigravityOnlyGemini: z.boolean().optional(),
387
- // 派生凭据变量名(issue #87):客户端据此定位 write-only 目标,非敏感。
388
- keyVar: z.string().optional(),
389
- })),
390
- }).optional(),
391
- corner: z.object({
392
- enabled: z.boolean(),
393
- goRolling: z.boolean(),
394
- goWeekly: z.boolean(),
395
- goMonthly: z.boolean(),
396
- budget: z.boolean(),
397
- }),
398
- // 输入框上方额度横条(v1.5.27):预算/Go/Coding Plan 用量横条 + 首次引导标记。
399
- quotaStrip: z.object({
400
- enabled: z.boolean(),
401
- budget: z.boolean(),
402
- go: z.boolean(),
403
- plans: z.boolean(),
404
- promptSeen: z.boolean(),
405
- }),
406
- // 进度条方向(issue #67):balance/budget/go/plan 各自 remaining | used。
407
- barDirections: z.object({
408
- balance: z.enum(['remaining', 'used']),
409
- budget: z.enum(['remaining', 'used']),
410
- go: z.enum(['remaining', 'used']),
411
- plan: z.enum(['remaining', 'used']),
412
- }).optional(),
413
- // Token 用量统计显示位置(当前固定 cost;键保留供读侧白名单)。
414
- usage: z.object({ position: z.enum(['cost', 'general', 'section']) }).optional(),
415
- // Plan/API 双轨计费分类(issue #64):providers 值 auto/plan/api;models 为 provider:model 显式覆盖。
416
- planBilling: z.object({
417
- providers: z.record(z.string(), z.enum(['auto', 'plan', 'api'])),
418
- models: z.record(z.string(), z.enum(['plan', 'api'])),
419
- modelPlans: z.record(z.string(), z.enum(['opendesign', 'anthropic', 'zai', 'minimax', 'kimi', 'openrouter', 'siliconflow', 'commandcode', 'scnet', 'volcengine', 'qwen', 'mimo', 'factory', 'go', 'codex', 'volcengine-agent', 'tencent-coding', 'tencent-token', 'baidu-coding'])).optional(),
420
- }).optional(),
421
- historyDays: num,
422
- fetchedAt: z.union([z.string(), z.null()]),
423
- priceSource: z.string(),
424
- })
425
-
426
- const balanceSchema = z.object({
427
- keyConfigured: z.boolean().optional(),
428
- keySource: z.string().optional(),
429
- status: z.enum(['off', 'ok', 'error']),
430
- message: z.string(),
431
- fetchedAt: num,
432
- currency: z.string(),
433
- totalBalance: num,
434
- grantedBalance: num,
435
- toppedUpBalance: num,
436
- })
437
-
438
- const goWindowSchema = z.union([
439
- z.object({ percent: num, resetsAt: z.string() }),
440
- z.null(),
441
- ])
442
-
443
- const goQuotaSchema = z.object({
444
- status: z.enum(['off', 'ok', 'error']),
445
- message: z.string(),
446
- fetchedAt: num,
447
- rolling: goWindowSchema,
448
- weekly: goWindowSchema,
449
- monthly: goWindowSchema,
450
- })
451
-
452
- const customBalanceSchema = z.object({
453
- status: z.enum(['off', 'ok', 'error']),
454
- message: z.string(),
455
- fetchedAt: num,
456
- label: z.string(),
457
- unit: z.string(),
458
- remaining: num,
459
- maxBudget: z.union([num, z.null()]),
460
- spend: z.union([num, z.null()]),
461
- // 条目索引(v1.7.0,issue #79):多配置形态下每条快照自带其在
462
- // config.customBalances 中的下标,客户端据此定位刷新按钮对应的条目。
463
- index: num.optional(),
464
- })
465
-
466
- const gatewayWindowSchema = z.object({
467
- id: z.string().max(96),
468
- label: z.string().max(160),
469
- percent: num.min(0).max(100).optional(),
470
- resetsAt: z.union([z.string(), z.null()]),
471
- periodHours: z.union([num, z.null()]),
472
- scope: z.string().max(32),
473
- })
474
- const gatewayCreditsSchema = z.object({
475
- unit: z.string().max(32),
476
- used: z.union([num, z.null()]),
477
- remaining: z.union([num, z.null()]),
478
- limit: z.union([num, z.null()]),
479
- fetchedAt: z.union([z.string(), z.null()]),
480
- packages: z.array(z.object({
481
- id: z.string().max(96), label: z.string().max(160), used: z.union([num, z.null()]),
482
- remaining: z.union([num, z.null()]), limit: z.union([num, z.null()]),
483
- startsAt: z.union([z.string(), z.null()]), resetsAt: z.union([z.string(), z.null()]),
484
- })).max(32),
485
- })
486
- const gatewayAccountSchema = z.object({
487
- id: z.string().max(64), provider: z.enum(['antigravity', 'claude', 'codex', 'kimi', 'xai', 'workbuddy']), label: z.string().max(160),
488
- status: z.enum(['ok', 'partial', 'unknown', 'error', 'stale', 'unsupported', 'capability_missing']),
489
- message: z.string(), windows: z.array(gatewayWindowSchema),
490
- plan: z.string().optional(), credits: gatewayCreditsSchema.optional(),
491
- })
492
- const gatewayQuotaSchema = z.object({
493
- id: z.string().max(48), type: z.literal('cliproxyapi'), label: z.string().max(80),
494
- status: z.enum(['off', 'loading', 'ok', 'partial', 'stale', 'error']),
495
- message: z.string(), fetchedAt: num, attemptedAt: num,
496
- serverVersion: z.string(), keyConfigured: z.boolean(), keySource: z.string(),
497
- accounts: z.array(gatewayAccountSchema), unsupportedProviders: z.array(z.string()),
498
- })
499
-
500
- // Coding plan 额度状态条目(运行时合并配置与查询结果;windows 为各用量窗口)。
501
- const codingPlanSchema = z.object({
502
- enabled: z.boolean(),
503
- display: z.enum(['sidebar', 'settings', 'both', 'off']),
504
- refreshMinutes: num,
505
- // v1.6.8 起恒为空串(密钥已改由 DSH 凭据库托管):仅保留字段以兼容旧客户端。
506
- apiKey: z.string(),
507
- baseUrl: z.string().optional(),
508
- orgId: z.string().optional(),
509
- workspaceId: z.string().optional(),
510
- factoryPool: z.enum(['standard', 'core', 'both']).optional(),
511
- // 密钥配置状态(v1.6.8):是否已在凭据库中配置,以及来自哪一层(env / file / legacy)。
512
- keyConfigured: z.boolean().optional(),
513
- keySource: z.string().optional(),
514
- status: z.enum(['off', 'ok', 'error']),
515
- message: z.string(),
516
- fetchedAt: num,
517
- windows: z.record(z.string(), z.object({ percent: num.optional(), resetsAt: z.string(), text: z.string().optional(), unlimited: z.boolean().optional() })),
518
- // 百炼 CLI 缺少额度查询所需的控制台凭据时显示登录按钮。
519
- loginRequired: z.boolean().optional(),
520
- // 本地计量配置透传(仅 scnet / qwen 有;settings 页编辑入口需要看到当前值)。
521
- planCredits: num.optional(),
522
- planStart: z.string().optional(),
523
- quotaSource: z.enum(['local', 'cli', 'bailian']).optional(),
524
- rates: z.record(z.string(), z.object({
525
- input: num,
526
- cachedInput: num,
527
- output: num,
528
- })).optional(),
529
- })
530
-
531
- // Token Plan 统计(issue #64):每 provider×window 的本地聚合、每 1%/满窗估算与采样区间序列。
532
- const planWindowStatSchema = z.object({
533
- percent: num,
534
- resetsAt: z.string(),
535
- localTokens: num,
536
- localCost: num,
537
- method: z.enum(['sample', 'live', 'none']),
538
- // 采样差分估算的基准时刻(最近有效区间终点;live/none 为 null)
539
- sampleAt: z.union([num, z.null()]).optional(),
540
- // 置信分档(v1.5.53):high = 差分跨度 Δp ≥ 5(个位量化误差 ≤ ±10%);
541
- // low = 跨度不足或 live 回退,结果波动大;none 方法为 null。缺席 = 旧快照。
542
- confidence: z.union([z.enum(['high', 'low']), z.null()]).optional(),
543
- per1Tokens: z.union([num, z.null()]),
544
- per1Cost: z.union([num, z.null()]),
545
- fullTokens: z.union([num, z.null()]),
546
- fullCost: z.union([num, z.null()]),
547
- sampleCount: num,
548
- })
549
- const planIntervalSchema = z.object({
550
- t0: num,
551
- t1: num,
552
- tokens: num,
553
- cost: num,
554
- pct: num,
555
- per1Tokens: num,
556
- per1Cost: num,
557
- })
558
- const planProviderStatSchema = z.object({
559
- windows: z.record(z.string(), planWindowStatSchema),
560
- intervals: z.record(z.string(), z.array(planIntervalSchema)),
561
- })
562
- const planStatsSchema = z.object({
563
- generatedAt: num,
564
- providers: z.record(z.string(), planProviderStatSchema),
565
- })
566
-
567
- export const stateSchema = z.object({
568
- today: daySchema,
569
- month: daySchema,
570
- total: daySchema,
571
- budgetUsed: num,
572
- balance: balanceSchema,
573
- goQuota: goQuotaSchema,
574
- // optional:兼容旧快照/降级路径(与 codingPlans/priceCatalog 同策略,避免 strict codec 击穿)。
575
- customBalance: customBalanceSchema.optional(),
576
- // 多配置形态(v1.7.0,issue #79):每条独立快照;customBalance 单条键为
577
- // 旧客户端兼容镜像(= 第一条 sidebar 可见条目或 entries[0])。
578
- customBalances: z.array(customBalanceSchema).optional(),
579
- gatewayQuotas: z.array(gatewayQuotaSchema).optional(),
580
- // 自定义余额 {{VAR}} 占位符的凭据状态(v1.7.6,issue #86):变量名 → 是否已配置/来源。
581
- // 只含 describe 摘要,不含密钥值;旧快照缺席时视为空表。
582
- customVarStatus: z.record(z.string(), z.object({
583
- configured: z.boolean(),
584
- source: z.string(),
585
- })).optional(),
586
- // 余额差交叉校验提示(issue #18):旧快照无此字段,optional 防击穿。
587
- reconcile: z.object({ ok: z.boolean(), message: z.string() }).optional(),
588
- codingPlans: z.record(z.string(), codingPlanSchema),
589
- // Token Plan 统计(issue #64);缺席 = 旧快照/降级路径。
590
- planStats: planStatsSchema.optional(),
591
- history: z.array(daySchema),
592
- externalUsage: externalUsageSchema.optional(),
593
- billionContext: z.object({ protocol: num, connected: z.boolean(), failed: z.boolean(), requests: num, unreported: num, partial: num, uncovered: num,
594
- detected: z.boolean().optional(), version: z.string().optional(), compatibility: z.enum(['unknown', 'ready', 'needs_update', 'changed', 'bridge_missing']).optional(), noticeId: z.string().optional() }).optional(),
595
- // dsh-codex-subscription 兼容(契约 C):仅在该插件安装时下发;键缺席 = 旧宿主 / 未安装,
596
- // strict codec 会丢弃未声明字段,故必须显式声明整棵状态树。
597
- codexCompat: z.object({
598
- installed: z.boolean(),
599
- version: z.string(),
600
- detection: z.enum(['package', 'profile', 'none']),
601
- planClass: z.enum(['auto', 'plan', 'api']),
602
- usage: z.object({ calls: num, cost: num, tokens: num, days: num, providers: z.array(z.string()) }),
603
- historyAppliedAt: num,
604
- promptDismissed: z.boolean(),
605
- promptDue: z.boolean(),
606
- }).optional(),
607
- config: configSchema,
608
- // 价格表版本号(宿主进程内唯一前缀 + 递增计数):客户端回传该值,一致时宿主
609
- // 省略 config.prices(占轮询载荷 56%)。缺席 = 旧宿主,客户端照常收全量。
610
- pricesRev: z.string().optional(),
611
- // 手改过价格的 OpenRouter 模型 id:前端标注「已自定义 · 不会被自动同步覆盖」。
612
- // 与刷新跳过覆盖的判定同源;无锁定时不下发本字段(旧快照兼容)。
613
- priceLockIds: z.array(z.string()).optional(),
614
- // 存量密钥迁移提示(v1.6.8):仅在有密钥未能自动导入凭据库时出现,值为环境变量名。
615
- secretMigration: z.object({ pending: z.array(z.string()) }).optional(),
616
- meta: z.object({
617
- locale: z.enum(['zh', 'en']).optional(),
618
- now: num,
619
- timezoneOffsetMinutes: num,
620
- // 宿主机 IANA 时区名(issue #74):与浏览器时区错位时前端显示提示;缺席 = 宿主取不到时区名。
621
- timezone: z.string().optional(),
622
- dayKey: z.string(),
623
- monthKey: z.string(),
624
- }),
625
- })
626
-
627
- const patchSchema = z.record(z.string(), z.unknown())
628
-
629
- const openRouterCatalogSchema = z.object({
630
- fetchedAt: z.string(), stale: z.boolean(), error: z.string(),
631
- models: z.array(z.object({
632
- id: z.string(), name: z.string(), contextLength: z.number().int().nonnegative().nullable(),
633
- input: z.number().nonnegative(), output: z.number().nonnegative(),
634
- cachedInput: z.number().nonnegative().nullable(), cacheWrite: z.number().nonnegative().nullable(),
635
- })),
636
- })
637
-
638
- const fetchPricesSchema = z.object({
639
- ok: z.boolean(),
640
- message: z.string(),
641
- state: stateSchema.optional(),
642
- })
643
-
644
- const strictCodec = (name, schema) => ({ mode: 'strict', typeSymbol: 'dsh-cost-meter#' + name, schema, create: () => schema })
645
- const _state$codec = strictCodec('CostState', stateSchema)
646
- const _patch$codec = strictCodec('ConfigPatch', patchSchema)
647
- const _fetch$codec = strictCodec('FetchPricesResult', fetchPricesSchema)
648
- const _repricingHistory$codec = strictCodec('RepricingHistory', z.array(z.object({ ...Object.fromEntries(['at', 'before', 'after', 'days', 'sessions', 'skipped'].map(key => [key, z.number().finite().nonnegative()])), ...Object.fromEntries(['beforeCny', 'afterCny', 'beforeEur', 'afterEur'].map(key => [key, z.number().finite().nonnegative().optional()])), model: z.string().optional() })))
649
- const _repricingConfirmation$codec = strictCodec('RepricingConfirmation', z.boolean())
650
- const _repricingModel$codec = strictCodec('RepricingModel', z.string().min(3).max(2048).refine(value => value.indexOf(':') > 0 && !value.endsWith(':') && !/[\r\n]/.test(value)))
651
- const _provider$codec = strictCodec('CodingPlanProvider', z.string())
652
- const _gatewaySourceId$codec = strictCodec('GatewayQuotaSourceId', z.string().optional())
653
- // 密钥目标(v1.6.8):'goQuota' | 'codingPlans.<id>' | 'codingPlans.volcengine.ak' | '...sk'
654
- const _credTarget$codec = strictCodec('CredentialTarget', z.string())
655
- // 密钥明文(v1.6.8):仅经 setCredential 单向写入凭据库,永不回传前端。
656
- const _credValue$codec = strictCodec('CredentialValue', z.string())
657
- const _day$codec = strictCodec('DayRecord', daySchema)
658
- const _date$codec = strictCodec('DayKey', z.string())
659
- const _topSessions$codec = strictCodec('TopSessions', topSessionsSchema)
660
- const _limit$codec = strictCodec('SessionLimit', num)
661
- const _sort$codec = strictCodec('SessionSort', z.string())
662
- const _dir$codec = strictCodec('SessionSortDir', z.string())
663
- const _sessionId$codec = strictCodec('SessionId', z.string().min(1).max(512))
664
- const _sessionCost$codec = strictCodec('SessionCost', sessionCostSchema)
665
- const _turnCost$codec = strictCodec('TurnCost', turnCostSchema)
666
- const _turnSeq$codec = strictCodec('TurnSeq', z.number().int().nonnegative())
667
-
668
- export const TYPERT = {
669
- package: 'dsh-cost-meter',
670
- face: 'host',
671
- schemas: [],
672
- invocations: [
673
- { id: 'dsh-cost-meter#costMeter/getContextIntegration', service: 'costMeter', namespace: 'costMeter', method: 'getContextIntegration', invocation: { kind: 'direct' }, parameters: [],
674
- result: strictCodec('ContextIntegration', z.object({ version: z.string(), compatible: z.boolean(), reason: z.enum(['ready', 'missing', 'unsupported', 'unavailable']) })) },
675
- {
676
- id: 'dsh-cost-meter#costMeter/getOpenRouterCatalog', service: 'costMeter', namespace: 'costMeter', method: 'getOpenRouterCatalog',
677
- invocation: { kind: 'direct' }, parameters: [], result: strictCodec('OpenRouterCatalog', openRouterCatalogSchema),
678
- },
679
- {
680
- id: 'dsh-cost-meter#costMeter/getState',
681
- service: 'costMeter',
682
- namespace: 'costMeter',
683
- method: 'getState',
684
- invocation: { kind: 'direct' },
685
- parameters: [],
686
- result: _state$codec,
687
- },
688
- { id: 'dsh-cost-meter#costMeter/getStateSince', service: 'costMeter', namespace: 'costMeter', method: 'getStateSince', invocation: { kind: 'direct' },
689
- parameters: [{ name: 'pricesRev', wire: 'pricesRev', source: 'json', codec: strictCodec('PricesRev', z.string()) }], result: _state$codec },
690
- { id: 'dsh-cost-meter#costMeter/getLocalState', service: 'costMeter', namespace: 'costMeter', method: 'getLocalState', invocation: { kind: 'direct' }, parameters: [], result: _state$codec },
691
- { id: 'dsh-cost-meter#costMeter/getRepricingHistory', service: 'costMeter', namespace: 'costMeter', method: 'getRepricingHistory', invocation: { kind: 'direct' }, parameters: [], result: _repricingHistory$codec },
692
- { id: 'dsh-cost-meter#costMeter/getPriceCatalog', service: 'costMeter', namespace: 'costMeter', method: 'getPriceCatalog', invocation: { kind: 'direct' }, parameters: [], result: strictCodec('PriceCatalog', priceCatalogSchema) },
693
- { id: 'dsh-cost-meter#costMeter/repriceHistory', service: 'costMeter', namespace: 'costMeter', method: 'repriceHistory', invocation: { kind: 'direct' }, parameters: [{ name: 'confirmed', wire: 'confirmed', source: 'json', codec: _repricingConfirmation$codec }], result: _fetch$codec },
694
- { id: 'dsh-cost-meter#costMeter/repriceModelHistory', service: 'costMeter', namespace: 'costMeter', method: 'repriceModelHistory', invocation: { kind: 'direct' }, parameters: [{ name: 'confirmed', wire: 'confirmed', source: 'json', codec: _repricingConfirmation$codec }, { name: 'model', wire: 'model', source: 'json', codec: _repricingModel$codec }], result: _fetch$codec },
695
- {
696
- id: 'dsh-cost-meter#costMeter/updateConfig',
697
- service: 'costMeter',
698
- namespace: 'costMeter',
699
- method: 'updateConfig',
700
- invocation: { kind: 'direct' },
701
- parameters: [
702
- { name: 'patch', wire: 'patch', source: 'json', codec: _patch$codec },
703
- ],
704
- result: _state$codec,
705
- },
706
- {
707
- // dsh-codex-subscription 兼容(契约 D):把历史 codex 类计费统一归类为 Plan,
708
- // 影响 Plan 配额基线,返回完整 state。
709
- id: 'dsh-cost-meter#costMeter/applyCodexCompatHistory',
710
- service: 'costMeter',
711
- namespace: 'costMeter',
712
- method: 'applyCodexCompatHistory',
713
- invocation: { kind: 'direct' },
714
- parameters: [],
715
- result: _state$codec,
716
- },
717
- {
718
- // 永久关闭一次性兼容提示(×/保持现状/ESC),返回完整 state。
719
- id: 'dsh-cost-meter#costMeter/dismissCodexCompat',
720
- service: 'costMeter',
721
- namespace: 'costMeter',
722
- method: 'dismissCodexCompat',
723
- invocation: { kind: 'direct' },
724
- parameters: [],
725
- result: _state$codec,
726
- },
727
- {
728
- id: 'dsh-cost-meter#costMeter/fetchPrices',
729
- service: 'costMeter',
730
- namespace: 'costMeter',
731
- method: 'fetchPrices',
732
- invocation: { kind: 'direct' },
733
- parameters: [],
734
- result: _fetch$codec,
735
- },
736
- {
737
- id: 'dsh-cost-meter#costMeter/releasePriceLock',
738
- service: 'costMeter',
739
- namespace: 'costMeter',
740
- method: 'releasePriceLock',
741
- invocation: { kind: 'direct' },
742
- parameters: [
743
- { name: 'id', wire: 'id', source: 'json', codec: strictCodec('PriceLockId', z.string().min(1)) },
744
- ],
745
- result: _fetch$codec,
746
- },
747
- {
748
- id: 'dsh-cost-meter#costMeter/refreshBalance',
749
- service: 'costMeter',
750
- namespace: 'costMeter',
751
- method: 'refreshBalance',
752
- invocation: { kind: 'direct' },
753
- parameters: [],
754
- result: _fetch$codec,
755
- },
756
- {
757
- id: 'dsh-cost-meter#costMeter/refreshGoQuota',
758
- service: 'costMeter',
759
- namespace: 'costMeter',
760
- method: 'refreshGoQuota',
761
- invocation: { kind: 'direct' },
762
- parameters: [],
763
- result: _fetch$codec,
764
- },
765
- {
766
- id: 'dsh-cost-meter#costMeter/refreshCustomBalance',
767
- service: 'costMeter',
768
- namespace: 'costMeter',
769
- method: 'refreshCustomBalance',
770
- invocation: { kind: 'direct' },
771
- // index(v1.7.0,issue #79):多配置形态下指定刷新的条目下标;缺省 = 全部刷新。
772
- // acceptsUndefined(v1.7.1):网关按「期望 wire 字段是否在 args 中」判缺失——
773
- // 无此标志的 json 参数缺省会以 arguments-invalid 拒绝调用;标志允许旧客户端
774
- // 的无参调用(等价全量刷新)继续走通。codec 必须是 strict 对象(裸 zod schema
775
- // 会被 typert-loader 以「parameter codec must use a strict codec」拒绝注册,
776
- // v1.7.0 因此无法启动宿主——本版回归)。
777
- parameters: [
778
- {
779
- name: 'index', wire: 'index', source: 'json', acceptsUndefined: true,
780
- codec: strictCodec('CustomBalanceIndex', z.number().int().min(0).max(7).optional()),
781
- },
782
- ],
783
- result: _fetch$codec,
784
- },
785
- {
786
- id: 'dsh-cost-meter#costMeter/refreshCodingPlan',
787
- service: 'costMeter',
788
- namespace: 'costMeter',
789
- method: 'refreshCodingPlan',
790
- invocation: { kind: 'direct' },
791
- parameters: [
792
- { name: 'provider', wire: 'provider', source: 'json', codec: _provider$codec },
793
- ],
794
- result: _fetch$codec,
795
- },
796
- {
797
- id: 'dsh-cost-meter#costMeter/loginCodingPlan',
798
- service: 'costMeter',
799
- namespace: 'costMeter',
800
- method: 'loginCodingPlan',
801
- invocation: { kind: 'direct' },
802
- parameters: [
803
- { name: 'provider', wire: 'provider', source: 'json', codec: _provider$codec },
804
- ],
805
- result: _fetch$codec,
806
- },
807
- {
808
- id: 'dsh-cost-meter#costMeter/refreshGatewayQuota',
809
- service: 'costMeter',
810
- namespace: 'costMeter',
811
- method: 'refreshGatewayQuota',
812
- invocation: { kind: 'direct' },
813
- parameters: [
814
- { name: 'sourceId', wire: 'sourceId', source: 'json', acceptsUndefined: true, codec: _gatewaySourceId$codec },
815
- ],
816
- result: _fetch$codec,
817
- },
818
- {
819
- id: 'dsh-cost-meter#costMeter/resetHistory',
820
- service: 'costMeter',
821
- namespace: 'costMeter',
822
- method: 'resetHistory',
823
- invocation: { kind: 'direct' },
824
- parameters: [],
825
- result: _state$codec,
826
- },
827
- {
828
- // 导入安装前历史(issue #27):回放全部会话日志,只补账本缺失的日期/会话。
829
- id: 'dsh-cost-meter#costMeter/importLegacyHistory',
830
- service: 'costMeter',
831
- namespace: 'costMeter',
832
- method: 'importLegacyHistory',
833
- invocation: { kind: 'direct' },
834
- parameters: [],
835
- result: _fetch$codec,
836
- },
837
- {
838
- id: 'dsh-cost-meter#costMeter/getDaySessions',
839
- service: 'costMeter',
840
- namespace: 'costMeter',
841
- method: 'getDaySessions',
842
- invocation: { kind: 'direct' },
843
- parameters: [
844
- { name: 'date', wire: 'date', source: 'json', codec: _date$codec },
845
- ],
846
- result: _day$codec,
847
- },
848
- {
849
- id: 'dsh-cost-meter#costMeter/getTopSessions',
850
- service: 'costMeter',
851
- namespace: 'costMeter',
852
- method: 'getTopSessions',
853
- invocation: { kind: 'direct' },
854
- parameters: [
855
- { name: 'limit', wire: 'limit', source: 'json', codec: _limit$codec },
856
- // sort/dir 与服务端函数默认值(sort='cost', dir='desc')对应,声明可缺省:
857
- // 网关对 args 字段做精确匹配,不声明 acceptsUndefined 时旧客户端单参数调用
858
- // 会因 missing "sort"/"dir" 被拒,会话排行面板直接加载失败。
859
- { name: 'sort', wire: 'sort', source: 'json', codec: _sort$codec, acceptsUndefined: true },
860
- { name: 'dir', wire: 'dir', source: 'json', codec: _dir$codec, acceptsUndefined: true },
861
- ],
862
- result: _topSessions$codec,
863
- },
864
- {
865
- id: 'dsh-cost-meter#costMeter/getSessionCost',
866
- service: 'costMeter',
867
- namespace: 'costMeter',
868
- method: 'getSessionCost',
869
- invocation: { kind: 'direct' },
870
- parameters: [{ name: 'sessionId', wire: 'sessionId', source: 'json', codec: _sessionId$codec }],
871
- result: _sessionCost$codec,
872
- },
873
- {
874
- id: 'dsh-cost-meter#costMeter/getTurnCost', service: 'costMeter', namespace: 'costMeter', method: 'getTurnCost',
875
- invocation: { kind: 'direct' },
876
- parameters: [{ name: 'sessionId', wire: 'sessionId', source: 'json', codec: _sessionId$codec }, { name: 'startSeq', wire: 'startSeq', source: 'json', codec: _turnSeq$codec }, { name: 'endSeq', wire: 'endSeq', source: 'json', codec: _turnSeq$codec }, { name: 'displayCurrency', wire: 'displayCurrency', source: 'json', acceptsUndefined: true, codec: strictCodec('DisplayCurrency', z.enum(['USD', 'CNY', 'EUR']).optional()) }],
877
- result: _turnCost$codec,
878
- },
879
- ...[['getBillingStatistics', 'BillingStatistics', billingStatisticsSchema], ['getSessionBilling', 'SessionBilling', sessionBillingSchema]].map(([method, name, schema]) => ({
880
- id: 'dsh-cost-meter#costMeter/' + method, service: 'costMeter', namespace: 'costMeter', method, invocation: { kind: 'direct' },
881
- parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('StatisticsQuery', statisticsQuerySchema) }],
882
- result: strictCodec(name, schema),
883
- })),
884
- { id: 'dsh-cost-meter#costMeter/getTurnInspection', service: 'costMeter', namespace: 'costMeter', method: 'getTurnInspection', invocation: { kind: 'direct' },
885
- parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('TurnInspectionQuery', turnInspectionQuerySchema) }], result: strictCodec('TurnInspection', turnInspectionSchema) },
886
- { id: 'dsh-cost-meter#costMeter/getCallInspection', service: 'costMeter', namespace: 'costMeter', method: 'getCallInspection', invocation: { kind: 'direct' },
887
- parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('CallInspectionQuery', callInspectionQuerySchema) }], result: strictCodec('CallInspection', callInspectionSchema) },
888
- ...[['getSessionTrajectory', 'Trajectory', trajectoryQuerySchema, trajectorySchema]].map(([method, name, query, schema]) => ({
889
- id: 'dsh-cost-meter#costMeter/' + method, service: 'costMeter', namespace: 'costMeter', method, invocation: { kind: 'direct' },
890
- parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec(name + 'Query', query) }], result: strictCodec(name, schema) })),
891
- { id: 'dsh-cost-meter#costMeter/getContextCosts', service: 'costMeter', namespace: 'costMeter', method: 'getContextCosts', invocation: { kind: 'direct' },
892
- parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('ContextCostsQuery', contextCostsQuerySchema) }], result: strictCodec('ContextCosts', contextCostsSchema) },
893
- {
894
- // 写入一枚密钥到 DSH 凭据库(v1.6.8):密钥不再经 updateConfig 传递,值只进凭据库。
895
- id: 'dsh-cost-meter#costMeter/setCredential',
896
- service: 'costMeter',
897
- namespace: 'costMeter',
898
- method: 'setCredential',
899
- invocation: { kind: 'direct' },
900
- parameters: [
901
- { name: 'target', wire: 'target', source: 'json', codec: _credTarget$codec },
902
- { name: 'value', wire: 'value', source: 'json', codec: _credValue$codec },
903
- ],
904
- result: _fetch$codec,
905
- },
906
- {
907
- // 从 DSH 凭据库移除一枚密钥(v1.6.8)。
908
- id: 'dsh-cost-meter#costMeter/clearCredential',
909
- service: 'costMeter',
910
- namespace: 'costMeter',
911
- method: 'clearCredential',
912
- invocation: { kind: 'direct' },
913
- parameters: [
914
- { name: 'target', wire: 'target', source: 'json', codec: _credTarget$codec },
915
- ],
916
- result: _fetch$codec,
917
- },
918
- ],
919
- model: {
920
- services: [
921
- {
922
- description: 'dsh-cost-meter 账本与配置服务(ctx.costMeter),聚合每日模型用量与费用。Ledger and config service (ctx.costMeter) aggregating daily model usage and cost.',
923
- summary: 'dsh-cost-meter 账本与配置服务 (dsh-cost-meter ledger & config service)。',
924
- tags: [],
925
- jsDoc: '/** dsh-cost-meter 账本与配置服务(ctx.costMeter)。dsh-cost-meter ledger & config service (ctx.costMeter). */',
926
- key: 'costMeter',
927
- exportName: 'CostMeterService',
928
- members: [
929
- { kind: 'method', name: 'getStateSince', signature: 'getStateSince(pricesRev: string): Promise<CostState>', summary: '按已知价格版本读取状态。Read state with a known price revision.' },
930
- {
931
- kind: 'method',
932
- name: 'getState',
933
- signature: 'getState(): CostState',
934
- summary: '读取今日/本月/累计聚合、历史记录与当前配置。Read today/month/total aggregates, history, and current config.',
935
- jsDoc: '/**\n * 读取今日/本月/累计聚合、历史记录与当前配置。\n * @returns 完整账本快照。\n * Read today/month/total aggregates, history, and current config.\n * @returns The full ledger snapshot.\n */',
936
- },
937
- {
938
- kind: 'method',
939
- name: 'updateConfig',
940
- signature: 'updateConfig(patch: ConfigPatch): CostState',
941
- summary: '深合并一份配置补丁并持久化。Deep-merge a config patch and persist it.',
942
- jsDoc: '/**\n * 深合并一份配置补丁并持久化。\n * @param patch - 配置补丁。\n * @returns 更新后的完整快照。\n * Deep-merge a config patch and persist it.\n * @param patch - The config patch.\n * @returns The updated full snapshot.\n */',
943
- },
944
- {
945
- kind: 'method',
946
- name: 'fetchPrices',
947
- signature: 'fetchPrices(): Promise<FetchPricesResult>',
948
- summary: '抓取官方定价页并应用解析出的价格。Fetch the official pricing page and apply the parsed prices.',
949
- jsDoc: '/**\n * 抓取官方定价页并应用解析出的价格。\n * @returns 抓取与应用结果。\n * Fetch the official pricing page and apply the parsed prices.\n * @returns The fetch-and-apply result.\n */',
950
- },
951
- { kind: 'method', name: 'getRepricingHistory', signature: 'getRepricingHistory(): Promise<RepricingHistory>', summary: '读取历史重算前后的金额。Read original and recalculated amounts.' },
952
- { kind: 'method', name: 'getPriceCatalog', signature: 'getPriceCatalog(): Promise<PriceCatalog>', summary: '按需读取可恢复的内置价格。Read bundled prices on demand.' },
953
- { kind: 'method', name: 'repriceHistory', signature: 'repriceHistory(confirmed: boolean): Promise<FetchPricesResult>', summary: '确认并备份后按当前价格重算历史。Recalculate history after explicit confirmation and backup.' },
954
- { kind: 'method', name: 'repriceModelHistory', signature: 'repriceModelHistory(confirmed: boolean, model: string): Promise<FetchPricesResult>', summary: '确认并备份后只重算指定渠道模型,保留同期汇率。Recalculate one channel/model with original exchange rates.' },
955
- {
956
- kind: 'method', name: 'getOpenRouterCatalog', signature: 'getOpenRouterCatalog(): Promise<OpenRouterCatalog>',
957
- summary: '只读查询公开模型价格,无需密钥。Read public model prices without credentials or config changes.',
958
- },
959
- {
960
- kind: 'method',
961
- name: 'releasePriceLock',
962
- signature: 'releasePriceLock(id: string): Promise<FetchPricesResult>',
963
- summary: '把手改过的 OpenRouter 价格交回自动同步。Hand a manually edited OpenRouter price back to auto-sync.',
964
- jsDoc: '/**\n * 把手改过的 OpenRouter 价格交回自动同步。\n * @param id - OpenRouter 模型 id。\n * @returns 结果与最新快照。\n * Hand a manually edited OpenRouter price back to auto-sync.\n * @param id - The OpenRouter model id.\n * @returns The result and the latest snapshot.\n */',
965
- },
966
- {
967
- kind: 'method',
968
- name: 'refreshBalance',
969
- signature: 'refreshBalance(): Promise<FetchPricesResult>',
970
- summary: '立即查询官方开放平台账户余额。Query the official open-platform account balance immediately.',
971
- jsDoc: '/**\n * 立即查询官方开放平台账户余额。\n * @returns 查询结果与最新快照。\n * Query the official open-platform account balance immediately.\n * @returns The query result and the latest snapshot.\n */',
972
- },
973
- {
974
- kind: 'method',
975
- name: 'refreshGoQuota',
976
- signature: 'refreshGoQuota(): Promise<FetchPricesResult>',
977
- summary: '立即查询 OpenCode Go 订阅额度。Query the OpenCode Go subscription quota immediately.',
978
- jsDoc: '/**\n * 立即查询 OpenCode Go 订阅额度(滚动5小时/本周/本月用量百分比)。\n * @returns 查询结果与最新快照。\n * Query the OpenCode Go subscription quota immediately (rolling-5h/weekly/monthly usage percent).\n * @returns The query result and the latest snapshot.\n */',
979
- },
980
- {
981
- kind: 'method',
982
- name: 'refreshGatewayQuota',
983
- signature: 'refreshGatewayQuota(sourceId?: string): Promise<FetchPricesResult>',
984
- summary: '立即刷新 CLIProxyAPI gateway quota 来源。Refresh CLIProxyAPI gateway quota sources immediately.',
985
- jsDoc: '/**\n * 立即刷新 CLIProxyAPI gateway quota 来源。\n * @param sourceId - 可选来源 ID;缺省刷新全部启用来源。\n * @returns 查询结果与最新快照。\n */',
986
- },
987
- {
988
- kind: 'method',
989
- name: 'refreshCustomBalance',
990
- signature: 'refreshCustomBalance(index?: number): Promise<FetchPricesResult>',
991
- summary: '立即查询自定义 Provider 余额(可指定条目)。Query custom provider balances immediately (optionally one entry).',
992
- jsDoc: '/**\n * 立即查询自定义 Provider 余额(可配置 HTTP 请求 + extract 规则)。\n * @param index - 可选:多配置形态下要刷新的条目下标(0-7);缺省刷新全部条目。\n * @returns 查询结果与最新快照。\n * Query custom provider balances immediately (configurable HTTP request + extract rules).\n * @param index - Optional: entry index (0-7) to refresh in the multi-entry form; omit to refresh all.\n * @returns The query result and the latest snapshot.\n */',
993
- },
994
- {
995
- kind: 'method',
996
- name: 'refreshCodingPlan',
997
- signature: 'refreshCodingPlan(provider: string): Promise<FetchPricesResult>',
998
- summary: '立即查询指定厂商的 coding plan 额度。Query a vendor coding plan quota immediately.',
999
- jsDoc: '/**\n * 立即查询指定厂商(anthropic | zai | minimax | kimi | openrouter | siliconflow)的 coding plan 额度。\n * @param provider - 提供商标识。\n * @returns 查询结果与最新快照。\n * Query a vendor (anthropic | zai | minimax | kimi | openrouter | siliconflow) coding plan quota immediately.\n * @param provider - The provider id.\n * @returns The query result and the latest snapshot.\n */',
1000
- },
1001
- {
1002
- kind: 'method',
1003
- name: 'resetHistory',
1004
- signature: 'resetHistory(): CostState',
1005
- summary: '清空全部历史记录。Clear all history records.',
1006
- jsDoc: '/**\n * 清空全部历史记录。\n * @returns 清空后的完整快照。\n * Clear all history records.\n * @returns The full snapshot after clearing.\n */',
1007
- },
1008
- {
1009
- kind: 'method',
1010
- name: 'getDaySessions',
1011
- signature: 'getDaySessions(date: string): DayRecord',
1012
- summary: '按需读取某一天的完整记录(含会话明细)。Read a day\'s full record on demand (with session details).',
1013
- jsDoc: '/**\n * 按需读取某一天的完整记录(含会话明细;历史记录列表为轻量副本不含会话)。\n * @param date - 本地日期键 YYYY-MM-DD。\n * @returns 该日完整记录;不存在时返回零值记录。\n * Read a day\'s full record on demand (with session details; the history list is a light copy without sessions).\n * @param date - Local day key YYYY-MM-DD.\n * @returns The full day record; a zero record when absent.\n */',
1014
- },
1015
- {
1016
- kind: 'method',
1017
- name: 'getTopSessions',
1018
- signature: 'getTopSessions(limit: number, sort?: string, dir?: string): TopSessions',
1019
- summary: '跨全部日期按指定排序返回前 N 个会话(不分日期视角)。Return the top N sessions across all days with the given sort.',
1020
- jsDoc: '/**\n * 跨全部日期返回前 N 个会话(每条带所属日期/标题/创建时刻)。\n * @param limit - 返回条数上限(服务端限制 1-500)。\n * @param sort - cost(费用) | time(创建时间) | recent(实时顺序)。\n * @param dir - asc | desc(默认 desc)。\n * @returns 会话列表(含 date/title/at 字段)。\n * Return the top N sessions across all days (each tagged with date/title/createdAt).\n * @param limit - Max rows to return (server clamps to 1-500).\n * @param sort - cost | time | recent (ledger/sidebar order).\n * @param dir - asc | desc (defaults to desc).\n * @returns Session list with date/title/at fields.\n */',
1021
- },
1022
- {
1023
- kind: 'method',
1024
- name: 'getTurnCost',
1025
- signature: 'getTurnCost(sessionId: string, startSeq: number, endSeq: number): TurnCost',
1026
- summary: '读取已完成轮次的分项用量与估算费用。Read recorded usage and estimated costs for a completed turn.',
1027
- },
1028
- {
1029
- kind: 'method',
1030
- name: 'getSessionCost',
1031
- signature: 'getSessionCost(sessionId: string): SessionCost',
1032
- summary: '读取本会话跨日期账本及可选的子代理费用汇总。Read a session ledger and optional descendant costs.',
1033
- jsDoc: '/** 只读会话费用;后代合计不改变每日账本。Read-only cost summary; descendant costs never rewrite daily totals. */',
1034
- },
1035
- {
1036
- kind: 'method',
1037
- name: 'setCredential',
1038
- signature: 'setCredential(target: CredentialTarget, value: CredentialValue): Promise<FetchPricesResult>',
1039
- summary: '把一枚密钥写入 DSH 凭据库。Store a credential in the DSH credential store.',
1040
- jsDoc: '/**\n * 把一枚密钥写入 DSH 凭据库(v1.6.8)。密钥不再经 updateConfig 传递:\n * config 中的密钥字段只留空占位(且不落盘),值一律存进宿主凭据库。\n * v1.7.6 新增 customVar:<NAME> 目标:自定义余额请求头 {{VAR}} 占位符的同名密钥\n * 也走这一入口写入,与模型页共享变量名即共用同一把密钥。\n * @param target - balance | goQuota | codingPlans.<id> | codingPlans.volcengine.ak | codingPlans.volcengine.sk | customVar:VAR_NAME\n * @param value - 密钥明文(非空)\n * @returns 写入结果与最新快照\n * Store a credential in the DSH credential store (v1.6.8). Credentials no longer travel\n * through updateConfig: config keeps blank placeholders only (and never persists them).\n * v1.7.6 adds the customVar:<NAME> target: keys for custom-balance header {{VAR}}\n * placeholders are stored through this same entry; sharing a variable name with the\n * Models page shares the same key.\n * @param target - balance | goQuota | codingPlans.<id> | codingPlans.volcengine.ak | codingPlans.volcengine.sk | customVar:VAR_NAME\n * @param value - The plaintext credential (non-empty)\n * @returns The write result and the latest snapshot\n */',
1041
- },
1042
- {
1043
- kind: 'method',
1044
- name: 'clearCredential',
1045
- signature: 'clearCredential(target: CredentialTarget): Promise<FetchPricesResult>',
1046
- summary: '从 DSH 凭据库移除一枚密钥。Remove a credential from the DSH credential store.',
1047
- jsDoc: '/**\n * 从 DSH 凭据库移除一枚密钥(v1.6.8),并清掉 config 中可能残留的旧明文。\n * @param target - 同 setCredential\n * @returns 移除结果与最新快照\n * Remove a credential from the DSH credential store (v1.6.8), also clearing any\n * leftover plaintext in config.\n * @param target - Same as setCredential\n * @returns The removal result and the latest snapshot\n */',
1048
- },
1049
- ],
1050
- types: [],
1051
- },
1052
- ],
1053
- events: [],
1054
- objects: [],
1055
- },
1056
- }
1057
-
1058
- export default TYPERT
1
+ import { multiplierPath } from './price-multiplier.js'
2
+ /**
3
+ * dsh-cost-meter 的 Host 面 Typert 清单(由 typert-loader 自动扫描注册)。
4
+ * 手写清单,结构与 @deepseek-ai/dsh-typert-generator 产物一致:
5
+ * `./typert` 导出 TYPERT;strict codec 同时提供旧宿主的 schema 和新宿主的 create()。
6
+ */
7
+
8
+ import { z } from 'zod'
9
+
10
+ const num = z.number()
11
+ const frozenMoney = Object.fromEntries(['costCny', 'apiCostCny', 'costEur', 'apiCostEur'].map(key => [key, num.optional()]))
12
+
13
+ const sessionSchema = z.object({
14
+ id: z.string(),
15
+ title: z.string().optional(),
16
+ at: num.optional(),
17
+ input: num,
18
+ output: num,
19
+ cacheRead: num,
20
+ cacheWrite: num,
21
+ reasoning: num.optional(),
22
+ calls: num,
23
+ cost: num,
24
+ // API 渠道金额(issue #64):真金白银部分;缺席 = 旧快照按 cost 全额 API。
25
+ apiCost: num.optional(),
26
+ ...frozenMoney,
27
+ byProviderModel: z.record(z.string(), z.object({ input: num, output: num, cacheRead: num, cacheWrite: num, reasoning: num.optional(), calls: num, cost: num, apiCost: num.optional(), ...frozenMoney })).optional(),
28
+ })
29
+
30
+ const daySchema = z.object({
31
+ date: z.string(),
32
+ input: num,
33
+ output: num,
34
+ cacheRead: num,
35
+ cacheWrite: num,
36
+ reasoning: num.optional(),
37
+ calls: num,
38
+ cost: num,
39
+ apiCost: num.optional(),
40
+ ...frozenMoney,
41
+ byProviderModel: z.record(z.string(), z.object({ input: num, output: num, cacheRead: num, cacheWrite: num, reasoning: num.optional(), calls: num, cost: num, apiCost: num.optional(), ...frozenMoney })).optional(),
42
+ sessions: z.array(sessionSchema),
43
+ })
44
+
45
+ const externalSummarySchema = z.object({ today: daySchema, month: daySchema, total: daySchema, history: z.array(daySchema) })
46
+ const externalUsageSchema = z.object({
47
+ fetchedAt: num,
48
+ stale: z.boolean(),
49
+ sources: z.array(externalSummarySchema.extend({ source: z.string() })),
50
+ combined: externalSummarySchema,
51
+ })
52
+
53
+ // 带所属日期的会话条目(issue #22 按会话排行:不分日期视角)。
54
+ const datedSessionSchema = sessionSchema.extend({ date: z.string() })
55
+
56
+ const topSessionsSchema = z.object({
57
+ sessions: z.array(datedSessionSchema),
58
+ })
59
+
60
+ export const sessionCostSchema = z.object({
61
+ own: sessionSchema,
62
+ subagents: sessionSchema,
63
+ subagentCount: num,
64
+ found: z.boolean(),
65
+ })
66
+ const turnCostRowSchema = z.object({ provider: z.string(), model: z.string(), bucket: z.string(), tokens: num, requests: num.optional(), rate: num, cost: num, priced: z.boolean(), plan: z.boolean() })
67
+ const meteringSchema = z.object({ source: z.literal('billion-context'), requestId: z.string(), attempt: num, complete: z.boolean(), status: z.string(), upstream: z.string() }).optional()
68
+ export const turnCostSchema = z.object({
69
+ found: z.boolean(), cost: num, apiCost: num, ...frozenMoney,
70
+ inherited: z.boolean().optional(),
71
+ rows: z.array(turnCostRowSchema),
72
+ calls: z.array(z.object({ kind: z.string(), provider: z.string(), model: z.string(), atMs: num, cost: num, apiCost: num, plan: z.boolean(), priced: z.boolean(), longContext: z.boolean(), rows: z.array(turnCostRowSchema), metering: meteringSchema })),
73
+ })
74
+
75
+ export const statisticsQuerySchema = z.object({
76
+ displayCurrency: z.enum(['USD', 'CNY', 'EUR']).optional(),
77
+ from: z.string().max(10).optional(), to: z.string().max(10).optional(),
78
+ provider: z.string().max(512).optional(), model: z.string().max(512).optional(), sessionId: z.string().max(512).optional(),
79
+ basis: z.enum(['api', 'plan', 'total']).optional(), offset: z.number().int().min(0).max(1e7).optional(),
80
+ turnOffset: z.number().int().min(0).max(1e7).optional(), background: z.boolean().optional(), generation: z.string().max(96).optional(),
81
+ })
82
+ const statisticsBuckets = z.object(Object.fromEntries(['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost'].map(key => [key, num])))
83
+ export const billingStatisticsSchema = z.object({
84
+ from: z.string(), to: z.string(), retainedFrom: z.string(), retainedTo: z.string(), totals: statisticsBuckets,
85
+ days: z.array(statisticsBuckets.extend({ date: z.string() })),
86
+ models: z.array(statisticsBuckets.extend({ key: z.string(), provider: z.string(), model: z.string(), priced: z.boolean() })),
87
+ providers: z.array(z.string()), modelOptions: z.array(z.string()),
88
+ sessions: z.array(statisticsBuckets.extend({ id: z.string(), title: z.string() })),
89
+ sessionCount: num, offset: num, unassignedCost: num, unmodeledCost: num,
90
+ })
91
+ const sessionBillingCallSchema = turnCostSchema.shape.calls.element.extend({ sessionId: z.string().default(''), turn: num.nullable(), step: num.nullable(), logSeq: num.nullable().default(null) })
92
+ export const sessionBillingSchema = turnCostSchema.extend({ refreshing: z.boolean().default(false), generatedAt: num.default(0), refreshFailed: z.boolean().default(false), totalCalls: num, offset: num, recorded: statisticsBuckets,
93
+ calls: z.array(sessionBillingCallSchema),
94
+ agents: z.array(statisticsBuckets.extend({ id: z.string(), title: z.string() })).default([]),
95
+ kinds: z.array(statisticsBuckets.extend({ kind: z.string(), unpriced: z.boolean() })),
96
+ turns: z.array(statisticsBuckets.extend({ sessionId: z.string().default(''), turn: num.nullable(), unpriced: z.boolean() })),
97
+ totalTurns: num, turnOffset: num,
98
+ callShares: z.array(z.object({ index: num, cost: num, apiCost: num, tokens: num, calls: num, other: z.boolean(), unpriced: z.boolean(), call: sessionBillingCallSchema.nullable().default(null) })).default([]),
99
+ stepShares: z.object(Object.fromEntries(['cost', 'calls'].map(key => [key, z.array(statisticsBuckets.extend({ sessionId: z.string().default(''), turn: num.nullable(), step: num.nullable(), other: z.boolean(), unpriced: z.boolean() }))]))),
100
+ })
101
+ export const turnInspectionQuerySchema = z.object({ sessionId: z.string().min(1).max(512), turn: z.number().int().min(0), offset: z.number().int().min(0).max(1e7).optional() })
102
+ export const turnInspectionSchema = z.object({ found: z.boolean(), turn: num, input: z.string(), inputTruncated: z.boolean(), totalTools: num, offset: num,
103
+ tools: z.array(z.object({ seq: num, step: num.nullable(), name: z.string(), callId: z.string(), atMs: num, arguments: z.string(), result: z.string(), truncated: z.boolean(), status: z.enum(['pending', 'complete', 'error']) })) })
104
+
105
+ export const contextCostsQuerySchema = z.object({ sessionId: z.string().min(1).max(512) })
106
+ const trajectoryPartsSchema = z.array(z.object({ bucket: z.string(), cost: num, apiCost: num, tokens: num, unpriced: z.boolean() })).default([])
107
+ const trajectoryGroupSchema = z.object({ key: z.string(), kind: z.string(), sessionId: z.string().default(''), title: z.string().default(''), tools: z.array(z.string()), steps: num, calls: num.default(0), cost: num, apiCost: num, unpriced: z.boolean(), parts: trajectoryPartsSchema })
108
+ export const trajectoryQuerySchema = contextCostsQuerySchema.extend({ displayCurrency: z.enum(['USD', 'CNY', 'EUR']).optional(), basis: z.enum(['api', 'plan', 'total']).default('total'), offset: z.number().int().min(0).max(1e7).default(0),
109
+ operation: z.string().max(80).default(''), operationGroup: z.string().max(4096).default(''), stepKey: z.string().max(2048).default(''), detail: z.enum(['full', 'map']).default('full'), ownOnly: z.boolean().default(false),
110
+ background: z.boolean().default(false), generation: z.string().max(96).default(''), order: z.enum(['cost', 'time']).default('time'), group: z.string().max(1024).default(''), agent: z.string().max(512).default('') })
111
+ export const trajectorySchema = z.object({ refreshing: z.boolean().default(false), generatedAt: num.default(0), refreshFailed: z.boolean().default(false), cost: num, apiCost: num, totalSteps: num, totalCalls: num.default(0), matchingSteps: num.default(0), order: z.enum(['cost', 'time']).default('time'), offset: num,
112
+ shares: z.array(z.object({ key: z.string(), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), cost: num, apiCost: num, unpriced: z.boolean(), other: z.boolean(), count: num })),
113
+ tiles: z.array(z.object({ key: z.string(), groupKey: z.string(), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), cost: num, apiCost: num, unpriced: z.boolean(), other: z.boolean(), count: num })).default([]),
114
+ groups: z.array(trajectoryGroupSchema), operations: z.array(trajectoryGroupSchema).default([]),
115
+ operationGroups: z.array(trajectoryGroupSchema.extend({ operationKey: z.string() })).default([]),
116
+ distribution: z.array(z.object({ key: z.string(), steps: num, calls: num, cost: num, apiCost: num, unpriced: z.boolean() })).default([]),
117
+ hierarchy: z.array(z.object({ id: z.string(), parentId: z.string(), title: z.string(), cost: num, apiCost: num, ownCost: num, ownApiCost: num, steps: num, calls: num, ownSteps: num, ownCalls: num, unpriced: z.boolean().default(false),
118
+ groups: z.array(trajectoryGroupSchema), operations: z.array(trajectoryGroupSchema).default([]) })).default([]),
119
+ steps: z.array(z.object({ key: z.string(), groupKey: z.string().default(''), typeKey: z.string().default(''), operationKey: z.string().default(''), operationGroupKey: z.string().default(''), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), atMs: num, calls: num, cost: num, apiCost: num, unpriced: z.boolean(), rows: turnCostSchema.shape.rows, callRefs: sessionBillingSchema.shape.calls.default([]) })) })
120
+ export const callInspectionQuerySchema = z.object({ sessionId: z.string().min(1).max(512), seq: z.number().int().min(0), atMs: z.number().finite().positive(), offset: z.number().int().min(0).max(1e7).optional() })
121
+ export const callInspectionSchema = z.object({ found: z.boolean(), kind: z.string(), input: z.string(), injected: z.string(), skills: z.string(), precedingTools: z.string(), output: z.string(), reasoning: z.string(), truncated: z.boolean(),
122
+ tools: z.array(turnInspectionSchema.shape.tools.element.extend({ durationMs: num.nullable().default(null) })), totalTools: num, offset: num })
123
+ const contextRateSchema = z.object(Object.fromEntries(['input', 'cacheRead', 'cacheWrite', 'output', 'reasoning'].map(key => [key, z.number().finite().nonnegative()])))
124
+ export const contextCostsSchema = z.object({
125
+ status: z.enum(['ready', 'busy', 'unavailable', 'session-unavailable', 'meter-unavailable', 'route-unavailable']),
126
+ sessionId: z.string(), generatedAt: num, revision: num, provider: z.string(), model: z.string(), basis: z.enum(['api', 'plan']), priced: z.boolean(),
127
+ source: z.enum(['none', 'usage', 'estimate']), linked: z.boolean(), contextTokens: z.number().finite().nonnegative(),
128
+ components: z.array(z.object({ key: z.enum(['system', 'tools', 'user', 'inject', 'skill', 'assistant', 'tool', 'other']), tokens: z.number().finite().nonnegative() })),
129
+ rates: contextRateSchema.nullable(), longContext: contextRateSchema.extend({ aboveInputTokens: z.number().positive() }).nullable(),
130
+ lastCall: turnCostSchema.shape.calls.element.extend({ sessionId: z.string().default(''), turn: num.nullable().default(null), step: num.nullable().default(null) }).nullable(),
131
+ })
132
+
133
+ const longContextSchema = z.object({
134
+ aboveInputTokens: z.number().positive(),
135
+ cacheHit: z.number().nonnegative(),
136
+ cacheMiss: z.number().nonnegative(),
137
+ cacheWrite: z.number().nonnegative().optional(),
138
+ output: z.number().nonnegative(),
139
+ reasoning: z.number().nonnegative().optional(),
140
+ })
141
+
142
+ const priceTierSchema = z.object({
143
+ cacheHit: num,
144
+ cacheMiss: num,
145
+ cacheWrite: z.number().nonnegative().optional(),
146
+ output: num,
147
+ reasoning: num.optional(),
148
+ })
149
+
150
+ const rateHistorySchema = priceTierSchema.extend({
151
+ before: z.string(),
152
+ offPeak: priceTierSchema.optional(),
153
+ peak: priceTierSchema.optional(),
154
+ })
155
+
156
+ const multiplierShape = {
157
+ multiplier: z.number().finite().nonnegative().optional(),
158
+ separateMultipliers: z.boolean().optional(),
159
+ multipliers: z.record(z.string().regex(multiplierPath), z.number().finite().nonnegative()).optional(),
160
+ }
161
+ const providerPriceSchema = z.object({
162
+ ...multiplierShape,
163
+ cacheHit: num.optional(),
164
+ cacheMiss: num.optional(),
165
+ input: num.optional(),
166
+ cachedInput: num.optional(),
167
+ cacheRead: num.optional(),
168
+ cacheWrite: z.number().nonnegative().optional(),
169
+ cny: priceTierSchema.optional(),
170
+ longContext: longContextSchema.optional(),
171
+ offPeak: priceTierSchema.optional(),
172
+ peak: priceTierSchema.optional(),
173
+ cacheCreation5m: num.optional(),
174
+ cacheCreation1h: num.optional(),
175
+ output: num.optional(),
176
+ reasoning: num.optional(),
177
+ unpriced: z.boolean().optional(),
178
+ billingMode: z.enum(['flat', 'deepseek-peak', 'utc-peak', 'batch']).optional(),
179
+ sourceUrl: z.string().optional(),
180
+ checkedAt: z.string().optional(),
181
+ notes: z.string().optional(),
182
+ })
183
+
184
+ const catalogEntrySchema = providerPriceSchema.extend({
185
+ cacheHit: num.optional(), cacheMiss: num.optional(), legacy: z.boolean().optional(),
186
+ offPeak: priceTierSchema.optional(), peak: priceTierSchema.optional(), legacyBase: priceTierSchema.optional(),
187
+ rateHistory: z.array(rateHistorySchema).max(16).optional(),
188
+ })
189
+ const priceCatalogSchema = z.record(z.string(), z.record(z.string(), z.record(z.string(), catalogEntrySchema)))
190
+
191
+ const priceSchema = z.object({
192
+ ...multiplierShape,
193
+ cacheHit: num,
194
+ cacheMiss: num,
195
+ cacheWrite: z.number().nonnegative().optional(),
196
+ longContext: longContextSchema.optional(),
197
+ output: num,
198
+ reasoning: num.optional(),
199
+ billingMode: z.enum(['flat', 'deepseek-peak', 'utc-peak', 'batch']).optional(),
200
+ offPeak: priceTierSchema.optional(),
201
+ peak: priceTierSchema.optional(),
202
+ legacy: z.boolean().optional(),
203
+ legacyBase: priceTierSchema.optional(),
204
+ rateHistory: z.array(rateHistorySchema).max(16).optional(),
205
+ sourceUrl: z.string().optional(),
206
+ checkedAt: z.string().optional(),
207
+ notes: z.string().optional(),
208
+ })
209
+
210
+ const configSchema = z.object({
211
+ locale: z.enum(['auto', 'zh', 'en']),
212
+ position: z.enum(['dock', 'header', 'off']),
213
+ sidebar: z.boolean(),
214
+ currency: z.string(),
215
+ symbol: z.string(),
216
+ decimals: num,
217
+ exchangeRate: num,
218
+ exchangeRateAuto: z.boolean().optional(),
219
+ fxRates: z.object({ USD: num, CNY: num, EUR: num }).optional(),
220
+ exchangeRateCheckedAt: num.optional(), exchangeRateDate: z.string().optional(),
221
+ // 官方价格币种(issue #47):USD(美元官方价) | CNY(人民币官方价,按汇率折算入账)。
222
+ pricingCurrency: z.enum(['USD', 'CNY']).optional(),
223
+ peakEnabled: z.boolean(),
224
+ peakEffectiveAt: z.string(),
225
+ peakWindows: z.array(z.object({ start: num, end: num })),
226
+ peakHolidays: z.array(z.string()),
227
+ peakNotice: z.boolean().optional(),
228
+ // 峰/谷切换前弹窗提醒:开关(默认开)/提前分钟数(1-30)/类型(峰|谷|两者)。
229
+ peakAlertEnabled: z.boolean().optional(),
230
+ peakAlertAhead: num.optional(),
231
+ peakAlertTarget: z.enum(['peak', 'offpeak', 'both']).optional(),
232
+ peakAlertPosition: z.enum(['corner', 'center']).optional(),
233
+ peakAlertWebNotify: z.boolean().optional(),
234
+ showSessionId: z.boolean().optional(),
235
+ // UI 隐藏开关(issues #45/#46):开启后官方余额/今日消耗金额的对应 UI 区块整体不渲染。
236
+ hideOfficialBalance: z.boolean().optional(),
237
+ hideBudget: z.boolean().optional(),
238
+ hideTodayCost: z.boolean().optional(),
239
+ modelStatistics: z.record(z.string(), z.object({ today: z.boolean().optional(), summary: z.boolean().optional(), budget: z.boolean().optional() }).strict()).optional(),
240
+ hideSessionCostHeader: z.boolean().optional(),
241
+ hideSessionCostDock: z.boolean().optional(),
242
+ hideTurnCost: z.boolean().optional(),
243
+ sessionCostCompact: z.boolean().optional(),
244
+ contextCostsEnabled: z.boolean().optional(),
245
+ contextCostsPromptSeen: z.boolean().optional(),
246
+ sidebarTodayMetric: z.enum(['cost', 'tokens']).optional(),
247
+ // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计。
248
+ statisticsBasis: z.enum(['auto', 'api', 'plan', 'total']).optional(),
249
+ showTotalWithPlan: z.boolean().optional(),
250
+ includeSubagentCost: z.boolean().optional(),
251
+ codexQuotaEnabled: z.boolean().optional(),
252
+ codexQuotaSidebar: z.boolean().optional(),
253
+ codexQuotaSource: z.enum(['auto', 'connect', 'subscription']).optional(),
254
+ // dsh-codex-subscription 兼容:一次性历史归类提示是否永久关闭 / 历史归类完成时刻 ms(0 = 未应用)。
255
+ codexCompatPromptDismissed: z.boolean().optional(),
256
+ codexCompatHistoryAppliedAt: num.optional(),
257
+ sidebarSimple: z.boolean().optional(),
258
+ sidebarSimplePromptSeen: z.boolean().optional(),
259
+ sidebarModels: z.object({ enabled: z.boolean(), period: z.enum(['today', 'history']), topN: z.number().int().min(1).max(10), summary: z.enum(['total', 'top']), position: z.enum(['first', 'afterBalance', 'last']), defaultOpen: z.boolean(), remember: z.boolean(), tokens: z.boolean(), shares: z.boolean(), refreshSeconds: z.number().int().min(10).max(60), dock: z.boolean() }).strict().optional(),
260
+ sidebarStyle: z.enum(['standard', 'compact']).optional(),
261
+ priceMatchDismissed: z.array(z.string()).optional(),
262
+ // 安装前历史自动导入完成时刻(issue #27,内部标记;0/缺席 = 尚未跑过)。
263
+ legacyAutoImportedAt: num.optional(),
264
+ peakStyle: z.enum(['compact', 'classic', 'progress']).optional(),
265
+ peakTimeDisplay: z.enum(['both', 'countdown', 'switch']).optional(),
266
+ peakProgressPromptSeen: z.boolean().optional(),
267
+ priceMatch: z.enum(['auto', 'exact']).optional(),
268
+ priceOverrides: z.record(z.string(), z.string()).optional(),
269
+ priceTableDisplay: z.record(z.string(), z.boolean()).optional(),
270
+ // prices 可缺席:轮询路径在客户端已持有同一版本时会省略整张价格表(占载荷
271
+ // 56%,实测 157.4/281.5 KB),客户端按 pricesRev 沿用它自己的上一份。
272
+ // 显式 RPC 与首次加载一律携带完整 prices,故旧客户端不受影响。
273
+ prices: z.object({
274
+ custom: z.record(z.string(), priceTierSchema.extend({ ...multiplierShape, currency: z.enum(['USD', 'CNY']), billingMode: z.literal('flat').optional() })).optional(),
275
+ // 价表币种标记(issue #47,fetchPrices 写入;zod 默认 strip 未知键,须显式声明才能下发)。
276
+ currency: z.enum(['USD', 'CNY']).optional(),
277
+ models: z.record(z.string(), priceSchema),
278
+ default: priceSchema,
279
+ providers: z.record(z.string(), z.object({ models: z.record(z.string(), providerPriceSchema) })).optional(),
280
+ }).optional(),
281
+ budget: z.object({
282
+ enabled: z.boolean(),
283
+ amount: num,
284
+ period: z.enum(['day', 'month', 'all', 'custom']),
285
+ customStart: z.union([z.string(), z.null()]),
286
+ customEnd: z.union([z.string(), z.null()]),
287
+ detail: z.boolean(),
288
+ }),
289
+ codingPlans: z.record(z.string(), z.object({
290
+ enabled: z.boolean().optional(),
291
+ display: z.enum(['sidebar', 'settings', 'both', 'off']).optional(),
292
+ refreshMinutes: num.optional(),
293
+ apiKey: z.string().optional(),
294
+ baseUrl: z.string().optional(),
295
+ orgId: z.string().optional(),
296
+ workspaceId: z.string().optional(),
297
+ factoryPool: z.enum(['standard', 'core', 'both']).optional(),
298
+ // SCNet 本地计量专用(issue #26):月度 Credits 额度与订阅起始日;其余厂商无此二键。
299
+ planCredits: num.optional(),
300
+ planStart: z.string().optional(),
301
+ quotaSource: z.enum(['local', 'cli', 'bailian']).optional(),
302
+ // 千问 Token Plan 抵扣率覆盖(issue #78):归一模型名 → 三费率;仅千问有此键。
303
+ rates: z.record(z.string(), z.object({
304
+ input: num,
305
+ cachedInput: num,
306
+ output: num,
307
+ })).optional(),
308
+ // 火山方舟双凭据(issue #60):AccessKeyID + SecretAccessKey
309
+ accessKeyId: z.string().optional(),
310
+ secretAccessKey: z.string().optional(),
311
+ // 密钥配置状态(v1.6.8):密钥改由 DSH 凭据库托管后,apiKey/accessKeyId/secretAccessKey
312
+ // 恒为空串,前端靠这两个描述性字段渲染 write-only 输入框(永不拿到密钥值本身)。
313
+ keyConfigured: z.boolean().optional(),
314
+ keySource: z.string().optional(),
315
+ })).optional(),
316
+ balance: z.object({
317
+ display: z.enum(['sidebar', 'settings', 'both', 'off']),
318
+ refreshMinutes: num,
319
+ showProgressBar: z.boolean().optional(),
320
+ budgetCap: z.union([num, z.null()]).optional(),
321
+ reconcile: z.boolean().optional(),
322
+ // 更新后提醒:余额图框点击刷新引导是否已处理(issue #37,内部标记)。
323
+ clickHintSeen: z.boolean().optional(),
324
+ }),
325
+ goQuota: z.object({
326
+ enabled: z.boolean(),
327
+ display: z.enum(['sidebar', 'settings', 'both', 'off']),
328
+ refreshMinutes: num,
329
+ // v1.6.8 起恒为空串:密钥由 DSH 凭据库托管,不再落盘也不再下发。
330
+ apiKey: z.string(),
331
+ main: z.enum(['rolling', 'weekly', 'monthly']),
332
+ detail: z.boolean(),
333
+ // 密钥配置状态(v1.6.8):见 codingPlans 同名字段的说明。
334
+ keyConfigured: z.boolean().optional(),
335
+ keySource: z.string().optional(),
336
+ }),
337
+ customBalance: z.object({
338
+ adapter: z.enum(['custom', 'aliyun', 'tokenrhythm']).optional(),
339
+ enabled: z.boolean(),
340
+ label: z.string(),
341
+ labelEn: z.string().optional(),
342
+ display: z.enum(['sidebar', 'settings', 'both', 'off']),
343
+ unit: z.enum(['USD', 'CNY', 'EUR', 'CREDITS']).optional(),
344
+ convertToDisplayCurrency: z.boolean().optional(),
345
+ allowInsecureHttp: z.boolean().optional(),
346
+ refreshMinutes: num,
347
+ request: z.object({
348
+ url: z.string(),
349
+ method: z.string().optional(),
350
+ headers: z.record(z.string(), z.string()).optional(),
351
+ body: z.unknown().optional(),
352
+ }),
353
+ extract: z.record(z.string(), z.unknown()),
354
+ allowedHosts: z.array(z.string()).optional(),
355
+ }).optional(),
356
+ // 多配置形态(v1.7.0,issue #79):自定义 Provider 余额多条并行,数组为运行期
357
+ // 真源;customBalance 单配置键仅为旧客户端兼容保留(= entries[0] 的镜像)。
358
+ customBalances: z.array(z.object({
359
+ adapter: z.enum(['custom', 'aliyun', 'tokenrhythm']).optional(),
360
+ enabled: z.boolean(),
361
+ label: z.string(),
362
+ labelEn: z.string().optional(),
363
+ display: z.enum(['sidebar', 'settings', 'both', 'off']),
364
+ unit: z.enum(['USD', 'CNY', 'EUR', 'CREDITS']).optional(),
365
+ convertToDisplayCurrency: z.boolean().optional(),
366
+ allowInsecureHttp: z.boolean().optional(),
367
+ refreshMinutes: num,
368
+ request: z.object({
369
+ url: z.string(),
370
+ method: z.string().optional(),
371
+ headers: z.record(z.string(), z.string()).optional(),
372
+ body: z.unknown().optional(),
373
+ }),
374
+ extract: z.record(z.string(), z.unknown()),
375
+ allowedHosts: z.array(z.string()).optional(),
376
+ })).optional(),
377
+ gatewayQuotas: z.object({
378
+ sources: z.array(z.object({
379
+ id: z.string(),
380
+ type: z.literal('cliproxyapi'),
381
+ label: z.string(),
382
+ baseURL: z.string(),
383
+ enabled: z.boolean(),
384
+ display: z.enum(['sidebar', 'settings', 'both', 'off']),
385
+ refreshMinutes: num,
386
+ includeProviders: z.array(z.string()),
387
+ allowedHosts: z.array(z.string()),
388
+ allowInsecureHttp: z.boolean(),
389
+ // 只显示 Antigravity 的 Gemini 原生组(过滤 Claude/GPT 第三方模型池);缺省不开启。
390
+ antigravityOnlyGemini: z.boolean().optional(),
391
+ // 派生凭据变量名(issue #87):客户端据此定位 write-only 目标,非敏感。
392
+ keyVar: z.string().optional(),
393
+ })),
394
+ }).optional(),
395
+ corner: z.object({
396
+ enabled: z.boolean(),
397
+ goRolling: z.boolean(),
398
+ goWeekly: z.boolean(),
399
+ goMonthly: z.boolean(),
400
+ budget: z.boolean(),
401
+ }),
402
+ // 输入框上方额度横条(v1.5.27):预算/Go/Coding Plan 用量横条 + 首次引导标记。
403
+ quotaStrip: z.object({
404
+ enabled: z.boolean(),
405
+ budget: z.boolean(),
406
+ go: z.boolean(),
407
+ plans: z.boolean(),
408
+ promptSeen: z.boolean(),
409
+ }),
410
+ // 进度条方向(issue #67):balance/budget/go/plan 各自 remaining | used。
411
+ barDirections: z.object({
412
+ balance: z.enum(['remaining', 'used']),
413
+ budget: z.enum(['remaining', 'used']),
414
+ go: z.enum(['remaining', 'used']),
415
+ plan: z.enum(['remaining', 'used']),
416
+ }).optional(),
417
+ // Token 用量统计显示位置(当前固定 cost;键保留供读侧白名单)。
418
+ usage: z.object({ position: z.enum(['cost', 'general', 'section']) }).optional(),
419
+ // Plan/API 双轨计费分类(issue #64):providers 值 auto/plan/api;models 为 provider:model 显式覆盖。
420
+ planBilling: z.object({
421
+ providers: z.record(z.string(), z.enum(['auto', 'plan', 'api'])),
422
+ models: z.record(z.string(), z.enum(['plan', 'api'])),
423
+ modelPlans: z.record(z.string(), z.enum(['opendesign', 'anthropic', 'zai', 'minimax', 'kimi', 'openrouter', 'siliconflow', 'commandcode', 'scnet', 'volcengine', 'qwen', 'mimo', 'factory', 'go', 'codex', 'volcengine-agent', 'tencent-coding', 'tencent-token', 'baidu-coding'])).optional(),
424
+ }).optional(),
425
+ historyDays: num,
426
+ fetchedAt: z.union([z.string(), z.null()]),
427
+ priceSource: z.string(),
428
+ })
429
+
430
+ const balanceSchema = z.object({
431
+ keyConfigured: z.boolean().optional(),
432
+ keySource: z.string().optional(),
433
+ status: z.enum(['off', 'ok', 'error']),
434
+ message: z.string(),
435
+ fetchedAt: num,
436
+ currency: z.string(),
437
+ totalBalance: num,
438
+ grantedBalance: num,
439
+ toppedUpBalance: num,
440
+ })
441
+
442
+ const goWindowSchema = z.union([
443
+ z.object({ percent: num, resetsAt: z.string() }),
444
+ z.null(),
445
+ ])
446
+
447
+ const goQuotaSchema = z.object({
448
+ status: z.enum(['off', 'ok', 'error']),
449
+ message: z.string(),
450
+ fetchedAt: num,
451
+ rolling: goWindowSchema,
452
+ weekly: goWindowSchema,
453
+ monthly: goWindowSchema,
454
+ })
455
+
456
+ const customBalanceSchema = z.object({
457
+ status: z.enum(['off', 'ok', 'error']),
458
+ message: z.string(),
459
+ fetchedAt: num,
460
+ label: z.string(),
461
+ unit: z.string(),
462
+ remaining: num,
463
+ maxBudget: z.union([num, z.null()]),
464
+ spend: z.union([num, z.null()]),
465
+ // 条目索引(v1.7.0,issue #79):多配置形态下每条快照自带其在
466
+ // config.customBalances 中的下标,客户端据此定位刷新按钮对应的条目。
467
+ index: num.optional(),
468
+ })
469
+
470
+ const gatewayWindowSchema = z.object({
471
+ id: z.string().max(96),
472
+ label: z.string().max(160),
473
+ percent: num.min(0).max(100).optional(),
474
+ resetsAt: z.union([z.string(), z.null()]),
475
+ periodHours: z.union([num, z.null()]),
476
+ scope: z.string().max(32),
477
+ })
478
+ const gatewayCreditsSchema = z.object({
479
+ unit: z.string().max(32),
480
+ used: z.union([num, z.null()]),
481
+ remaining: z.union([num, z.null()]),
482
+ limit: z.union([num, z.null()]),
483
+ fetchedAt: z.union([z.string(), z.null()]),
484
+ packages: z.array(z.object({
485
+ id: z.string().max(96), label: z.string().max(160), used: z.union([num, z.null()]),
486
+ remaining: z.union([num, z.null()]), limit: z.union([num, z.null()]),
487
+ startsAt: z.union([z.string(), z.null()]), resetsAt: z.union([z.string(), z.null()]),
488
+ })).max(32),
489
+ })
490
+ const gatewayAccountSchema = z.object({
491
+ id: z.string().max(64), provider: z.enum(['antigravity', 'claude', 'codex', 'kimi', 'xai', 'workbuddy']), label: z.string().max(160),
492
+ status: z.enum(['ok', 'partial', 'unknown', 'error', 'stale', 'unsupported', 'capability_missing']),
493
+ message: z.string(), windows: z.array(gatewayWindowSchema),
494
+ plan: z.string().optional(), credits: gatewayCreditsSchema.optional(),
495
+ })
496
+ const gatewayQuotaSchema = z.object({
497
+ id: z.string().max(48), type: z.literal('cliproxyapi'), label: z.string().max(80),
498
+ status: z.enum(['off', 'loading', 'ok', 'partial', 'stale', 'error']),
499
+ message: z.string(), fetchedAt: num, attemptedAt: num,
500
+ serverVersion: z.string(), keyConfigured: z.boolean(), keySource: z.string(),
501
+ accounts: z.array(gatewayAccountSchema), unsupportedProviders: z.array(z.string()),
502
+ })
503
+
504
+ // Coding plan 额度状态条目(运行时合并配置与查询结果;windows 为各用量窗口)。
505
+ const codingPlanSchema = z.object({
506
+ enabled: z.boolean(),
507
+ display: z.enum(['sidebar', 'settings', 'both', 'off']),
508
+ refreshMinutes: num,
509
+ // v1.6.8 起恒为空串(密钥已改由 DSH 凭据库托管):仅保留字段以兼容旧客户端。
510
+ apiKey: z.string(),
511
+ baseUrl: z.string().optional(),
512
+ orgId: z.string().optional(),
513
+ workspaceId: z.string().optional(),
514
+ factoryPool: z.enum(['standard', 'core', 'both']).optional(),
515
+ // 密钥配置状态(v1.6.8):是否已在凭据库中配置,以及来自哪一层(env / file / legacy)。
516
+ keyConfigured: z.boolean().optional(),
517
+ keySource: z.string().optional(),
518
+ status: z.enum(['off', 'ok', 'error']),
519
+ message: z.string(),
520
+ fetchedAt: num,
521
+ windows: z.record(z.string(), z.object({ percent: num.optional(), resetsAt: z.string(), text: z.string().optional(), unlimited: z.boolean().optional() })),
522
+ // 百炼 CLI 缺少额度查询所需的控制台凭据时显示登录按钮。
523
+ loginRequired: z.boolean().optional(),
524
+ // 本地计量配置透传(仅 scnet / qwen 有;settings 页编辑入口需要看到当前值)。
525
+ planCredits: num.optional(),
526
+ planStart: z.string().optional(),
527
+ quotaSource: z.enum(['local', 'cli', 'bailian']).optional(),
528
+ rates: z.record(z.string(), z.object({
529
+ input: num,
530
+ cachedInput: num,
531
+ output: num,
532
+ })).optional(),
533
+ })
534
+
535
+ // Token Plan 统计(issue #64):每 provider×window 的本地聚合、每 1%/满窗估算与采样区间序列。
536
+ const planWindowStatSchema = z.object({
537
+ percent: num,
538
+ resetsAt: z.string(),
539
+ localTokens: num,
540
+ localCost: num,
541
+ method: z.enum(['sample', 'live', 'none']),
542
+ // 采样差分估算的基准时刻(最近有效区间终点;live/none 为 null)
543
+ sampleAt: z.union([num, z.null()]).optional(),
544
+ // 置信分档(v1.5.53):high = 差分跨度 Δp ≥ 5(个位量化误差 ≤ ±10%);
545
+ // low = 跨度不足或 live 回退,结果波动大;none 方法为 null。缺席 = 旧快照。
546
+ confidence: z.union([z.enum(['high', 'low']), z.null()]).optional(),
547
+ per1Tokens: z.union([num, z.null()]),
548
+ per1Cost: z.union([num, z.null()]),
549
+ fullTokens: z.union([num, z.null()]),
550
+ fullCost: z.union([num, z.null()]),
551
+ sampleCount: num,
552
+ })
553
+ const planIntervalSchema = z.object({
554
+ t0: num,
555
+ t1: num,
556
+ tokens: num,
557
+ cost: num,
558
+ pct: num,
559
+ per1Tokens: num,
560
+ per1Cost: num,
561
+ })
562
+ const planProviderStatSchema = z.object({
563
+ windows: z.record(z.string(), planWindowStatSchema),
564
+ intervals: z.record(z.string(), z.array(planIntervalSchema)),
565
+ })
566
+ const planStatsSchema = z.object({
567
+ generatedAt: num,
568
+ providers: z.record(z.string(), planProviderStatSchema),
569
+ })
570
+
571
+ export const stateSchema = z.object({
572
+ today: daySchema,
573
+ month: daySchema,
574
+ total: daySchema,
575
+ budgetUsed: num,
576
+ balance: balanceSchema,
577
+ goQuota: goQuotaSchema,
578
+ // optional:兼容旧快照/降级路径(与 codingPlans/priceCatalog 同策略,避免 strict codec 击穿)。
579
+ customBalance: customBalanceSchema.optional(),
580
+ // 多配置形态(v1.7.0,issue #79):每条独立快照;customBalance 单条键为
581
+ // 旧客户端兼容镜像(= 第一条 sidebar 可见条目或 entries[0])。
582
+ customBalances: z.array(customBalanceSchema).optional(),
583
+ gatewayQuotas: z.array(gatewayQuotaSchema).optional(),
584
+ // 自定义余额 {{VAR}} 占位符的凭据状态(v1.7.6,issue #86):变量名 → 是否已配置/来源。
585
+ // 只含 describe 摘要,不含密钥值;旧快照缺席时视为空表。
586
+ customVarStatus: z.record(z.string(), z.object({
587
+ configured: z.boolean(),
588
+ source: z.string(),
589
+ })).optional(),
590
+ // 余额差交叉校验提示(issue #18):旧快照无此字段,optional 防击穿。
591
+ reconcile: z.object({ ok: z.boolean(), message: z.string() }).optional(),
592
+ codingPlans: z.record(z.string(), codingPlanSchema),
593
+ // Token Plan 统计(issue #64);缺席 = 旧快照/降级路径。
594
+ planStats: planStatsSchema.optional(),
595
+ history: z.array(daySchema),
596
+ externalUsage: externalUsageSchema.optional(),
597
+ billionContext: z.object({ protocol: num, connected: z.boolean(), failed: z.boolean(), requests: num, unreported: num, partial: num, uncovered: num,
598
+ detected: z.boolean().optional(), version: z.string().optional(), compatibility: z.enum(['unknown', 'ready', 'needs_update', 'changed', 'bridge_missing']).optional(), noticeId: z.string().optional() }).optional(),
599
+ // dsh-codex-subscription 兼容(契约 C):仅在该插件安装时下发;键缺席 = 旧宿主 / 未安装,
600
+ // strict codec 会丢弃未声明字段,故必须显式声明整棵状态树。
601
+ codexCompat: z.object({
602
+ installed: z.boolean(),
603
+ enabled: z.boolean().optional(),
604
+ version: z.string(),
605
+ detection: z.enum(['package', 'profile', 'none']),
606
+ planClass: z.enum(['auto', 'plan', 'api']),
607
+ usage: z.object({ calls: num, cost: num, tokens: num, days: num, providers: z.array(z.string()) }),
608
+ historyAppliedAt: num,
609
+ promptDismissed: z.boolean(),
610
+ promptDue: z.boolean(),
611
+ }).optional(),
612
+ config: configSchema,
613
+ // 价格表版本号(宿主进程内唯一前缀 + 递增计数):客户端回传该值,一致时宿主
614
+ // 省略 config.prices(占轮询载荷 56%)。缺席 = 旧宿主,客户端照常收全量。
615
+ pricesRev: z.string().optional(),
616
+ // 手改过价格的 OpenRouter 模型 id:前端标注「已自定义 · 不会被自动同步覆盖」。
617
+ // 与刷新跳过覆盖的判定同源;无锁定时不下发本字段(旧快照兼容)。
618
+ priceLockIds: z.array(z.string()).optional(),
619
+ // 存量密钥迁移提示(v1.6.8):仅在有密钥未能自动导入凭据库时出现,值为环境变量名。
620
+ secretMigration: z.object({ pending: z.array(z.string()) }).optional(),
621
+ meta: z.object({
622
+ locale: z.enum(['zh', 'en']).optional(),
623
+ now: num,
624
+ timezoneOffsetMinutes: num,
625
+ // 宿主机 IANA 时区名(issue #74):与浏览器时区错位时前端显示提示;缺席 = 宿主取不到时区名。
626
+ timezone: z.string().optional(),
627
+ dayKey: z.string(),
628
+ monthKey: z.string(),
629
+ }),
630
+ })
631
+
632
+ const patchSchema = z.record(z.string(), z.unknown())
633
+
634
+ const openRouterCatalogSchema = z.object({
635
+ fetchedAt: z.string(), stale: z.boolean(), error: z.string(),
636
+ models: z.array(z.object({
637
+ id: z.string(), name: z.string(), contextLength: z.number().int().nonnegative().nullable(),
638
+ input: z.number().nonnegative(), output: z.number().nonnegative(),
639
+ cachedInput: z.number().nonnegative().nullable(), cacheWrite: z.number().nonnegative().nullable(),
640
+ })),
641
+ })
642
+
643
+ const fetchPricesSchema = z.object({
644
+ ok: z.boolean(),
645
+ message: z.string(),
646
+ state: stateSchema.optional(),
647
+ })
648
+
649
+ const strictCodec = (name, schema) => ({ mode: 'strict', typeSymbol: 'dsh-cost-meter#' + name, schema, create: () => schema })
650
+ const _state$codec = strictCodec('CostState', stateSchema)
651
+ const _patch$codec = strictCodec('ConfigPatch', patchSchema)
652
+ const _fetch$codec = strictCodec('FetchPricesResult', fetchPricesSchema)
653
+ const _repricingHistory$codec = strictCodec('RepricingHistory', z.array(z.object({ ...Object.fromEntries(['at', 'before', 'after', 'days', 'sessions', 'skipped'].map(key => [key, z.number().finite().nonnegative()])), ...Object.fromEntries(['beforeCny', 'afterCny', 'beforeEur', 'afterEur'].map(key => [key, z.number().finite().nonnegative().optional()])), model: z.string().optional() })))
654
+ const _repricingConfirmation$codec = strictCodec('RepricingConfirmation', z.boolean())
655
+ const _repricingModel$codec = strictCodec('RepricingModel', z.string().min(3).max(2048).refine(value => value.indexOf(':') > 0 && !value.endsWith(':') && !/[\r\n]/.test(value)))
656
+ const _provider$codec = strictCodec('CodingPlanProvider', z.string())
657
+ const _gatewaySourceId$codec = strictCodec('GatewayQuotaSourceId', z.string().optional())
658
+ // 密钥目标(v1.6.8):'goQuota' | 'codingPlans.<id>' | 'codingPlans.volcengine.ak' | '...sk'
659
+ const _credTarget$codec = strictCodec('CredentialTarget', z.string())
660
+ // 密钥明文(v1.6.8):仅经 setCredential 单向写入凭据库,永不回传前端。
661
+ const _credValue$codec = strictCodec('CredentialValue', z.string())
662
+ const _day$codec = strictCodec('DayRecord', daySchema)
663
+ const _date$codec = strictCodec('DayKey', z.string())
664
+ const _topSessions$codec = strictCodec('TopSessions', topSessionsSchema)
665
+ const _limit$codec = strictCodec('SessionLimit', num)
666
+ const _sort$codec = strictCodec('SessionSort', z.string())
667
+ const _dir$codec = strictCodec('SessionSortDir', z.string())
668
+ const _sessionId$codec = strictCodec('SessionId', z.string().min(1).max(512))
669
+ const _sessionCost$codec = strictCodec('SessionCost', sessionCostSchema)
670
+ const _turnCost$codec = strictCodec('TurnCost', turnCostSchema)
671
+ const _turnSeq$codec = strictCodec('TurnSeq', z.number().int().nonnegative())
672
+
673
+ export const TYPERT = {
674
+ package: 'dsh-cost-meter',
675
+ face: 'host',
676
+ schemas: [],
677
+ invocations: [
678
+ { id: 'dsh-cost-meter#costMeter/getContextIntegration', service: 'costMeter', namespace: 'costMeter', method: 'getContextIntegration', invocation: { kind: 'direct' }, parameters: [],
679
+ result: strictCodec('ContextIntegration', z.object({ version: z.string(), compatible: z.boolean(), reason: z.enum(['ready', 'missing', 'unsupported', 'unavailable']) })) },
680
+ {
681
+ id: 'dsh-cost-meter#costMeter/getOpenRouterCatalog', service: 'costMeter', namespace: 'costMeter', method: 'getOpenRouterCatalog',
682
+ invocation: { kind: 'direct' }, parameters: [], result: strictCodec('OpenRouterCatalog', openRouterCatalogSchema),
683
+ },
684
+ {
685
+ id: 'dsh-cost-meter#costMeter/getState',
686
+ service: 'costMeter',
687
+ namespace: 'costMeter',
688
+ method: 'getState',
689
+ invocation: { kind: 'direct' },
690
+ parameters: [],
691
+ result: _state$codec,
692
+ },
693
+ { id: 'dsh-cost-meter#costMeter/getStateSince', service: 'costMeter', namespace: 'costMeter', method: 'getStateSince', invocation: { kind: 'direct' },
694
+ parameters: [{ name: 'pricesRev', wire: 'pricesRev', source: 'json', codec: strictCodec('PricesRev', z.string()) }], result: _state$codec },
695
+ { id: 'dsh-cost-meter#costMeter/getLocalState', service: 'costMeter', namespace: 'costMeter', method: 'getLocalState', invocation: { kind: 'direct' }, parameters: [], result: _state$codec },
696
+ { id: 'dsh-cost-meter#costMeter/getRepricingHistory', service: 'costMeter', namespace: 'costMeter', method: 'getRepricingHistory', invocation: { kind: 'direct' }, parameters: [], result: _repricingHistory$codec },
697
+ { id: 'dsh-cost-meter#costMeter/getPriceCatalog', service: 'costMeter', namespace: 'costMeter', method: 'getPriceCatalog', invocation: { kind: 'direct' }, parameters: [], result: strictCodec('PriceCatalog', priceCatalogSchema) },
698
+ { id: 'dsh-cost-meter#costMeter/repriceHistory', service: 'costMeter', namespace: 'costMeter', method: 'repriceHistory', invocation: { kind: 'direct' }, parameters: [{ name: 'confirmed', wire: 'confirmed', source: 'json', codec: _repricingConfirmation$codec }], result: _fetch$codec },
699
+ { id: 'dsh-cost-meter#costMeter/repriceModelHistory', service: 'costMeter', namespace: 'costMeter', method: 'repriceModelHistory', invocation: { kind: 'direct' }, parameters: [{ name: 'confirmed', wire: 'confirmed', source: 'json', codec: _repricingConfirmation$codec }, { name: 'model', wire: 'model', source: 'json', codec: _repricingModel$codec }], result: _fetch$codec },
700
+ {
701
+ id: 'dsh-cost-meter#costMeter/updateConfig',
702
+ service: 'costMeter',
703
+ namespace: 'costMeter',
704
+ method: 'updateConfig',
705
+ invocation: { kind: 'direct' },
706
+ parameters: [
707
+ { name: 'patch', wire: 'patch', source: 'json', codec: _patch$codec },
708
+ ],
709
+ result: _state$codec,
710
+ },
711
+ {
712
+ // dsh-codex-subscription 兼容(契约 D):把历史 codex 类计费统一归类为 Plan,
713
+ // 影响 Plan 配额基线,返回完整 state。
714
+ id: 'dsh-cost-meter#costMeter/applyCodexCompatHistory',
715
+ service: 'costMeter',
716
+ namespace: 'costMeter',
717
+ method: 'applyCodexCompatHistory',
718
+ invocation: { kind: 'direct' },
719
+ parameters: [],
720
+ result: _state$codec,
721
+ },
722
+ {
723
+ // 永久关闭一次性兼容提示(×/保持现状/ESC),返回完整 state。
724
+ id: 'dsh-cost-meter#costMeter/dismissCodexCompat',
725
+ service: 'costMeter',
726
+ namespace: 'costMeter',
727
+ method: 'dismissCodexCompat',
728
+ invocation: { kind: 'direct' },
729
+ parameters: [],
730
+ result: _state$codec,
731
+ },
732
+ {
733
+ id: 'dsh-cost-meter#costMeter/fetchPrices',
734
+ service: 'costMeter',
735
+ namespace: 'costMeter',
736
+ method: 'fetchPrices',
737
+ invocation: { kind: 'direct' },
738
+ parameters: [],
739
+ result: _fetch$codec,
740
+ },
741
+ {
742
+ id: 'dsh-cost-meter#costMeter/releasePriceLock',
743
+ service: 'costMeter',
744
+ namespace: 'costMeter',
745
+ method: 'releasePriceLock',
746
+ invocation: { kind: 'direct' },
747
+ parameters: [
748
+ { name: 'id', wire: 'id', source: 'json', codec: strictCodec('PriceLockId', z.string().min(1)) },
749
+ ],
750
+ result: _fetch$codec,
751
+ },
752
+ {
753
+ id: 'dsh-cost-meter#costMeter/refreshBalance',
754
+ service: 'costMeter',
755
+ namespace: 'costMeter',
756
+ method: 'refreshBalance',
757
+ invocation: { kind: 'direct' },
758
+ parameters: [],
759
+ result: _fetch$codec,
760
+ },
761
+ {
762
+ id: 'dsh-cost-meter#costMeter/refreshGoQuota',
763
+ service: 'costMeter',
764
+ namespace: 'costMeter',
765
+ method: 'refreshGoQuota',
766
+ invocation: { kind: 'direct' },
767
+ parameters: [],
768
+ result: _fetch$codec,
769
+ },
770
+ {
771
+ id: 'dsh-cost-meter#costMeter/refreshCustomBalance',
772
+ service: 'costMeter',
773
+ namespace: 'costMeter',
774
+ method: 'refreshCustomBalance',
775
+ invocation: { kind: 'direct' },
776
+ // index(v1.7.0,issue #79):多配置形态下指定刷新的条目下标;缺省 = 全部刷新。
777
+ // acceptsUndefined(v1.7.1):网关按「期望 wire 字段是否在 args 中」判缺失——
778
+ // 无此标志的 json 参数缺省会以 arguments-invalid 拒绝调用;标志允许旧客户端
779
+ // 的无参调用(等价全量刷新)继续走通。codec 必须是 strict 对象(裸 zod schema
780
+ // 会被 typert-loader 以「parameter codec must use a strict codec」拒绝注册,
781
+ // v1.7.0 因此无法启动宿主——本版回归)。
782
+ parameters: [
783
+ {
784
+ name: 'index', wire: 'index', source: 'json', acceptsUndefined: true,
785
+ codec: strictCodec('CustomBalanceIndex', z.number().int().min(0).max(7).optional()),
786
+ },
787
+ ],
788
+ result: _fetch$codec,
789
+ },
790
+ {
791
+ id: 'dsh-cost-meter#costMeter/refreshCodingPlan',
792
+ service: 'costMeter',
793
+ namespace: 'costMeter',
794
+ method: 'refreshCodingPlan',
795
+ invocation: { kind: 'direct' },
796
+ parameters: [
797
+ { name: 'provider', wire: 'provider', source: 'json', codec: _provider$codec },
798
+ ],
799
+ result: _fetch$codec,
800
+ },
801
+ {
802
+ id: 'dsh-cost-meter#costMeter/loginCodingPlan',
803
+ service: 'costMeter',
804
+ namespace: 'costMeter',
805
+ method: 'loginCodingPlan',
806
+ invocation: { kind: 'direct' },
807
+ parameters: [
808
+ { name: 'provider', wire: 'provider', source: 'json', codec: _provider$codec },
809
+ ],
810
+ result: _fetch$codec,
811
+ },
812
+ {
813
+ id: 'dsh-cost-meter#costMeter/refreshGatewayQuota',
814
+ service: 'costMeter',
815
+ namespace: 'costMeter',
816
+ method: 'refreshGatewayQuota',
817
+ invocation: { kind: 'direct' },
818
+ parameters: [
819
+ { name: 'sourceId', wire: 'sourceId', source: 'json', acceptsUndefined: true, codec: _gatewaySourceId$codec },
820
+ ],
821
+ result: _fetch$codec,
822
+ },
823
+ {
824
+ id: 'dsh-cost-meter#costMeter/resetHistory',
825
+ service: 'costMeter',
826
+ namespace: 'costMeter',
827
+ method: 'resetHistory',
828
+ invocation: { kind: 'direct' },
829
+ parameters: [],
830
+ result: _state$codec,
831
+ },
832
+ {
833
+ // 导入安装前历史(issue #27):回放全部会话日志,只补账本缺失的日期/会话。
834
+ id: 'dsh-cost-meter#costMeter/importLegacyHistory',
835
+ service: 'costMeter',
836
+ namespace: 'costMeter',
837
+ method: 'importLegacyHistory',
838
+ invocation: { kind: 'direct' },
839
+ parameters: [],
840
+ result: _fetch$codec,
841
+ },
842
+ {
843
+ id: 'dsh-cost-meter#costMeter/getDaySessions',
844
+ service: 'costMeter',
845
+ namespace: 'costMeter',
846
+ method: 'getDaySessions',
847
+ invocation: { kind: 'direct' },
848
+ parameters: [
849
+ { name: 'date', wire: 'date', source: 'json', codec: _date$codec },
850
+ ],
851
+ result: _day$codec,
852
+ },
853
+ {
854
+ id: 'dsh-cost-meter#costMeter/getTopSessions',
855
+ service: 'costMeter',
856
+ namespace: 'costMeter',
857
+ method: 'getTopSessions',
858
+ invocation: { kind: 'direct' },
859
+ parameters: [
860
+ { name: 'limit', wire: 'limit', source: 'json', codec: _limit$codec },
861
+ // sort/dir 与服务端函数默认值(sort='cost', dir='desc')对应,声明可缺省:
862
+ // 网关对 args 字段做精确匹配,不声明 acceptsUndefined 时旧客户端单参数调用
863
+ // 会因 missing "sort"/"dir" 被拒,会话排行面板直接加载失败。
864
+ { name: 'sort', wire: 'sort', source: 'json', codec: _sort$codec, acceptsUndefined: true },
865
+ { name: 'dir', wire: 'dir', source: 'json', codec: _dir$codec, acceptsUndefined: true },
866
+ ],
867
+ result: _topSessions$codec,
868
+ },
869
+ {
870
+ id: 'dsh-cost-meter#costMeter/getSessionCost',
871
+ service: 'costMeter',
872
+ namespace: 'costMeter',
873
+ method: 'getSessionCost',
874
+ invocation: { kind: 'direct' },
875
+ parameters: [{ name: 'sessionId', wire: 'sessionId', source: 'json', codec: _sessionId$codec }],
876
+ result: _sessionCost$codec,
877
+ },
878
+ {
879
+ id: 'dsh-cost-meter#costMeter/getTurnCost', service: 'costMeter', namespace: 'costMeter', method: 'getTurnCost',
880
+ invocation: { kind: 'direct' },
881
+ parameters: [{ name: 'sessionId', wire: 'sessionId', source: 'json', codec: _sessionId$codec }, { name: 'startSeq', wire: 'startSeq', source: 'json', codec: _turnSeq$codec }, { name: 'endSeq', wire: 'endSeq', source: 'json', codec: _turnSeq$codec }, { name: 'displayCurrency', wire: 'displayCurrency', source: 'json', acceptsUndefined: true, codec: strictCodec('DisplayCurrency', z.enum(['USD', 'CNY', 'EUR']).optional()) }],
882
+ result: _turnCost$codec,
883
+ },
884
+ ...[['getBillingStatistics', 'BillingStatistics', billingStatisticsSchema], ['getSessionBilling', 'SessionBilling', sessionBillingSchema]].map(([method, name, schema]) => ({
885
+ id: 'dsh-cost-meter#costMeter/' + method, service: 'costMeter', namespace: 'costMeter', method, invocation: { kind: 'direct' },
886
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('StatisticsQuery', statisticsQuerySchema) }],
887
+ result: strictCodec(name, schema),
888
+ })),
889
+ { id: 'dsh-cost-meter#costMeter/getTurnInspection', service: 'costMeter', namespace: 'costMeter', method: 'getTurnInspection', invocation: { kind: 'direct' },
890
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('TurnInspectionQuery', turnInspectionQuerySchema) }], result: strictCodec('TurnInspection', turnInspectionSchema) },
891
+ { id: 'dsh-cost-meter#costMeter/getCallInspection', service: 'costMeter', namespace: 'costMeter', method: 'getCallInspection', invocation: { kind: 'direct' },
892
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('CallInspectionQuery', callInspectionQuerySchema) }], result: strictCodec('CallInspection', callInspectionSchema) },
893
+ ...[['getSessionTrajectory', 'Trajectory', trajectoryQuerySchema, trajectorySchema]].map(([method, name, query, schema]) => ({
894
+ id: 'dsh-cost-meter#costMeter/' + method, service: 'costMeter', namespace: 'costMeter', method, invocation: { kind: 'direct' },
895
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec(name + 'Query', query) }], result: strictCodec(name, schema) })),
896
+ { id: 'dsh-cost-meter#costMeter/getContextCosts', service: 'costMeter', namespace: 'costMeter', method: 'getContextCosts', invocation: { kind: 'direct' },
897
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('ContextCostsQuery', contextCostsQuerySchema) }], result: strictCodec('ContextCosts', contextCostsSchema) },
898
+ {
899
+ // 写入一枚密钥到 DSH 凭据库(v1.6.8):密钥不再经 updateConfig 传递,值只进凭据库。
900
+ id: 'dsh-cost-meter#costMeter/setCredential',
901
+ service: 'costMeter',
902
+ namespace: 'costMeter',
903
+ method: 'setCredential',
904
+ invocation: { kind: 'direct' },
905
+ parameters: [
906
+ { name: 'target', wire: 'target', source: 'json', codec: _credTarget$codec },
907
+ { name: 'value', wire: 'value', source: 'json', codec: _credValue$codec },
908
+ ],
909
+ result: _fetch$codec,
910
+ },
911
+ {
912
+ // 从 DSH 凭据库移除一枚密钥(v1.6.8)。
913
+ id: 'dsh-cost-meter#costMeter/clearCredential',
914
+ service: 'costMeter',
915
+ namespace: 'costMeter',
916
+ method: 'clearCredential',
917
+ invocation: { kind: 'direct' },
918
+ parameters: [
919
+ { name: 'target', wire: 'target', source: 'json', codec: _credTarget$codec },
920
+ ],
921
+ result: _fetch$codec,
922
+ },
923
+ ],
924
+ model: {
925
+ services: [
926
+ {
927
+ description: 'dsh-cost-meter 账本与配置服务(ctx.costMeter),聚合每日模型用量与费用。Ledger and config service (ctx.costMeter) aggregating daily model usage and cost.',
928
+ summary: 'dsh-cost-meter 账本与配置服务 (dsh-cost-meter ledger & config service)。',
929
+ tags: [],
930
+ jsDoc: '/** dsh-cost-meter 账本与配置服务(ctx.costMeter)。dsh-cost-meter ledger & config service (ctx.costMeter). */',
931
+ key: 'costMeter',
932
+ exportName: 'CostMeterService',
933
+ members: [
934
+ { kind: 'method', name: 'getStateSince', signature: 'getStateSince(pricesRev: string): Promise<CostState>', summary: '按已知价格版本读取状态。Read state with a known price revision.' },
935
+ {
936
+ kind: 'method',
937
+ name: 'getState',
938
+ signature: 'getState(): CostState',
939
+ summary: '读取今日/本月/累计聚合、历史记录与当前配置。Read today/month/total aggregates, history, and current config.',
940
+ jsDoc: '/**\n * 读取今日/本月/累计聚合、历史记录与当前配置。\n * @returns 完整账本快照。\n * Read today/month/total aggregates, history, and current config.\n * @returns The full ledger snapshot.\n */',
941
+ },
942
+ {
943
+ kind: 'method',
944
+ name: 'updateConfig',
945
+ signature: 'updateConfig(patch: ConfigPatch): CostState',
946
+ summary: '深合并一份配置补丁并持久化。Deep-merge a config patch and persist it.',
947
+ jsDoc: '/**\n * 深合并一份配置补丁并持久化。\n * @param patch - 配置补丁。\n * @returns 更新后的完整快照。\n * Deep-merge a config patch and persist it.\n * @param patch - The config patch.\n * @returns The updated full snapshot.\n */',
948
+ },
949
+ {
950
+ kind: 'method',
951
+ name: 'fetchPrices',
952
+ signature: 'fetchPrices(): Promise<FetchPricesResult>',
953
+ summary: '抓取官方定价页并应用解析出的价格。Fetch the official pricing page and apply the parsed prices.',
954
+ jsDoc: '/**\n * 抓取官方定价页并应用解析出的价格。\n * @returns 抓取与应用结果。\n * Fetch the official pricing page and apply the parsed prices.\n * @returns The fetch-and-apply result.\n */',
955
+ },
956
+ { kind: 'method', name: 'getRepricingHistory', signature: 'getRepricingHistory(): Promise<RepricingHistory>', summary: '读取历史重算前后的金额。Read original and recalculated amounts.' },
957
+ { kind: 'method', name: 'getPriceCatalog', signature: 'getPriceCatalog(): Promise<PriceCatalog>', summary: '按需读取可恢复的内置价格。Read bundled prices on demand.' },
958
+ { kind: 'method', name: 'repriceHistory', signature: 'repriceHistory(confirmed: boolean): Promise<FetchPricesResult>', summary: '确认并备份后按当前价格重算历史。Recalculate history after explicit confirmation and backup.' },
959
+ { kind: 'method', name: 'repriceModelHistory', signature: 'repriceModelHistory(confirmed: boolean, model: string): Promise<FetchPricesResult>', summary: '确认并备份后只重算指定渠道模型,保留同期汇率。Recalculate one channel/model with original exchange rates.' },
960
+ {
961
+ kind: 'method', name: 'getOpenRouterCatalog', signature: 'getOpenRouterCatalog(): Promise<OpenRouterCatalog>',
962
+ summary: '只读查询公开模型价格,无需密钥。Read public model prices without credentials or config changes.',
963
+ },
964
+ {
965
+ kind: 'method',
966
+ name: 'releasePriceLock',
967
+ signature: 'releasePriceLock(id: string): Promise<FetchPricesResult>',
968
+ summary: '把手改过的 OpenRouter 价格交回自动同步。Hand a manually edited OpenRouter price back to auto-sync.',
969
+ jsDoc: '/**\n * 把手改过的 OpenRouter 价格交回自动同步。\n * @param id - OpenRouter 模型 id。\n * @returns 结果与最新快照。\n * Hand a manually edited OpenRouter price back to auto-sync.\n * @param id - The OpenRouter model id.\n * @returns The result and the latest snapshot.\n */',
970
+ },
971
+ {
972
+ kind: 'method',
973
+ name: 'refreshBalance',
974
+ signature: 'refreshBalance(): Promise<FetchPricesResult>',
975
+ summary: '立即查询官方开放平台账户余额。Query the official open-platform account balance immediately.',
976
+ jsDoc: '/**\n * 立即查询官方开放平台账户余额。\n * @returns 查询结果与最新快照。\n * Query the official open-platform account balance immediately.\n * @returns The query result and the latest snapshot.\n */',
977
+ },
978
+ {
979
+ kind: 'method',
980
+ name: 'refreshGoQuota',
981
+ signature: 'refreshGoQuota(): Promise<FetchPricesResult>',
982
+ summary: '立即查询 OpenCode Go 订阅额度。Query the OpenCode Go subscription quota immediately.',
983
+ jsDoc: '/**\n * 立即查询 OpenCode Go 订阅额度(滚动5小时/本周/本月用量百分比)。\n * @returns 查询结果与最新快照。\n * Query the OpenCode Go subscription quota immediately (rolling-5h/weekly/monthly usage percent).\n * @returns The query result and the latest snapshot.\n */',
984
+ },
985
+ {
986
+ kind: 'method',
987
+ name: 'refreshGatewayQuota',
988
+ signature: 'refreshGatewayQuota(sourceId?: string): Promise<FetchPricesResult>',
989
+ summary: '立即刷新 CLIProxyAPI gateway quota 来源。Refresh CLIProxyAPI gateway quota sources immediately.',
990
+ jsDoc: '/**\n * 立即刷新 CLIProxyAPI gateway quota 来源。\n * @param sourceId - 可选来源 ID;缺省刷新全部启用来源。\n * @returns 查询结果与最新快照。\n */',
991
+ },
992
+ {
993
+ kind: 'method',
994
+ name: 'refreshCustomBalance',
995
+ signature: 'refreshCustomBalance(index?: number): Promise<FetchPricesResult>',
996
+ summary: '立即查询自定义 Provider 余额(可指定条目)。Query custom provider balances immediately (optionally one entry).',
997
+ jsDoc: '/**\n * 立即查询自定义 Provider 余额(可配置 HTTP 请求 + extract 规则)。\n * @param index - 可选:多配置形态下要刷新的条目下标(0-7);缺省刷新全部条目。\n * @returns 查询结果与最新快照。\n * Query custom provider balances immediately (configurable HTTP request + extract rules).\n * @param index - Optional: entry index (0-7) to refresh in the multi-entry form; omit to refresh all.\n * @returns The query result and the latest snapshot.\n */',
998
+ },
999
+ {
1000
+ kind: 'method',
1001
+ name: 'refreshCodingPlan',
1002
+ signature: 'refreshCodingPlan(provider: string): Promise<FetchPricesResult>',
1003
+ summary: '立即查询指定厂商的 coding plan 额度。Query a vendor coding plan quota immediately.',
1004
+ jsDoc: '/**\n * 立即查询指定厂商(anthropic | zai | minimax | kimi | openrouter | siliconflow)的 coding plan 额度。\n * @param provider - 提供商标识。\n * @returns 查询结果与最新快照。\n * Query a vendor (anthropic | zai | minimax | kimi | openrouter | siliconflow) coding plan quota immediately.\n * @param provider - The provider id.\n * @returns The query result and the latest snapshot.\n */',
1005
+ },
1006
+ {
1007
+ kind: 'method',
1008
+ name: 'resetHistory',
1009
+ signature: 'resetHistory(): CostState',
1010
+ summary: '清空全部历史记录。Clear all history records.',
1011
+ jsDoc: '/**\n * 清空全部历史记录。\n * @returns 清空后的完整快照。\n * Clear all history records.\n * @returns The full snapshot after clearing.\n */',
1012
+ },
1013
+ {
1014
+ kind: 'method',
1015
+ name: 'getDaySessions',
1016
+ signature: 'getDaySessions(date: string): DayRecord',
1017
+ summary: '按需读取某一天的完整记录(含会话明细)。Read a day\'s full record on demand (with session details).',
1018
+ jsDoc: '/**\n * 按需读取某一天的完整记录(含会话明细;历史记录列表为轻量副本不含会话)。\n * @param date - 本地日期键 YYYY-MM-DD。\n * @returns 该日完整记录;不存在时返回零值记录。\n * Read a day\'s full record on demand (with session details; the history list is a light copy without sessions).\n * @param date - Local day key YYYY-MM-DD.\n * @returns The full day record; a zero record when absent.\n */',
1019
+ },
1020
+ {
1021
+ kind: 'method',
1022
+ name: 'getTopSessions',
1023
+ signature: 'getTopSessions(limit: number, sort?: string, dir?: string): TopSessions',
1024
+ summary: '跨全部日期按指定排序返回前 N 个会话(不分日期视角)。Return the top N sessions across all days with the given sort.',
1025
+ jsDoc: '/**\n * 跨全部日期返回前 N 个会话(每条带所属日期/标题/创建时刻)。\n * @param limit - 返回条数上限(服务端限制 1-500)。\n * @param sort - cost(费用) | time(创建时间) | recent(实时顺序)。\n * @param dir - asc | desc(默认 desc)。\n * @returns 会话列表(含 date/title/at 字段)。\n * Return the top N sessions across all days (each tagged with date/title/createdAt).\n * @param limit - Max rows to return (server clamps to 1-500).\n * @param sort - cost | time | recent (ledger/sidebar order).\n * @param dir - asc | desc (defaults to desc).\n * @returns Session list with date/title/at fields.\n */',
1026
+ },
1027
+ {
1028
+ kind: 'method',
1029
+ name: 'getTurnCost',
1030
+ signature: 'getTurnCost(sessionId: string, startSeq: number, endSeq: number): TurnCost',
1031
+ summary: '读取已完成轮次的分项用量与估算费用。Read recorded usage and estimated costs for a completed turn.',
1032
+ },
1033
+ {
1034
+ kind: 'method',
1035
+ name: 'getSessionCost',
1036
+ signature: 'getSessionCost(sessionId: string): SessionCost',
1037
+ summary: '读取本会话跨日期账本及可选的子代理费用汇总。Read a session ledger and optional descendant costs.',
1038
+ jsDoc: '/** 只读会话费用;后代合计不改变每日账本。Read-only cost summary; descendant costs never rewrite daily totals. */',
1039
+ },
1040
+ {
1041
+ kind: 'method',
1042
+ name: 'setCredential',
1043
+ signature: 'setCredential(target: CredentialTarget, value: CredentialValue): Promise<FetchPricesResult>',
1044
+ summary: '把一枚密钥写入 DSH 凭据库。Store a credential in the DSH credential store.',
1045
+ jsDoc: '/**\n * 把一枚密钥写入 DSH 凭据库(v1.6.8)。密钥不再经 updateConfig 传递:\n * config 中的密钥字段只留空占位(且不落盘),值一律存进宿主凭据库。\n * v1.7.6 新增 customVar:<NAME> 目标:自定义余额请求头 {{VAR}} 占位符的同名密钥\n * 也走这一入口写入,与模型页共享变量名即共用同一把密钥。\n * @param target - balance | goQuota | codingPlans.<id> | codingPlans.volcengine.ak | codingPlans.volcengine.sk | customVar:VAR_NAME\n * @param value - 密钥明文(非空)\n * @returns 写入结果与最新快照\n * Store a credential in the DSH credential store (v1.6.8). Credentials no longer travel\n * through updateConfig: config keeps blank placeholders only (and never persists them).\n * v1.7.6 adds the customVar:<NAME> target: keys for custom-balance header {{VAR}}\n * placeholders are stored through this same entry; sharing a variable name with the\n * Models page shares the same key.\n * @param target - balance | goQuota | codingPlans.<id> | codingPlans.volcengine.ak | codingPlans.volcengine.sk | customVar:VAR_NAME\n * @param value - The plaintext credential (non-empty)\n * @returns The write result and the latest snapshot\n */',
1046
+ },
1047
+ {
1048
+ kind: 'method',
1049
+ name: 'clearCredential',
1050
+ signature: 'clearCredential(target: CredentialTarget): Promise<FetchPricesResult>',
1051
+ summary: '从 DSH 凭据库移除一枚密钥。Remove a credential from the DSH credential store.',
1052
+ jsDoc: '/**\n * 从 DSH 凭据库移除一枚密钥(v1.6.8),并清掉 config 中可能残留的旧明文。\n * @param target - 同 setCredential\n * @returns 移除结果与最新快照\n * Remove a credential from the DSH credential store (v1.6.8), also clearing any\n * leftover plaintext in config.\n * @param target - Same as setCredential\n * @returns The removal result and the latest snapshot\n */',
1053
+ },
1054
+ ],
1055
+ types: [],
1056
+ },
1057
+ ],
1058
+ events: [],
1059
+ objects: [],
1060
+ },
1061
+ }
1062
+
1063
+ export default TYPERT