dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0
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/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.ja.md +217 -220
- package/CHANGELOG.ko.md +211 -214
- package/CHANGELOG.md +401 -376
- package/CHANGELOG.zh.md +196 -199
- package/README.md +97 -97
- package/README.zh.md +86 -86
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +44 -0
- package/packages/selector/lib/client.js +1733 -6
- package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +204 -3
- package/packages/selector/lib/profiles.d.ts +6 -0
- package/packages/selector/lib/pruner.d.ts +6 -0
- package/packages/selector/lib/pruner.js +90 -258
- package/packages/selector/lib/style.css +88 -46
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
- package/packages/selector/src/client/decode.ts +57 -53
- package/packages/selector/src/client/index.ts +307 -213
- package/packages/selector/src/client/locales/de.ts +141 -0
- package/packages/selector/src/client/locales/es.ts +141 -0
- package/packages/selector/src/client/locales/fr.ts +141 -0
- package/packages/selector/src/client/locales/it.ts +141 -0
- package/packages/selector/src/client/locales/ja.ts +141 -0
- package/packages/selector/src/client/locales/ko.ts +141 -0
- package/packages/selector/src/client/locales/ru.ts +141 -0
- package/packages/selector/src/client/locales.ts +282 -196
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +140 -124
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
- package/packages/selector/src/index.ts +207 -5
- package/packages/selector/src/preset-overlay.ts +629 -629
- package/packages/selector/src/profiles.ts +431 -414
- package/packages/selector/src/pruner/content.ts +198 -198
- package/packages/selector/src/pruner/state.ts +57 -57
- package/packages/selector/src/pruner.ts +2759 -2665
- package/packages/selector/src/runtime/audit.ts +303 -303
- package/packages/selector/src/runtime/config.ts +756 -731
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/reducers.ts +1674 -1674
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/summary-command.ts +133 -133
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
- package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
- package/packages/selector/src/runtime/types.ts +365 -358
- package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
- package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
- package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
- package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
- package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
- package/scripts/packed-components-smoke.mjs +734 -734
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +1 -1
- package/tests/TEST_INVENTORY.md +41 -41
- package/tsconfig.tests.json +17 -17
- package/vitest.config.ts +57 -57
|
@@ -1,4 +1,783 @@
|
|
|
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
|
+
const advisorStates = /* @__PURE__ */ new WeakMap();
|
|
504
|
+
/**
|
|
505
|
+
* The per-session advisor state, created on first touch.
|
|
506
|
+
* @param session - the session to key the state on (by object identity).
|
|
507
|
+
*/
|
|
508
|
+
function getAdvisorState(session) {
|
|
509
|
+
let state = advisorStates.get(session);
|
|
510
|
+
if (state === void 0) {
|
|
511
|
+
state = {
|
|
512
|
+
todoVersion: void 0,
|
|
513
|
+
summary: void 0,
|
|
514
|
+
lastSummaryTurn: -1,
|
|
515
|
+
watermarkSeq: 0,
|
|
516
|
+
scores: /* @__PURE__ */ new Map(),
|
|
517
|
+
recertified: /* @__PURE__ */ new Map(),
|
|
518
|
+
failures: void 0,
|
|
519
|
+
inFlight: false,
|
|
520
|
+
lastDecay: void 0,
|
|
521
|
+
lastAdvice: void 0
|
|
522
|
+
};
|
|
523
|
+
advisorStates.set(session, state);
|
|
524
|
+
}
|
|
525
|
+
return state;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Insert or refresh one score with LRU semantics: a re-touched seq moves to
|
|
529
|
+
* the newest position, and the oldest entry is evicted once the map exceeds
|
|
530
|
+
* {@link ADVISOR_SCORES_LIMIT}.
|
|
531
|
+
*/
|
|
532
|
+
function recordScore(state, seq, entry) {
|
|
533
|
+
state.scores.delete(seq);
|
|
534
|
+
state.scores.set(seq, entry);
|
|
535
|
+
if (state.scores.size > 64) {
|
|
536
|
+
const oldest = state.scores.keys().next();
|
|
537
|
+
if (oldest.done !== true) state.scores.delete(oldest.value);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Mark one seq as LLM-recertified low relevance (a suggestion for later
|
|
542
|
+
* history-aggressiveness decisions, consumed by nothing in this round).
|
|
543
|
+
* Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
|
|
544
|
+
*/
|
|
545
|
+
function recordRecertified(state, seq, turn) {
|
|
546
|
+
state.recertified.delete(seq);
|
|
547
|
+
state.recertified.set(seq, turn);
|
|
548
|
+
if (state.recertified.size > 64) {
|
|
549
|
+
const oldest = state.recertified.keys().next();
|
|
550
|
+
if (oldest.done !== true) state.recertified.delete(oldest.value);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Drop every cached artifact that depends on the task semantics: a changed
|
|
555
|
+
* todo version invalidates the summary and makes all eligible candidates
|
|
556
|
+
* rescore-worthy (the watermark alone would otherwise hide them).
|
|
557
|
+
*/
|
|
558
|
+
function invalidateOnTaskChange(state, todoVersion) {
|
|
559
|
+
if (state.todoVersion === todoVersion) return false;
|
|
560
|
+
state.todoVersion = todoVersion;
|
|
561
|
+
state.summary = void 0;
|
|
562
|
+
state.lastSummaryTurn = -1;
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* `/ctx-summary off|on` overrides, keyed by session id (string). The command
|
|
567
|
+
* handler only sees `invocation.agent.session.id`, not the pruner's Session
|
|
568
|
+
* object, so these are id-keyed rather than WeakMap'd. Entries are two-char
|
|
569
|
+
* strings per session and cleared whenever the override is lifted.
|
|
570
|
+
*/
|
|
571
|
+
const summaryOverrides = /* @__PURE__ */ new Map();
|
|
572
|
+
/** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
|
|
573
|
+
function getSummaryOverride(sessionId) {
|
|
574
|
+
return summaryOverrides.get(sessionId);
|
|
575
|
+
}
|
|
576
|
+
/** Set or clear (`undefined`) the session's `/ctx-summary` override. */
|
|
577
|
+
function setSummaryOverride(sessionId, value) {
|
|
578
|
+
if (value === void 0) summaryOverrides.delete(sessionId);
|
|
579
|
+
else summaryOverrides.set(sessionId, value);
|
|
580
|
+
}
|
|
581
|
+
/** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
|
|
582
|
+
const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
|
|
583
|
+
/** Record the gate input the pass last evaluated for this session. */
|
|
584
|
+
function observeIntentEnabled(sessionId, enabled) {
|
|
585
|
+
lastObservedIntentEnabled.set(sessionId, enabled);
|
|
586
|
+
}
|
|
587
|
+
/** The settings-side enabled flag last observed for the session, if any. */
|
|
588
|
+
function getObservedIntentEnabled(sessionId) {
|
|
589
|
+
return lastObservedIntentEnabled.get(sessionId);
|
|
590
|
+
}
|
|
591
|
+
const lastIntentFolds = /* @__PURE__ */ new Map();
|
|
592
|
+
/** Record a landed intent fold for the session (newest wins). */
|
|
593
|
+
function recordIntentFold(sessionId, record) {
|
|
594
|
+
lastIntentFolds.set(sessionId, record);
|
|
595
|
+
}
|
|
596
|
+
/** The most recent landed intent fold for the session, if any. */
|
|
597
|
+
function getLastIntentFold(sessionId) {
|
|
598
|
+
return lastIntentFolds.get(sessionId);
|
|
599
|
+
}
|
|
600
|
+
//#endregion
|
|
601
|
+
//#region src/runtime/tokenpilot/intent-gate.ts
|
|
602
|
+
/**
|
|
603
|
+
* Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
|
|
604
|
+
*
|
|
605
|
+
* Pure decision helper evaluated at the turn-boundary postflight: it decides
|
|
606
|
+
* whether this turn may spend a summary-writer LLM call and stage a fold for
|
|
607
|
+
* the next pressure round. The gate is deliberately conservative — every
|
|
608
|
+
* unresolved input (unknown context window, non-finite counters) fails closed
|
|
609
|
+
* toward "do not run", because a skipped fold is free while a wasted summary
|
|
610
|
+
* call is not. Content safety is unaffected either way: fail-open semantics
|
|
611
|
+
* live in the fold landing path, not here.
|
|
612
|
+
*/
|
|
613
|
+
/** Floor: the live surface must exceed this fraction of the context window. */
|
|
614
|
+
const INTENT_GATE_FLOOR_FRACTION = .45;
|
|
615
|
+
/** Growth: the live surface must have grown by more than this since the last landed fold. */
|
|
616
|
+
const INTENT_GATE_GROWTH_TOKENS = 5e4;
|
|
617
|
+
function isUsableNumber(value) {
|
|
618
|
+
return Number.isFinite(value) && value >= 0;
|
|
619
|
+
}
|
|
620
|
+
/** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
|
|
621
|
+
function evaluateIntentGate(input) {
|
|
622
|
+
const snapshot = (decision, reason) => ({
|
|
623
|
+
...input,
|
|
624
|
+
decision,
|
|
625
|
+
reason
|
|
626
|
+
});
|
|
627
|
+
if (!input.enabled) return snapshot(false, "disabled");
|
|
628
|
+
if (input.override === "off") return snapshot(false, "override-off");
|
|
629
|
+
if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
|
|
630
|
+
if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
|
|
631
|
+
if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
|
|
632
|
+
if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
|
|
633
|
+
if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
|
|
634
|
+
return snapshot(true, "passed");
|
|
635
|
+
}
|
|
636
|
+
//#endregion
|
|
637
|
+
//#region src/runtime/monitor.ts
|
|
638
|
+
/**
|
|
639
|
+
* 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
|
|
640
|
+
* 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
|
|
641
|
+
* (默认 80%)——提前一档给出人工干预窗口。
|
|
642
|
+
*/
|
|
643
|
+
const MONITOR_SUGGEST_PCT = .7;
|
|
644
|
+
/**
|
|
645
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
646
|
+
* injectable so tests seed a private instance instead of the process
|
|
647
|
+
* singleton.
|
|
648
|
+
*/
|
|
649
|
+
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
650
|
+
const scopeKey = sessionId ?? "";
|
|
651
|
+
const override = getSummaryOverride(scopeKey);
|
|
652
|
+
const observedContext = scopeKey.length > 0 ? getContextUsage(scopeKey) : latestObservedContextUsage();
|
|
653
|
+
const contextBlock = observedContext === void 0 ? void 0 : {
|
|
654
|
+
liveTokens: observedContext.liveTokens,
|
|
655
|
+
contextWindow: observedContext.contextWindow,
|
|
656
|
+
pct: observedContext.contextWindow !== void 0 && observedContext.contextWindow > 0 ? Math.round(observedContext.liveTokens / observedContext.contextWindow * 1e3) / 1e3 : null,
|
|
657
|
+
sessionId: observedContext.sessionId
|
|
658
|
+
};
|
|
659
|
+
const suggestion = contextBlock === void 0 || contextBlock.pct === null ? void 0 : {
|
|
660
|
+
suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
|
|
661
|
+
thresholdPct: MONITOR_SUGGEST_PCT,
|
|
662
|
+
occupancyPct: contextBlock.pct
|
|
663
|
+
};
|
|
664
|
+
return {
|
|
665
|
+
...ledger.snapshot(sessionId),
|
|
666
|
+
...contextBlock === void 0 ? {} : { context: contextBlock },
|
|
667
|
+
...suggestion === void 0 ? {} : { suggestion },
|
|
668
|
+
intent: {
|
|
669
|
+
override,
|
|
670
|
+
observedEnabled: getObservedIntentEnabled(scopeKey),
|
|
671
|
+
gate: {
|
|
672
|
+
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
673
|
+
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
674
|
+
},
|
|
675
|
+
lastFold: getLastIntentFold(scopeKey)
|
|
676
|
+
},
|
|
677
|
+
sessionScope: sessionId ?? null
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
/** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
|
|
681
|
+
const contextUsageBySession = /* @__PURE__ */ new Map();
|
|
682
|
+
const CONTEXT_USAGE_CAP = 64;
|
|
683
|
+
/**
|
|
684
|
+
* 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
|
|
685
|
+
* contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
|
|
686
|
+
*/
|
|
687
|
+
function observeContextUsage(sessionId, liveTokens, contextWindow) {
|
|
688
|
+
if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return;
|
|
689
|
+
if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
|
|
690
|
+
const oldest = contextUsageBySession.keys().next().value;
|
|
691
|
+
if (oldest !== void 0) contextUsageBySession.delete(oldest);
|
|
692
|
+
}
|
|
693
|
+
contextUsageBySession.set(sessionId, {
|
|
694
|
+
liveTokens,
|
|
695
|
+
contextWindow,
|
|
696
|
+
at: Date.now(),
|
|
697
|
+
seq: ++observeSeq
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
function getContextUsage(sessionId) {
|
|
701
|
+
const entry = contextUsageBySession.get(sessionId);
|
|
702
|
+
return entry === void 0 ? void 0 : {
|
|
703
|
+
liveTokens: entry.liveTokens,
|
|
704
|
+
contextWindow: entry.contextWindow,
|
|
705
|
+
sessionId
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
let observeSeq = 0;
|
|
709
|
+
function latestObservedContextUsage() {
|
|
710
|
+
let latest;
|
|
711
|
+
for (const [sessionId, entry] of contextUsageBySession) if (latest === void 0 || entry.seq > latest.seq) latest = {
|
|
712
|
+
sessionId,
|
|
713
|
+
liveTokens: entry.liveTokens,
|
|
714
|
+
contextWindow: entry.contextWindow,
|
|
715
|
+
seq: entry.seq
|
|
716
|
+
};
|
|
717
|
+
return latest;
|
|
718
|
+
}
|
|
719
|
+
function isSessionOverrideAction(value) {
|
|
720
|
+
return value === "on" || value === "off" || value === "clear";
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
724
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
725
|
+
* handed back so the route can echo the post-action truth.
|
|
726
|
+
*/
|
|
727
|
+
function applySessionOverride(sessionId, action) {
|
|
728
|
+
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
729
|
+
return { override: getSummaryOverride(sessionId) };
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
733
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
734
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
735
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
736
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
737
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
738
|
+
*/
|
|
739
|
+
function estimateSavingsPricing(readService, snapshot) {
|
|
740
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
741
|
+
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
742
|
+
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
743
|
+
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
744
|
+
if (provider !== "deepseek-official") return void 0;
|
|
745
|
+
const now = /* @__PURE__ */ new Date();
|
|
746
|
+
const startedAt = new Date(snapshot.startedAt);
|
|
747
|
+
const base = {
|
|
748
|
+
provider,
|
|
749
|
+
baseUrlClass: "official-public",
|
|
750
|
+
apiRoute: "chat-completions",
|
|
751
|
+
modelId,
|
|
752
|
+
currency: "USD",
|
|
753
|
+
startedAt,
|
|
754
|
+
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
755
|
+
};
|
|
756
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
757
|
+
...base,
|
|
758
|
+
usage: {
|
|
759
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
760
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
761
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
765
|
+
...base,
|
|
766
|
+
usage: {
|
|
767
|
+
cacheReadTokens: 0,
|
|
768
|
+
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
769
|
+
outputTokens: 0
|
|
770
|
+
}
|
|
771
|
+
}) : void 0;
|
|
772
|
+
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
773
|
+
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
774
|
+
return {
|
|
775
|
+
currency: "USD",
|
|
776
|
+
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
777
|
+
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
//#endregion
|
|
2
781
|
//#region src/runtime/types.ts
|
|
3
782
|
/** User-facing mixed strategy profile. */
|
|
4
783
|
const COMPRESSION_PROFILES = [
|
|
@@ -387,6 +1166,20 @@ function parseIntentSummarySettings(value) {
|
|
|
387
1166
|
return { enabled };
|
|
388
1167
|
}
|
|
389
1168
|
/**
|
|
1169
|
+
* Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
|
|
1170
|
+
* section semantics: absent inherits the hidden default, while a
|
|
1171
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
1172
|
+
*/
|
|
1173
|
+
function parseMonitorPanelSettings(value) {
|
|
1174
|
+
if (value === void 0) return { enabled: false };
|
|
1175
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression monitorPanel must be a plain object");
|
|
1176
|
+
const keys = Object.keys(value);
|
|
1177
|
+
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
1178
|
+
const enabled = value.enabled;
|
|
1179
|
+
if (typeof enabled !== "boolean") throw new TypeError("Context-compression monitorPanel.enabled must be a boolean");
|
|
1180
|
+
return { enabled };
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
390
1183
|
* Parse the optional tokenpilot-inspired preset sub-capability section. Absent
|
|
391
1184
|
* inherits the preset defaults; present-but-invalid is rejected, mirroring the
|
|
392
1185
|
* codeSkeleton section semantics.
|
|
@@ -494,7 +1287,8 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
|
|
|
494
1287
|
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
495
1288
|
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
496
1289
|
codeSkeleton: { enabled: false },
|
|
497
|
-
intentSummary: { enabled: false }
|
|
1290
|
+
intentSummary: { enabled: false },
|
|
1291
|
+
monitorPanel: { enabled: false }
|
|
498
1292
|
};
|
|
499
1293
|
/**
|
|
500
1294
|
* Parse one settings document with the persisted-section semantics: `undefined`
|
|
@@ -512,19 +1306,21 @@ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value)
|
|
|
512
1306
|
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
|
|
513
1307
|
assertPlainDataTree(value);
|
|
514
1308
|
const candidate = structuredClone(value);
|
|
515
|
-
const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "presetOptions");
|
|
1309
|
+
const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
|
|
516
1310
|
if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
|
|
517
1311
|
assertPresentSection(candidate, "profile", isSupportedProfile);
|
|
518
1312
|
assertPresentSection(candidate, "custom", isUsableCustomDocument);
|
|
519
1313
|
const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
|
|
520
1314
|
const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
|
|
521
1315
|
const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
|
|
1316
|
+
const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
|
|
522
1317
|
const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
|
|
523
1318
|
return {
|
|
524
1319
|
...contextCompressionSettingsInputSchema(candidate),
|
|
525
1320
|
autoCompact,
|
|
526
1321
|
codeSkeleton,
|
|
527
1322
|
intentSummary,
|
|
1323
|
+
monitorPanel,
|
|
528
1324
|
...presetOptions === void 0 ? {} : { presetOptions }
|
|
529
1325
|
};
|
|
530
1326
|
}).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
|
|
@@ -913,138 +1709,5 @@ function assertPositiveInteger(name, value) {
|
|
|
913
1709
|
function assertNonNegativeInteger(name, value) {
|
|
914
1710
|
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
|
|
915
1711
|
}
|
|
916
|
-
const advisorStates = /* @__PURE__ */ new WeakMap();
|
|
917
|
-
/**
|
|
918
|
-
* The per-session advisor state, created on first touch.
|
|
919
|
-
* @param session - the session to key the state on (by object identity).
|
|
920
|
-
*/
|
|
921
|
-
function getAdvisorState(session) {
|
|
922
|
-
let state = advisorStates.get(session);
|
|
923
|
-
if (state === void 0) {
|
|
924
|
-
state = {
|
|
925
|
-
todoVersion: void 0,
|
|
926
|
-
summary: void 0,
|
|
927
|
-
lastSummaryTurn: -1,
|
|
928
|
-
watermarkSeq: 0,
|
|
929
|
-
scores: /* @__PURE__ */ new Map(),
|
|
930
|
-
recertified: /* @__PURE__ */ new Map(),
|
|
931
|
-
failures: void 0,
|
|
932
|
-
inFlight: false,
|
|
933
|
-
lastDecay: void 0,
|
|
934
|
-
lastAdvice: void 0
|
|
935
|
-
};
|
|
936
|
-
advisorStates.set(session, state);
|
|
937
|
-
}
|
|
938
|
-
return state;
|
|
939
|
-
}
|
|
940
|
-
/**
|
|
941
|
-
* Insert or refresh one score with LRU semantics: a re-touched seq moves to
|
|
942
|
-
* the newest position, and the oldest entry is evicted once the map exceeds
|
|
943
|
-
* {@link ADVISOR_SCORES_LIMIT}.
|
|
944
|
-
*/
|
|
945
|
-
function recordScore(state, seq, entry) {
|
|
946
|
-
state.scores.delete(seq);
|
|
947
|
-
state.scores.set(seq, entry);
|
|
948
|
-
if (state.scores.size > 64) {
|
|
949
|
-
const oldest = state.scores.keys().next();
|
|
950
|
-
if (oldest.done !== true) state.scores.delete(oldest.value);
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Mark one seq as LLM-recertified low relevance (a suggestion for later
|
|
955
|
-
* history-aggressiveness decisions, consumed by nothing in this round).
|
|
956
|
-
* Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
|
|
957
|
-
*/
|
|
958
|
-
function recordRecertified(state, seq, turn) {
|
|
959
|
-
state.recertified.delete(seq);
|
|
960
|
-
state.recertified.set(seq, turn);
|
|
961
|
-
if (state.recertified.size > 64) {
|
|
962
|
-
const oldest = state.recertified.keys().next();
|
|
963
|
-
if (oldest.done !== true) state.recertified.delete(oldest.value);
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* Drop every cached artifact that depends on the task semantics: a changed
|
|
968
|
-
* todo version invalidates the summary and makes all eligible candidates
|
|
969
|
-
* rescore-worthy (the watermark alone would otherwise hide them).
|
|
970
|
-
*/
|
|
971
|
-
function invalidateOnTaskChange(state, todoVersion) {
|
|
972
|
-
if (state.todoVersion === todoVersion) return false;
|
|
973
|
-
state.todoVersion = todoVersion;
|
|
974
|
-
state.summary = void 0;
|
|
975
|
-
state.lastSummaryTurn = -1;
|
|
976
|
-
return true;
|
|
977
|
-
}
|
|
978
|
-
/**
|
|
979
|
-
* `/ctx-summary off|on` overrides, keyed by session id (string). The command
|
|
980
|
-
* handler only sees `invocation.agent.session.id`, not the pruner's Session
|
|
981
|
-
* object, so these are id-keyed rather than WeakMap'd. Entries are two-char
|
|
982
|
-
* strings per session and cleared whenever the override is lifted.
|
|
983
|
-
*/
|
|
984
|
-
const summaryOverrides = /* @__PURE__ */ new Map();
|
|
985
|
-
/** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
|
|
986
|
-
function getSummaryOverride(sessionId) {
|
|
987
|
-
return summaryOverrides.get(sessionId);
|
|
988
|
-
}
|
|
989
|
-
/** Set or clear (`undefined`) the session's `/ctx-summary` override. */
|
|
990
|
-
function setSummaryOverride(sessionId, value) {
|
|
991
|
-
if (value === void 0) summaryOverrides.delete(sessionId);
|
|
992
|
-
else summaryOverrides.set(sessionId, value);
|
|
993
|
-
}
|
|
994
|
-
/** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
|
|
995
|
-
const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
|
|
996
|
-
/** Record the gate input the pass last evaluated for this session. */
|
|
997
|
-
function observeIntentEnabled(sessionId, enabled) {
|
|
998
|
-
lastObservedIntentEnabled.set(sessionId, enabled);
|
|
999
|
-
}
|
|
1000
|
-
/** The settings-side enabled flag last observed for the session, if any. */
|
|
1001
|
-
function getObservedIntentEnabled(sessionId) {
|
|
1002
|
-
return lastObservedIntentEnabled.get(sessionId);
|
|
1003
|
-
}
|
|
1004
|
-
const lastIntentFolds = /* @__PURE__ */ new Map();
|
|
1005
|
-
/** Record a landed intent fold for the session (newest wins). */
|
|
1006
|
-
function recordIntentFold(sessionId, record) {
|
|
1007
|
-
lastIntentFolds.set(sessionId, record);
|
|
1008
|
-
}
|
|
1009
|
-
/** The most recent landed intent fold for the session, if any. */
|
|
1010
|
-
function getLastIntentFold(sessionId) {
|
|
1011
|
-
return lastIntentFolds.get(sessionId);
|
|
1012
|
-
}
|
|
1013
|
-
//#endregion
|
|
1014
|
-
//#region src/runtime/tokenpilot/intent-gate.ts
|
|
1015
|
-
/**
|
|
1016
|
-
* Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
|
|
1017
|
-
*
|
|
1018
|
-
* Pure decision helper evaluated at the turn-boundary postflight: it decides
|
|
1019
|
-
* whether this turn may spend a summary-writer LLM call and stage a fold for
|
|
1020
|
-
* the next pressure round. The gate is deliberately conservative — every
|
|
1021
|
-
* unresolved input (unknown context window, non-finite counters) fails closed
|
|
1022
|
-
* toward "do not run", because a skipped fold is free while a wasted summary
|
|
1023
|
-
* call is not. Content safety is unaffected either way: fail-open semantics
|
|
1024
|
-
* live in the fold landing path, not here.
|
|
1025
|
-
*/
|
|
1026
|
-
/** Floor: the live surface must exceed this fraction of the context window. */
|
|
1027
|
-
const INTENT_GATE_FLOOR_FRACTION = .45;
|
|
1028
|
-
/** Growth: the live surface must have grown by more than this since the last landed fold. */
|
|
1029
|
-
const INTENT_GATE_GROWTH_TOKENS = 5e4;
|
|
1030
|
-
function isUsableNumber(value) {
|
|
1031
|
-
return Number.isFinite(value) && value >= 0;
|
|
1032
|
-
}
|
|
1033
|
-
/** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
|
|
1034
|
-
function evaluateIntentGate(input) {
|
|
1035
|
-
const snapshot = (decision, reason) => ({
|
|
1036
|
-
...input,
|
|
1037
|
-
decision,
|
|
1038
|
-
reason
|
|
1039
|
-
});
|
|
1040
|
-
if (!input.enabled) return snapshot(false, "disabled");
|
|
1041
|
-
if (input.override === "off") return snapshot(false, "override-off");
|
|
1042
|
-
if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
|
|
1043
|
-
if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
|
|
1044
|
-
if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
|
|
1045
|
-
if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
|
|
1046
|
-
if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
|
|
1047
|
-
return snapshot(true, "passed");
|
|
1048
|
-
}
|
|
1049
1712
|
//#endregion
|
|
1050
|
-
export {
|
|
1713
|
+
export { getLastIntentFold as A, decimalRateNanoUnits as B, estimateSavingsPricing as C, INTENT_GATE_GROWTH_TOKENS as D, INTENT_GATE_FLOOR_FRACTION as E, recordIntentFold as F, resolveOfficialDeepSeekPrice as H, recordRecertified as I, recordScore as L, getSummaryOverride as M, invalidateOnTaskChange as N, evaluateIntentGate as O, observeIntentEnabled as P, setSummaryOverride as R, buildMonitorSnapshot as S, observeContextUsage as T, getSavingsLedger as U, priceOfficialDeepSeekUsage as V, resolveCustomPolicy as _, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as a, COMPRESSION_PROFILES as b, charsToTokens as c, isValidAutoCompactThresholdPercent as d, parseContextCompressionSettings as f, DEFAULT_CUSTOM_COMPRESSION_POLICY as g, CustomCompressionPolicySchema as h, DEFAULTS as i, getObservedIntentEnabled as j, getAdvisorState as k, codePointLength as l, resolvePolicy as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, PRUNE_MARKER as o, resolveConfig as p, ContextCompressionSettingsSchema as r, charsForTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isCompressionProfile as u, assertNever as v, isSessionOverrideAction as w, applySessionOverride as x, deepFreeze as y, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as z };
|