dsh-thinking-levels 4.1.0 → 4.2.0-beta.26

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.
@@ -0,0 +1,393 @@
1
+ /**
2
+ * TL cache-billing projection unit (`tlCacheBilling`).
3
+ *
4
+ * Accounting semantics ported from better-er/dsh-cache-billing (read line by
5
+ * line, see .agents/plans/tl-billing-popover): usage samples from
6
+ * assistant/chunk (type 'usage') and assistant/message (data.usage), same-step
7
+ * replacement settles old-minus-new, turn aggregation resets on turn switch,
8
+ * session totals price every sample at its own event-time rate.
9
+ *
10
+ * Pricing: single model DeepSeek-V4.1-Flash, Beijing-time peak/off-peak
11
+ * (workdays 09-12 & 14-18 peak, weekends and CN statutory holidays off-peak
12
+ * all day; pure UTC+8 math, never the local clock). Unmatched model names are
13
+ * still priced at Flash rates and flagged via modelMatched=false.
14
+ *
15
+ * Schema library: the projection framework duck-types `stateSchema.parse()` /
16
+ * `wire.viewSchema.parse()` (dsh-session-projection lib:255/259/305), so these
17
+ * MUST be real zod objects — schemastery has no parse. zod ^4.4.3 rides in
18
+ * dependencies (TL's tsc build does not bundle).
19
+ * @module dsh-thinking-levels/billing-projection
20
+ */
21
+ import { z } from 'zod';
22
+ /** 账目只认 DeepSeek-V4.1-Flash:现名、旧名与历史变体全部由 Flash 服务。 */
23
+ export const BILLING_MODEL = {
24
+ key: 'deepseek-v4.1-flash',
25
+ label: 'DeepSeek-V4.1-Flash',
26
+ aliases: [
27
+ 'deepseek-v4.1-flash',
28
+ 'deepseek-flash',
29
+ 'deepseek-v4-flash',
30
+ 'deepseek-v4-flash-vision-exp',
31
+ ],
32
+ peak: { cacheHit: 0.04, cacheMiss: 2, output: 8 },
33
+ offPeak: { cacheHit: 0.02, cacheMiss: 1, output: 4 },
34
+ };
35
+ /**
36
+ * 中国法定节假日放假日(北京时间 YYYY-MM-DD),2026 年国务院安排 33 天(holiday-cn)。
37
+ * 只收放假日不收调休补班周末;表外年份退化为只认周末。
38
+ */
39
+ export const HOLIDAYS_2026 = new Set([
40
+ '2026-01-01', '2026-01-02', '2026-01-03',
41
+ '2026-02-15', '2026-02-16', '2026-02-17', '2026-02-18', '2026-02-19',
42
+ '2026-02-20', '2026-02-21', '2026-02-22', '2026-02-23',
43
+ '2026-04-04', '2026-04-05', '2026-04-06',
44
+ '2026-05-01', '2026-05-02', '2026-05-03', '2026-05-04', '2026-05-05',
45
+ '2026-06-19', '2026-06-20', '2026-06-21',
46
+ '2026-09-25', '2026-09-26', '2026-09-27',
47
+ '2026-10-01', '2026-10-02', '2026-10-03', '2026-10-04', '2026-10-05',
48
+ '2026-10-06', '2026-10-07',
49
+ ]);
50
+ /** 时刻是否为北京高峰。UTC+8 纯数学换算;无效时间戳用 getUTC* 拼串不抛错。 */
51
+ export function isPeakBeijing(timeMs) {
52
+ const shifted = new Date(timeMs + 8 * 3600 * 1000);
53
+ const day = shifted.getUTCDay();
54
+ if (day === 0 || day === 6)
55
+ return false;
56
+ const month = String(shifted.getUTCMonth() + 1).padStart(2, '0');
57
+ const dayOfMonth = String(shifted.getUTCDate()).padStart(2, '0');
58
+ if (HOLIDAYS_2026.has(`${shifted.getUTCFullYear()}-${month}-${dayOfMonth}`))
59
+ return false;
60
+ const hour = shifted.getUTCHours();
61
+ return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18);
62
+ }
63
+ /** 模型在某时刻的费率行 + 峰谷 + 白名单命中标记。 */
64
+ export function rateOf(model, timeMs) {
65
+ const key = (model ?? '').toLowerCase();
66
+ const tier = isPeakBeijing(timeMs) ? 'peak' : 'offPeak';
67
+ const row = tier === 'peak' ? BILLING_MODEL.peak : BILLING_MODEL.offPeak;
68
+ const matched = BILLING_MODEL.aliases.some((alias) => key === alias || key.endsWith(alias) || key.includes(alias));
69
+ return { row, tier, matchedModel: BILLING_MODEL.label, matched };
70
+ }
71
+ const round9 = (n) => Math.round(n * 1e9) / 1e9;
72
+ /** 按样本模型与事件时刻计一轮三笔费用(元)。 */
73
+ export function costOf(sample) {
74
+ const { row } = rateOf(sample.model, sample.time);
75
+ return {
76
+ hit: round9((sample.cacheReadTokens * row.cacheHit) / 1e6),
77
+ miss: round9(((sample.inputTokens + sample.cacheWriteTokens) * row.cacheMiss) / 1e6),
78
+ output: round9((sample.outputTokens * row.output) / 1e6),
79
+ };
80
+ }
81
+ /** 写失效:发生过缓存写入(官方不报,恒 false,个别中转有值)。 */
82
+ export const isWriteMiss = (s) => s.cacheWriteTokens > 0;
83
+ /** 完全失效:有输入但缓存命中为 0(首轮无缓存可命中也算,近似,任何路由可靠)。 */
84
+ export const isFullMiss = (s) => s.inputTokens + s.cacheReadTokens + s.cacheWriteTokens > 0 && s.cacheReadTokens === 0;
85
+ const sampleInput = (s) => s.inputTokens + s.cacheReadTokens + s.cacheWriteTokens;
86
+ const EMPTY_TOTALS = {
87
+ cacheHitCost: 0,
88
+ missCost: 0,
89
+ outputCost: 0,
90
+ inputTokens: 0,
91
+ cacheReadTokens: 0,
92
+ outputTokens: 0,
93
+ rounds: 0,
94
+ missSteps: 0,
95
+ writeTokens: 0,
96
+ fullMissSteps: 0,
97
+ };
98
+ const sampleSchemaFields = {
99
+ inputTokens: z.number().int().nonnegative(),
100
+ cacheReadTokens: z.number().int().nonnegative(),
101
+ cacheWriteTokens: z.number().int().nonnegative(),
102
+ outputTokens: z.number().int().nonnegative(),
103
+ model: z.string().nullable(),
104
+ provider: z.string().nullable(),
105
+ time: z.number(),
106
+ };
107
+ const turnTotalsShape = {
108
+ id: z.number().int(),
109
+ hitCost: z.number().nonnegative(),
110
+ missCost: z.number().nonnegative(),
111
+ outputCost: z.number().nonnegative(),
112
+ inputTokens: z.number().int().nonnegative(),
113
+ cacheReadTokens: z.number().int().nonnegative(),
114
+ outputTokens: z.number().int().nonnegative(),
115
+ };
116
+ const totalsShape = {
117
+ cacheHitCost: z.number().nonnegative(),
118
+ missCost: z.number().nonnegative(),
119
+ outputCost: z.number().nonnegative(),
120
+ inputTokens: z.number().int().nonnegative(),
121
+ cacheReadTokens: z.number().int().nonnegative(),
122
+ outputTokens: z.number().int().nonnegative(),
123
+ rounds: z.number().int().nonnegative(),
124
+ missSteps: z.number().int().nonnegative(),
125
+ writeTokens: z.number().int().nonnegative(),
126
+ fullMissSteps: z.number().int().nonnegative(),
127
+ };
128
+ /**
129
+ * Build the `tlCacheBilling` projection definition. Registered soft-coupled
130
+ * (runtime inject — NEVER a top-level export inject, which would make the
131
+ * whole plugin 0.2.0-only): hosts without the sessionProjections service
132
+ * simply never register it, and the ring's billing section stays hidden.
133
+ */
134
+ export function buildBillingDefinition() {
135
+ const stateSchema = z.object({
136
+ provider: z.string().nullable(),
137
+ model: z.string().nullable(),
138
+ last: z.object({ turn: z.number().int(), step: z.number().int(), ...sampleSchemaFields }).nullable(),
139
+ turn: z.object(turnTotalsShape).nullable(),
140
+ totals: z.object(totalsShape),
141
+ });
142
+ const init = () => ({
143
+ provider: null,
144
+ model: null,
145
+ last: null,
146
+ turn: null,
147
+ totals: { ...EMPTY_TOTALS },
148
+ });
149
+ // Wire-format reducer: events arrive untyped off the transport mirror and
150
+ // every field access below already narrows defensively.
151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
+ const apply = (state, event) => {
153
+ // 当前请求的 provider/model 跟踪
154
+ if (event.type === 'request/header') {
155
+ const cfg = event.data?.header?.config;
156
+ const provider = typeof cfg?.provider === 'string' && cfg.provider !== '' ? cfg.provider : state.provider;
157
+ const model = typeof cfg?.model === 'string' && cfg.model !== '' ? cfg.model : state.model;
158
+ return provider !== state.provider || model !== state.model ? { ...state, provider, model } : state;
159
+ }
160
+ if (event.type === 'request/context') {
161
+ const raw = event.data?.model;
162
+ const model = typeof raw === 'string' && raw !== '' ? raw : state.model;
163
+ return model !== state.model ? { ...state, model } : state;
164
+ }
165
+ // usage 双源采样
166
+ let turn;
167
+ let step;
168
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- wire-format usage sample, normalized a few lines down
169
+ let usage;
170
+ let sourceModel;
171
+ let sourceProvider;
172
+ if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'usage') {
173
+ turn = event.data.turn;
174
+ step = event.data.step;
175
+ usage = event.data.chunk.usage;
176
+ }
177
+ else if (event.type === 'assistant/message' && event.data?.usage !== undefined) {
178
+ turn = event.data.turn;
179
+ step = event.data.step;
180
+ usage = event.data.usage;
181
+ const source = event.data.message?.source;
182
+ if (typeof source?.provider === 'string')
183
+ sourceProvider = source.provider;
184
+ if (typeof source?.model === 'string')
185
+ sourceModel = source.model;
186
+ }
187
+ else {
188
+ return state; // 无关事件:同一引用,驱动以 Object.is 把关变更流
189
+ }
190
+ if (usage === undefined || typeof turn !== 'number' || typeof step !== 'number')
191
+ return state;
192
+ const sample = {
193
+ turn,
194
+ step,
195
+ inputTokens: Number(usage.inputTokens) || 0,
196
+ cacheReadTokens: Number(usage.cacheReadTokens) || 0,
197
+ cacheWriteTokens: Number(usage.cacheWriteTokens) || 0,
198
+ outputTokens: Number(usage.outputTokens) || 0,
199
+ model: sourceModel ?? state.model,
200
+ provider: sourceProvider ?? state.provider,
201
+ time: typeof event.time === 'number' ? event.time : Date.now(),
202
+ };
203
+ const prev = state.last;
204
+ // 同 step 替换样本:数据全同则引用不变
205
+ if (prev !== null && prev.turn === turn && prev.step === step &&
206
+ prev.inputTokens === sample.inputTokens &&
207
+ prev.cacheReadTokens === sample.cacheReadTokens &&
208
+ prev.cacheWriteTokens === sample.cacheWriteTokens &&
209
+ prev.outputTokens === sample.outputTokens &&
210
+ prev.model === sample.model && prev.provider === sample.provider) {
211
+ return state;
212
+ }
213
+ const current = costOf(sample);
214
+ const writeMiss = isWriteMiss(sample);
215
+ const fullMiss = isFullMiss(sample);
216
+ const input = sampleInput(sample);
217
+ if (prev !== null && prev.turn === turn && prev.step === step) {
218
+ // 同 step 替换:扣旧加新,轮数不变
219
+ const old = costOf(prev);
220
+ const prevInput = sampleInput(prev);
221
+ const turnBase = state.turn !== null && state.turn.id === prev.turn
222
+ ? state.turn
223
+ : { id: turn, hitCost: 0, missCost: 0, outputCost: 0, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 };
224
+ return {
225
+ ...state,
226
+ last: sample,
227
+ turn: {
228
+ ...turnBase,
229
+ id: turn,
230
+ hitCost: turnBase.hitCost - old.hit + current.hit,
231
+ missCost: turnBase.missCost - old.miss + current.miss,
232
+ outputCost: turnBase.outputCost - old.output + current.output,
233
+ inputTokens: turnBase.inputTokens - prevInput + input,
234
+ cacheReadTokens: turnBase.cacheReadTokens - prev.cacheReadTokens + sample.cacheReadTokens,
235
+ outputTokens: turnBase.outputTokens - prev.outputTokens + sample.outputTokens,
236
+ },
237
+ totals: {
238
+ cacheHitCost: state.totals.cacheHitCost - old.hit + current.hit,
239
+ missCost: state.totals.missCost - old.miss + current.miss,
240
+ outputCost: state.totals.outputCost - old.output + current.output,
241
+ inputTokens: state.totals.inputTokens - prevInput + input,
242
+ cacheReadTokens: state.totals.cacheReadTokens - prev.cacheReadTokens + sample.cacheReadTokens,
243
+ outputTokens: state.totals.outputTokens - prev.outputTokens + sample.outputTokens,
244
+ rounds: state.totals.rounds,
245
+ missSteps: state.totals.missSteps - (isWriteMiss(prev) ? 1 : 0) + (writeMiss ? 1 : 0),
246
+ writeTokens: state.totals.writeTokens - prev.cacheWriteTokens + sample.cacheWriteTokens,
247
+ fullMissSteps: state.totals.fullMissSteps - (isFullMiss(prev) ? 1 : 0) + (fullMiss ? 1 : 0),
248
+ },
249
+ };
250
+ }
251
+ // 新 step:同 turn 累加 / 异 turn 重置;totals 累加、轮数+1
252
+ const sameTurn = state.turn !== null && state.turn.id === turn;
253
+ return {
254
+ ...state,
255
+ last: sample,
256
+ turn: sameTurn
257
+ ? {
258
+ ...state.turn,
259
+ hitCost: state.turn.hitCost + current.hit,
260
+ missCost: state.turn.missCost + current.miss,
261
+ outputCost: state.turn.outputCost + current.output,
262
+ inputTokens: state.turn.inputTokens + input,
263
+ cacheReadTokens: state.turn.cacheReadTokens + sample.cacheReadTokens,
264
+ outputTokens: state.turn.outputTokens + sample.outputTokens,
265
+ }
266
+ : {
267
+ id: turn,
268
+ hitCost: current.hit,
269
+ missCost: current.miss,
270
+ outputCost: current.output,
271
+ inputTokens: input,
272
+ cacheReadTokens: sample.cacheReadTokens,
273
+ outputTokens: sample.outputTokens,
274
+ },
275
+ totals: {
276
+ cacheHitCost: state.totals.cacheHitCost + current.hit,
277
+ missCost: state.totals.missCost + current.miss,
278
+ outputCost: state.totals.outputCost + current.output,
279
+ inputTokens: state.totals.inputTokens + input,
280
+ cacheReadTokens: state.totals.cacheReadTokens + sample.cacheReadTokens,
281
+ outputTokens: state.totals.outputTokens + sample.outputTokens,
282
+ rounds: state.totals.rounds + 1,
283
+ missSteps: state.totals.missSteps + (writeMiss ? 1 : 0),
284
+ writeTokens: state.totals.writeTokens + sample.cacheWriteTokens,
285
+ fullMissSteps: state.totals.fullMissSteps + (fullMiss ? 1 : 0),
286
+ },
287
+ };
288
+ };
289
+ const view = (state) => {
290
+ const s = state.last;
291
+ const t = state.totals;
292
+ if (s === null) {
293
+ return {
294
+ available: false, cost: 0, missCost: 0, outputCost: 0, currency: 'CNY',
295
+ cacheReadTokens: 0, totalInputTokens: 0, outputTokens: 0, hitRate: null,
296
+ model: state.model, provider: state.provider, matchedModel: null, modelMatched: false,
297
+ tier: null, unitPricePerM: null, turn: null, step: null,
298
+ turnCost: 0, turnHitCost: 0, turnMissCost: 0, turnOutputCost: 0,
299
+ turnTokens: 0, turnCacheReadTokens: 0, turnInputTokens: 0, turnOutputTokens: 0,
300
+ sessionCacheHitCost: t.cacheHitCost, sessionMissCost: t.missCost, sessionOutputCost: t.outputCost,
301
+ sessionInputTokens: t.inputTokens, sessionCacheReadTokens: t.cacheReadTokens,
302
+ sessionOutputTokens: t.outputTokens, sessionRounds: t.rounds, sessionMissSteps: t.missSteps,
303
+ sessionWriteTokens: t.writeTokens, sessionFullMissSteps: t.fullMissSteps,
304
+ };
305
+ }
306
+ const totalInput = sampleInput(s);
307
+ const { row, tier, matchedModel, matched } = rateOf(s.model, s.time);
308
+ const cost = round9((s.cacheReadTokens * row.cacheHit) / 1e6);
309
+ const missCost = round9(((s.inputTokens + s.cacheWriteTokens) * row.cacheMiss) / 1e6);
310
+ const outputCost = round9((s.outputTokens * row.output) / 1e6);
311
+ const turn = state.turn;
312
+ return {
313
+ available: totalInput > 0 || s.outputTokens > 0,
314
+ cost, missCost, outputCost,
315
+ currency: 'CNY',
316
+ cacheReadTokens: s.cacheReadTokens,
317
+ totalInputTokens: totalInput,
318
+ outputTokens: s.outputTokens,
319
+ hitRate: totalInput > 0 ? Math.round((s.cacheReadTokens / totalInput) * 1000) / 10 : null,
320
+ model: s.model,
321
+ provider: s.provider,
322
+ matchedModel,
323
+ modelMatched: matched,
324
+ tier,
325
+ unitPricePerM: row.cacheHit,
326
+ turn: s.turn,
327
+ step: s.step,
328
+ turnCost: turn === null ? 0 : turn.hitCost + turn.missCost + turn.outputCost,
329
+ turnHitCost: turn === null ? 0 : turn.hitCost,
330
+ turnMissCost: turn === null ? 0 : turn.missCost,
331
+ turnOutputCost: turn === null ? 0 : turn.outputCost,
332
+ turnTokens: turn === null ? 0 : turn.inputTokens + turn.outputTokens,
333
+ turnCacheReadTokens: turn === null ? 0 : turn.cacheReadTokens,
334
+ turnInputTokens: turn === null ? 0 : turn.inputTokens,
335
+ turnOutputTokens: turn === null ? 0 : turn.outputTokens,
336
+ sessionCacheHitCost: t.cacheHitCost,
337
+ sessionMissCost: t.missCost,
338
+ sessionOutputCost: t.outputCost,
339
+ sessionInputTokens: t.inputTokens,
340
+ sessionCacheReadTokens: t.cacheReadTokens,
341
+ sessionOutputTokens: t.outputTokens,
342
+ sessionRounds: t.rounds,
343
+ sessionMissSteps: t.missSteps,
344
+ sessionWriteTokens: t.writeTokens,
345
+ sessionFullMissSteps: t.fullMissSteps,
346
+ };
347
+ };
348
+ const viewSchema = z.object({
349
+ available: z.boolean(),
350
+ cost: z.number().nonnegative(),
351
+ missCost: z.number().nonnegative(),
352
+ outputCost: z.number().nonnegative(),
353
+ currency: z.literal('CNY'),
354
+ cacheReadTokens: z.number().int().nonnegative(),
355
+ totalInputTokens: z.number().int().nonnegative(),
356
+ outputTokens: z.number().int().nonnegative(),
357
+ hitRate: z.number().nullable(),
358
+ model: z.string().nullable(),
359
+ provider: z.string().nullable(),
360
+ matchedModel: z.string().nullable(),
361
+ modelMatched: z.boolean(),
362
+ tier: z.enum(['peak', 'offPeak']).nullable(),
363
+ unitPricePerM: z.number().nullable(),
364
+ turn: z.number().int().nullable(),
365
+ step: z.number().int().nullable(),
366
+ turnCost: z.number().nonnegative(),
367
+ turnHitCost: z.number().nonnegative(),
368
+ turnMissCost: z.number().nonnegative(),
369
+ turnOutputCost: z.number().nonnegative(),
370
+ turnTokens: z.number().int().nonnegative(),
371
+ turnCacheReadTokens: z.number().int().nonnegative(),
372
+ turnInputTokens: z.number().int().nonnegative(),
373
+ turnOutputTokens: z.number().int().nonnegative(),
374
+ sessionCacheHitCost: z.number().nonnegative(),
375
+ sessionMissCost: z.number().nonnegative(),
376
+ sessionOutputCost: z.number().nonnegative(),
377
+ sessionInputTokens: z.number().int().nonnegative(),
378
+ sessionCacheReadTokens: z.number().int().nonnegative(),
379
+ sessionOutputTokens: z.number().int().nonnegative(),
380
+ sessionRounds: z.number().int().nonnegative(),
381
+ sessionMissSteps: z.number().int().nonnegative(),
382
+ sessionWriteTokens: z.number().int().nonnegative(),
383
+ sessionFullMissSteps: z.number().int().nonnegative(),
384
+ });
385
+ return {
386
+ key: 'tlCacheBilling',
387
+ stateVersion: 1,
388
+ stateSchema,
389
+ init,
390
+ apply,
391
+ wire: { viewSchema, view },
392
+ };
393
+ }