dsh-context-compression-improved 0.8.0-beta.1 → 0.8.0-beta.3
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.
- package/CHANGELOG.de.md +539 -0
- package/CHANGELOG.es.md +547 -0
- package/CHANGELOG.fr.md +534 -0
- package/CHANGELOG.it.md +536 -0
- package/CHANGELOG.md +15 -0
- package/CHANGELOG.ru.md +517 -0
- package/README.de.md +98 -0
- package/README.es.md +98 -0
- package/README.fr.md +98 -0
- package/README.it.md +98 -0
- package/README.ja.md +1 -1
- package/README.ko.md +1 -1
- package/README.md +1 -1
- package/README.ru.md +98 -0
- package/README.zh.md +1 -1
- package/docs/installation.de.md +104 -0
- package/docs/installation.es.md +104 -0
- package/docs/installation.fr.md +104 -0
- package/docs/installation.it.md +104 -0
- package/docs/installation.ja.md +78 -78
- package/docs/installation.ko.md +78 -78
- package/docs/installation.md +103 -103
- package/docs/installation.ru.md +104 -0
- package/docs/installation.zh.md +100 -100
- package/package.json +17 -16
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/advisor-state.js +503 -1
- package/packages/selector/lib/client.d.ts +14 -0
- package/packages/selector/lib/client.js +1053 -3
- package/packages/selector/lib/index.js +122 -2
- package/packages/selector/lib/pruner.js +87 -258
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/index.ts +244 -213
- package/packages/selector/src/client/locales/de.ts +113 -0
- package/packages/selector/src/client/locales/es.ts +113 -0
- package/packages/selector/src/client/locales/fr.ts +113 -0
- package/packages/selector/src/client/locales/it.ts +113 -0
- package/packages/selector/src/client/locales/ja.ts +113 -0
- package/packages/selector/src/client/locales/ko.ts +113 -0
- package/packages/selector/src/client/locales/ru.ts +113 -0
- package/packages/selector/src/client/locales.ts +226 -196
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +126 -124
- package/packages/selector/src/index.ts +547 -411
- package/packages/selector/src/pruner.ts +2505 -2421
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/tests/TEST_INVENTORY.md +41 -41
|
@@ -1,4 +1,506 @@
|
|
|
1
1
|
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
//#region src/runtime/savings.ts
|
|
4
|
+
/**
|
|
5
|
+
* 节省统计账本(诚实口径)。
|
|
6
|
+
*
|
|
7
|
+
* 原则(与 dsh-token-optimizer 类功能对齐的需求口径):
|
|
8
|
+
* 1. **只记已实现**:抵扣来自真实落盘的 rewrite(published replacement)的
|
|
9
|
+
* tokensBefore − tokensAfter,不按"本可以压多少"的最大值计;
|
|
10
|
+
* 2. **负节省(配对抵消)**:同一份原文先被压缩(代码骨架/历史老化/去重指针/
|
|
11
|
+
* 尾裁引用)后,模型又请求了全文——原声称的节省被抵消:全文读取本身
|
|
12
|
+
* 记为负项。净额因此可以为负(骨架 S + 全文 O,对比从未压缩的基线 O,
|
|
13
|
+
* 净 −S),这正是"先骨架再全文 = 负节省"的诚实口径;
|
|
14
|
+
* 3. **口径分列,不混算**:精确 tokenizer 与 chars/4 估算两个 basis 各自独立
|
|
15
|
+
* 汇总,永不合并成一个数。
|
|
16
|
+
*
|
|
17
|
+
* 存储:进程内 per-session 账本(条目环形缓冲 + hash 注册表)。不落盘——
|
|
18
|
+
* 节省统计是运行期面板数据,重启归零是可接受语义(审计日志里已有全量原始记录)。
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-context-compression-improved/runtime/savings
|
|
21
|
+
*/
|
|
22
|
+
const MAX_ENTRIES_PER_SESSION = 400;
|
|
23
|
+
const MAX_REGISTRY = 2048;
|
|
24
|
+
var SavingsLedger = class {
|
|
25
|
+
entries = /* @__PURE__ */ new Map();
|
|
26
|
+
registry = /* @__PURE__ */ new Map();
|
|
27
|
+
seenFullText = /* @__PURE__ */ new Set();
|
|
28
|
+
usage = /* @__PURE__ */ new Map();
|
|
29
|
+
startedAt = Date.now();
|
|
30
|
+
/**
|
|
31
|
+
* 累计一次官方 usage(request-boundary 读取上一已完成请求;末次请求在
|
|
32
|
+
* dispose 汇总前未入账属可接受低估)。usage 字段缺省按 0 计。
|
|
33
|
+
*/
|
|
34
|
+
recordUsage(sessionId, usage) {
|
|
35
|
+
let total = this.usage.get(sessionId);
|
|
36
|
+
if (total === void 0) {
|
|
37
|
+
total = {
|
|
38
|
+
requests: 0,
|
|
39
|
+
inputTokens: 0,
|
|
40
|
+
outputTokens: 0,
|
|
41
|
+
cacheReadTokens: 0,
|
|
42
|
+
cacheWriteTokens: 0
|
|
43
|
+
};
|
|
44
|
+
this.usage.set(sessionId, total);
|
|
45
|
+
}
|
|
46
|
+
total.requests += 1;
|
|
47
|
+
total.inputTokens += positiveOrZero(usage.inputTokens);
|
|
48
|
+
total.outputTokens += positiveOrZero(usage.outputTokens);
|
|
49
|
+
total.cacheReadTokens += positiveOrZero(usage.cacheReadTokens);
|
|
50
|
+
total.cacheWriteTokens += positiveOrZero(usage.cacheWriteTokens);
|
|
51
|
+
}
|
|
52
|
+
totalsFor(scope) {
|
|
53
|
+
const sum = {
|
|
54
|
+
requests: 0,
|
|
55
|
+
inputTokens: 0,
|
|
56
|
+
outputTokens: 0,
|
|
57
|
+
cacheReadTokens: 0,
|
|
58
|
+
cacheWriteTokens: 0
|
|
59
|
+
};
|
|
60
|
+
for (const sid of scope) {
|
|
61
|
+
const t = this.usage.get(sid);
|
|
62
|
+
if (t === void 0) continue;
|
|
63
|
+
sum.requests += t.requests;
|
|
64
|
+
sum.inputTokens += t.inputTokens;
|
|
65
|
+
sum.outputTokens += t.outputTokens;
|
|
66
|
+
sum.cacheReadTokens += t.cacheReadTokens;
|
|
67
|
+
sum.cacheWriteTokens += t.cacheWriteTokens;
|
|
68
|
+
}
|
|
69
|
+
return sum;
|
|
70
|
+
}
|
|
71
|
+
/** 单行会话汇总(session/disposed 日志用)。 */
|
|
72
|
+
sessionSummaryLine(sessionId) {
|
|
73
|
+
const snap = this.snapshot(sessionId);
|
|
74
|
+
const hit = snap.usage.cacheHitRate;
|
|
75
|
+
return `net=${snap.net.exact}(exact)/${snap.net.estimated}(est) gross=${snap.gross.exact}/${snap.gross.estimated} offsets=${snap.offsets.exact}/${snap.offsets.estimated} requests=${snap.usage.requests} cacheHit=${hit === null ? "–" : `${Math.round(hit * 100)}%`}`;
|
|
76
|
+
}
|
|
77
|
+
/** 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。 */
|
|
78
|
+
recordSaving(input) {
|
|
79
|
+
const removed = input.tokensBefore - input.tokensAfter;
|
|
80
|
+
if (!Number.isFinite(removed) || removed <= 0) return;
|
|
81
|
+
this.push(input.sessionId, {
|
|
82
|
+
kind: "saving",
|
|
83
|
+
component: input.component,
|
|
84
|
+
tokens: removed,
|
|
85
|
+
basis: input.basis,
|
|
86
|
+
at: Date.now()
|
|
87
|
+
});
|
|
88
|
+
if (typeof input.originalText === "string" && input.originalText.length > 0) {
|
|
89
|
+
const hash = savingsHash(input.originalText);
|
|
90
|
+
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(hash)) {
|
|
91
|
+
const oldest = this.registry.keys().next().value;
|
|
92
|
+
if (oldest !== void 0) this.registry.delete(oldest);
|
|
93
|
+
}
|
|
94
|
+
this.registry.set(hash, {
|
|
95
|
+
sessionId: input.sessionId,
|
|
96
|
+
component: input.component,
|
|
97
|
+
claimedTokens: removed,
|
|
98
|
+
basis: input.basis,
|
|
99
|
+
sourceSeq: input.sourceSeq,
|
|
100
|
+
consumed: false
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* 新的全文工具结果进入上下文(每个 (session, seq) 只看一次):若其原文哈希
|
|
106
|
+
* 命中之前压缩过的条目且未消费过抵消 → 记负项并消费。
|
|
107
|
+
* @param measure 返回 {tokens, basis}——全文按当前可用口径计量。
|
|
108
|
+
*/
|
|
109
|
+
noteFullText(input) {
|
|
110
|
+
if (typeof input.text !== "string" || input.text.length === 0) return;
|
|
111
|
+
const seenKey = `${input.sessionId}:${input.seq}`;
|
|
112
|
+
if (this.seenFullText.has(seenKey)) return;
|
|
113
|
+
this.seenFullText.add(seenKey);
|
|
114
|
+
if (this.seenFullText.size > MAX_REGISTRY * 4) {
|
|
115
|
+
this.seenFullText.clear();
|
|
116
|
+
this.seenFullText.add(seenKey);
|
|
117
|
+
}
|
|
118
|
+
const hit = this.registry.get(savingsHash(input.text));
|
|
119
|
+
if (hit === void 0 || hit.consumed || hit.sessionId !== input.sessionId) return;
|
|
120
|
+
hit.consumed = true;
|
|
121
|
+
const { tokens, basis } = input.measure(input.text);
|
|
122
|
+
if (tokens <= 0) return;
|
|
123
|
+
this.push(input.sessionId, {
|
|
124
|
+
kind: "offset",
|
|
125
|
+
component: "full-read",
|
|
126
|
+
tokens,
|
|
127
|
+
basis,
|
|
128
|
+
at: Date.now(),
|
|
129
|
+
note: `#${hit.sourceSeq} ${hit.component} 的原文被全文重读(原声称 −${hit.claimedTokens})`
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** retrieve 回读(部分或全部)重新进入上下文:按返回内容计量记负项。 */
|
|
133
|
+
recordOffset(input) {
|
|
134
|
+
if (!Number.isFinite(input.tokens) || input.tokens <= 0) return;
|
|
135
|
+
this.push(input.sessionId, {
|
|
136
|
+
kind: "offset",
|
|
137
|
+
component: input.component,
|
|
138
|
+
tokens: input.tokens,
|
|
139
|
+
basis: input.basis,
|
|
140
|
+
at: Date.now(),
|
|
141
|
+
...input.note === void 0 ? {} : { note: input.note }
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
sourceSeqOf(item) {
|
|
145
|
+
return item.sourceSeq;
|
|
146
|
+
}
|
|
147
|
+
push(sessionId, entry) {
|
|
148
|
+
let list = this.entries.get(sessionId);
|
|
149
|
+
if (list === void 0) {
|
|
150
|
+
list = [];
|
|
151
|
+
this.entries.set(sessionId, list);
|
|
152
|
+
}
|
|
153
|
+
list.push(entry);
|
|
154
|
+
if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION);
|
|
155
|
+
}
|
|
156
|
+
/** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
|
|
157
|
+
snapshot(sessionId) {
|
|
158
|
+
const scope = sessionId === void 0 ? [...this.entries.keys()] : [sessionId];
|
|
159
|
+
const totals = {
|
|
160
|
+
grossExact: 0,
|
|
161
|
+
grossEstimated: 0,
|
|
162
|
+
offsetExact: 0,
|
|
163
|
+
offsetEstimated: 0
|
|
164
|
+
};
|
|
165
|
+
const perComponent = /* @__PURE__ */ new Map();
|
|
166
|
+
const recentOffsets = [];
|
|
167
|
+
for (const sid of scope) for (const entry of this.entries.get(sid) ?? []) {
|
|
168
|
+
const exact = entry.basis === "exact-tokenizer";
|
|
169
|
+
if (entry.kind === "saving") {
|
|
170
|
+
if (exact) totals.grossExact += entry.tokens;
|
|
171
|
+
else totals.grossEstimated += entry.tokens;
|
|
172
|
+
} else {
|
|
173
|
+
if (exact) totals.offsetExact += entry.tokens;
|
|
174
|
+
else totals.offsetEstimated += entry.tokens;
|
|
175
|
+
recentOffsets.push(entry);
|
|
176
|
+
}
|
|
177
|
+
const key = `${entry.kind}:${entry.component}:${entry.basis}`;
|
|
178
|
+
const agg = perComponent.get(key);
|
|
179
|
+
if (agg === void 0) perComponent.set(key, {
|
|
180
|
+
component: entry.component,
|
|
181
|
+
tokens: entry.tokens,
|
|
182
|
+
basis: entry.basis,
|
|
183
|
+
kind: entry.kind
|
|
184
|
+
});
|
|
185
|
+
else agg.tokens += entry.tokens;
|
|
186
|
+
}
|
|
187
|
+
recentOffsets.sort((a, b) => b.at - a.at);
|
|
188
|
+
const usageTotals = this.totalsFor(scope);
|
|
189
|
+
const perSession = sessionId === void 0 ? [.../* @__PURE__ */ new Set([...this.entries.keys(), ...this.usage.keys()])].map((sid) => {
|
|
190
|
+
const s = this.snapshot(sid);
|
|
191
|
+
return {
|
|
192
|
+
sessionId: sid,
|
|
193
|
+
gross: s.gross,
|
|
194
|
+
offsets: s.offsets,
|
|
195
|
+
net: s.net,
|
|
196
|
+
requests: s.usage.requests,
|
|
197
|
+
cacheHitRate: s.usage.cacheHitRate
|
|
198
|
+
};
|
|
199
|
+
}).sort((a, b) => b.net.exact - a.net.exact || b.net.estimated - a.net.estimated).slice(0, 8) : [];
|
|
200
|
+
return {
|
|
201
|
+
startedAt: new Date(this.startedAt).toISOString(),
|
|
202
|
+
sessions: sessionId === void 0 ? this.entries.size : this.entries.has(sessionId) ? 1 : 0,
|
|
203
|
+
gross: {
|
|
204
|
+
exact: totals.grossExact,
|
|
205
|
+
estimated: totals.grossEstimated
|
|
206
|
+
},
|
|
207
|
+
offsets: {
|
|
208
|
+
exact: totals.offsetExact,
|
|
209
|
+
estimated: totals.offsetEstimated
|
|
210
|
+
},
|
|
211
|
+
net: {
|
|
212
|
+
exact: totals.grossExact - totals.offsetExact,
|
|
213
|
+
estimated: totals.grossEstimated - totals.offsetEstimated
|
|
214
|
+
},
|
|
215
|
+
perComponent: [...perComponent.values()].sort((a, b) => b.tokens - a.tokens),
|
|
216
|
+
recentOffsets: recentOffsets.slice(0, 8).map((e) => ({
|
|
217
|
+
component: e.component,
|
|
218
|
+
tokens: e.tokens,
|
|
219
|
+
basis: e.basis,
|
|
220
|
+
at: new Date(e.at).toISOString(),
|
|
221
|
+
...e.note === void 0 ? {} : { note: e.note }
|
|
222
|
+
})),
|
|
223
|
+
usage: {
|
|
224
|
+
...usageTotals,
|
|
225
|
+
cacheHitRate: cacheHitRateOf(usageTotals)
|
|
226
|
+
},
|
|
227
|
+
perSession
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** 测试与停机清理。 */
|
|
231
|
+
clear() {
|
|
232
|
+
this.entries.clear();
|
|
233
|
+
this.registry.clear();
|
|
234
|
+
this.seenFullText.clear();
|
|
235
|
+
this.usage.clear();
|
|
236
|
+
this.startedAt = Date.now();
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
function cacheHitRateOf(t) {
|
|
240
|
+
const denom = t.inputTokens + t.cacheReadTokens + t.cacheWriteTokens;
|
|
241
|
+
return denom <= 0 ? null : Math.round(t.cacheReadTokens / denom * 1e3) / 1e3;
|
|
242
|
+
}
|
|
243
|
+
/** 原文配对哈希(规整行尾与首尾空白——同一文件两次读取的 innocuous 差异不配错)。 */
|
|
244
|
+
function savingsHash(text) {
|
|
245
|
+
return createHash("sha256").update(text.replace(/\r\n?/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/(^\s+)|(\s+$)/g, ""), "utf8").digest("hex");
|
|
246
|
+
}
|
|
247
|
+
function positiveOrZero(v) {
|
|
248
|
+
return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : 0;
|
|
249
|
+
}
|
|
250
|
+
const singleton = new SavingsLedger();
|
|
251
|
+
/** 模块级单例:pruner 与 retrieve 分处两文件,共享同一本账。 */
|
|
252
|
+
function getSavingsLedger() {
|
|
253
|
+
return singleton;
|
|
254
|
+
}
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region src/runtime/deepseek-official-pricing.ts
|
|
257
|
+
/** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
|
|
258
|
+
const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
|
|
259
|
+
/** Wall-clock time at which the checked-in official price pages were verified. */
|
|
260
|
+
const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
|
|
261
|
+
const PRICES = Object.freeze({
|
|
262
|
+
"deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
|
|
263
|
+
"0.007",
|
|
264
|
+
"0.22",
|
|
265
|
+
"0.66"
|
|
266
|
+
], [
|
|
267
|
+
"0.014",
|
|
268
|
+
"0.44",
|
|
269
|
+
"1.32"
|
|
270
|
+
], [
|
|
271
|
+
"0.05",
|
|
272
|
+
"1.5",
|
|
273
|
+
"4.5"
|
|
274
|
+
], [
|
|
275
|
+
"0.10",
|
|
276
|
+
"3.0",
|
|
277
|
+
"9.0"
|
|
278
|
+
]),
|
|
279
|
+
"deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
|
|
280
|
+
"0.022",
|
|
281
|
+
"0.66",
|
|
282
|
+
"1.98"
|
|
283
|
+
], [
|
|
284
|
+
"0.044",
|
|
285
|
+
"1.32",
|
|
286
|
+
"3.96"
|
|
287
|
+
], [
|
|
288
|
+
"0.15",
|
|
289
|
+
"4.5",
|
|
290
|
+
"13.5"
|
|
291
|
+
], [
|
|
292
|
+
"0.30",
|
|
293
|
+
"9.0",
|
|
294
|
+
"27.0"
|
|
295
|
+
]),
|
|
296
|
+
"deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
|
|
297
|
+
"0.007",
|
|
298
|
+
"0.22",
|
|
299
|
+
"0.66"
|
|
300
|
+
], [
|
|
301
|
+
"0.014",
|
|
302
|
+
"0.44",
|
|
303
|
+
"1.32"
|
|
304
|
+
], [
|
|
305
|
+
"0.05",
|
|
306
|
+
"1.5",
|
|
307
|
+
"4.5"
|
|
308
|
+
], [
|
|
309
|
+
"0.10",
|
|
310
|
+
"3.0",
|
|
311
|
+
"9.0"
|
|
312
|
+
])
|
|
313
|
+
});
|
|
314
|
+
const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
|
|
315
|
+
const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
|
|
316
|
+
const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
|
|
317
|
+
/**
|
|
318
|
+
* Resolve one immutable official price record; aliases and compatible gateways fail closed.
|
|
319
|
+
* @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
|
|
320
|
+
* @returns An immutable price record or an explicit unpriced reason.
|
|
321
|
+
*/
|
|
322
|
+
function resolveOfficialDeepSeekPrice(input) {
|
|
323
|
+
if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
|
|
324
|
+
if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
|
|
325
|
+
if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
|
|
326
|
+
if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
|
|
327
|
+
if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
|
|
328
|
+
const band = priceBandAt(input.at);
|
|
329
|
+
if (band === void 0) return unpriced("invalid price timestamp");
|
|
330
|
+
const model = PRICES[input.modelId];
|
|
331
|
+
const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
|
|
332
|
+
return {
|
|
333
|
+
kind: "priced",
|
|
334
|
+
record: Object.freeze({
|
|
335
|
+
catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
|
|
336
|
+
checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
|
|
337
|
+
provider: "deepseek-official",
|
|
338
|
+
baseUrlClass: "official-public",
|
|
339
|
+
apiRoute: input.apiRoute,
|
|
340
|
+
modelId: input.modelId,
|
|
341
|
+
modelVersion: model.version,
|
|
342
|
+
currency: input.currency,
|
|
343
|
+
unitTokens: 1e6,
|
|
344
|
+
band,
|
|
345
|
+
inputCacheHit,
|
|
346
|
+
inputCacheMiss,
|
|
347
|
+
output,
|
|
348
|
+
sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
|
|
349
|
+
sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
|
|
350
|
+
peakRule: PEAK_RULE
|
|
351
|
+
})
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Classify a timestamp under the published Beijing peak schedule.
|
|
356
|
+
* @param at - absolute request time to interpret in Asia/Shanghai.
|
|
357
|
+
* @returns Peak/off-peak, or undefined for an invalid timestamp.
|
|
358
|
+
*/
|
|
359
|
+
function priceBandAt(at) {
|
|
360
|
+
if (!Number.isFinite(at.getTime())) return void 0;
|
|
361
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
362
|
+
timeZone: "Asia/Shanghai",
|
|
363
|
+
weekday: "short",
|
|
364
|
+
hour: "2-digit",
|
|
365
|
+
minute: "2-digit",
|
|
366
|
+
second: "2-digit",
|
|
367
|
+
hourCycle: "h23"
|
|
368
|
+
}).formatToParts(at);
|
|
369
|
+
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
|
370
|
+
const weekday = values.weekday;
|
|
371
|
+
const hour = Number(values.hour);
|
|
372
|
+
const minute = Number(values.minute);
|
|
373
|
+
const second = Number(values.second);
|
|
374
|
+
if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
|
|
375
|
+
const workday = weekday !== "Sat" && weekday !== "Sun";
|
|
376
|
+
const seconds = hour * 3600 + minute * 60 + second;
|
|
377
|
+
return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Price one completed request, returning a range when it spans a published band boundary.
|
|
381
|
+
* @param input - exact applicability, request interval, and complete disjoint usage buckets.
|
|
382
|
+
* @returns Fixed-point exact/range cost or an explicit unpriced reason.
|
|
383
|
+
*/
|
|
384
|
+
function priceOfficialDeepSeekUsage(input) {
|
|
385
|
+
for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
|
|
386
|
+
if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
|
|
387
|
+
const start = resolveOfficialDeepSeekPrice({
|
|
388
|
+
...input,
|
|
389
|
+
at: input.startedAt
|
|
390
|
+
});
|
|
391
|
+
if (start.kind === "unpriced") return start;
|
|
392
|
+
const end = resolveOfficialDeepSeekPrice({
|
|
393
|
+
...input,
|
|
394
|
+
at: input.completedAt
|
|
395
|
+
});
|
|
396
|
+
if (end.kind === "unpriced") return end;
|
|
397
|
+
const startAmount = amountFor(start.record, input.usage);
|
|
398
|
+
if (startAmount === void 0) return unpriced("invalid decimal price record");
|
|
399
|
+
const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
|
|
400
|
+
if (start.record.band === end.record.band && !crossesBoundary) return {
|
|
401
|
+
kind: "exact",
|
|
402
|
+
currency: start.record.currency,
|
|
403
|
+
band: start.record.band,
|
|
404
|
+
...startAmount
|
|
405
|
+
};
|
|
406
|
+
const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
|
|
407
|
+
const endAmount = amountFor(comparisonRecord, input.usage);
|
|
408
|
+
if (endAmount === void 0) return unpriced("invalid decimal price record");
|
|
409
|
+
const startFemto = BigInt(startAmount.femtoUnits);
|
|
410
|
+
const endFemto = BigInt(endAmount.femtoUnits);
|
|
411
|
+
return {
|
|
412
|
+
kind: "range",
|
|
413
|
+
currency: start.record.currency,
|
|
414
|
+
bands: [start.record.band, comparisonRecord.band],
|
|
415
|
+
minimum: startFemto <= endFemto ? startAmount : endAmount,
|
|
416
|
+
maximum: startFemto <= endFemto ? endAmount : startAmount
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
/** Detect any published UTC band boundary, even when both endpoints share a band. */
|
|
420
|
+
function spansPublishedPriceBoundary(startedAt, completedAt) {
|
|
421
|
+
const start = startedAt.getTime();
|
|
422
|
+
const end = completedAt.getTime();
|
|
423
|
+
if (end <= start) return false;
|
|
424
|
+
const dayMs = 864e5;
|
|
425
|
+
if (end - start >= 7 * dayMs) return true;
|
|
426
|
+
const firstDay = Math.floor(start / dayMs) * dayMs;
|
|
427
|
+
for (let day = firstDay; day <= end; day += dayMs) {
|
|
428
|
+
const weekday = new Date(day).getUTCDay();
|
|
429
|
+
if (weekday === 0 || weekday === 6) continue;
|
|
430
|
+
for (const hour of [
|
|
431
|
+
1,
|
|
432
|
+
4,
|
|
433
|
+
6,
|
|
434
|
+
10
|
|
435
|
+
]) {
|
|
436
|
+
const boundary = day + hour * 60 * 60 * 1e3;
|
|
437
|
+
if (boundary > start && boundary <= end) return true;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
function priceRecordInBand(record, band) {
|
|
443
|
+
const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
|
|
444
|
+
return Object.freeze({
|
|
445
|
+
...record,
|
|
446
|
+
band,
|
|
447
|
+
inputCacheHit,
|
|
448
|
+
inputCacheMiss,
|
|
449
|
+
output
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
|
|
454
|
+
* @param value - canonical non-negative decimal with at most nine fractional digits.
|
|
455
|
+
* @returns Integer nano-units, or undefined when the decimal is invalid.
|
|
456
|
+
*/
|
|
457
|
+
function decimalRateNanoUnits(value) {
|
|
458
|
+
const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
|
|
459
|
+
if (match === null) return void 0;
|
|
460
|
+
const whole = match[1] ?? "0";
|
|
461
|
+
const fraction = (match[2] ?? "").padEnd(9, "0");
|
|
462
|
+
return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
|
|
463
|
+
}
|
|
464
|
+
function amountFor(record, usage) {
|
|
465
|
+
const hit = decimalRateNanoUnits(record.inputCacheHit);
|
|
466
|
+
const miss = decimalRateNanoUnits(record.inputCacheMiss);
|
|
467
|
+
const output = decimalRateNanoUnits(record.output);
|
|
468
|
+
if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
|
|
469
|
+
const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
|
|
470
|
+
return {
|
|
471
|
+
femtoUnits: femtoUnits.toString(),
|
|
472
|
+
decimal: formatFemto(femtoUnits)
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
function formatFemto(value) {
|
|
476
|
+
const digits = value.toString().padStart(16, "0");
|
|
477
|
+
const whole = digits.slice(0, -15);
|
|
478
|
+
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
479
|
+
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
480
|
+
}
|
|
481
|
+
function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
|
|
482
|
+
return Object.freeze({
|
|
483
|
+
version,
|
|
484
|
+
USD: Object.freeze({
|
|
485
|
+
"off-peak": usdOffPeak,
|
|
486
|
+
peak: usdPeak
|
|
487
|
+
}),
|
|
488
|
+
CNY: Object.freeze({
|
|
489
|
+
"off-peak": cnyOffPeak,
|
|
490
|
+
peak: cnyPeak
|
|
491
|
+
})
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
function isOfficialModel(value) {
|
|
495
|
+
return Object.prototype.hasOwnProperty.call(PRICES, value);
|
|
496
|
+
}
|
|
497
|
+
function unpriced(reason) {
|
|
498
|
+
return {
|
|
499
|
+
kind: "unpriced",
|
|
500
|
+
reason
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
//#endregion
|
|
2
504
|
//#region src/runtime/types.ts
|
|
3
505
|
/** User-facing mixed strategy profile. */
|
|
4
506
|
const COMPRESSION_PROFILES = [
|
|
@@ -959,4 +1461,4 @@ function invalidateOnTaskChange(state, todoVersion) {
|
|
|
959
1461
|
return true;
|
|
960
1462
|
}
|
|
961
1463
|
//#endregion
|
|
962
|
-
export { deepFreeze as C, assertNever as S, resolveConfig as _, AUTO_COMPACT_THRESHOLD_LIMITS as a, DEFAULT_CUSTOM_COMPRESSION_POLICY as b, DEFAULTS as c, charsForTokens as d, charsToTokens as f, parseContextCompressionSettings as g, isValidAutoCompactThresholdPercent as h, recordScore as i, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as l, isCompressionProfile as m, invalidateOnTaskChange as n, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as o, codePointLength as p, recordRecertified as r, ContextCompressionSettingsSchema as s, getAdvisorState as t, PRUNE_MARKER as u, resolvePolicy as v, COMPRESSION_PROFILES as w, resolveCustomPolicy as x, CustomCompressionPolicySchema as y };
|
|
1464
|
+
export { deepFreeze as C, priceOfficialDeepSeekUsage as D, decimalRateNanoUnits as E, resolveOfficialDeepSeekPrice as O, assertNever as S, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as T, resolveConfig as _, AUTO_COMPACT_THRESHOLD_LIMITS as a, DEFAULT_CUSTOM_COMPRESSION_POLICY as b, DEFAULTS as c, charsForTokens as d, charsToTokens as f, parseContextCompressionSettings as g, isValidAutoCompactThresholdPercent as h, recordScore as i, getSavingsLedger as k, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as l, isCompressionProfile as m, invalidateOnTaskChange as n, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as o, codePointLength as p, recordRecertified as r, ContextCompressionSettingsSchema as s, getAdvisorState as t, PRUNE_MARKER as u, resolvePolicy as v, COMPRESSION_PROFILES as w, resolveCustomPolicy as x, CustomCompressionPolicySchema as y };
|
|
@@ -102,6 +102,20 @@ declare const zh: {
|
|
|
102
102
|
'custom.save': string;
|
|
103
103
|
'custom.reset': string;
|
|
104
104
|
'custom.invalid': string;
|
|
105
|
+
'savings.title': string;
|
|
106
|
+
'savings.netExact': string;
|
|
107
|
+
'savings.netEstimated': string;
|
|
108
|
+
'savings.gross': string;
|
|
109
|
+
'savings.offsets': string;
|
|
110
|
+
'savings.empty': string;
|
|
111
|
+
'savings.basisExact': string;
|
|
112
|
+
'savings.basisEstimated': string;
|
|
113
|
+
'savings.basisNote': string;
|
|
114
|
+
'savings.requests': string;
|
|
115
|
+
'savings.cacheHit': string;
|
|
116
|
+
'savings.actualCost': string;
|
|
117
|
+
'savings.savedMoney': string;
|
|
118
|
+
'savings.perSession': string;
|
|
105
119
|
};
|
|
106
120
|
/** Locale keys that every context-compression selector dictionary must provide. */
|
|
107
121
|
type ContextCompressionLocaleKey = keyof typeof zh;
|