dsh-context-compression-improved 0.2.4 → 0.2.5

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.
Files changed (127) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +8 -8
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +212 -16
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +1 -19
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +75 -54
  22. package/packages/selector/README.md +7 -12
  23. package/packages/selector/README.zh.md +6 -13
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +16 -16
  27. package/packages/selector/lib/client.d.ts +97 -5
  28. package/packages/selector/lib/client.js +1884 -92
  29. package/packages/selector/lib/config.js +863 -6
  30. package/packages/selector/lib/index.d.ts +29 -21
  31. package/packages/selector/lib/index.js +424 -18
  32. package/packages/selector/lib/invariant.js +4 -4
  33. package/packages/selector/lib/pruner.d.ts +179 -4
  34. package/packages/selector/lib/pruner.js +1406 -371
  35. package/packages/selector/lib/style.css +42 -0
  36. package/packages/selector/lib/tail-trim.js +13 -4
  37. package/packages/selector/package.json +18 -27
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +200 -62
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/profiles.ts +431 -342
  61. package/packages/selector/src/pruner/state.ts +57 -43
  62. package/packages/selector/src/pruner.ts +2736 -2154
  63. package/packages/selector/src/runtime/audit.ts +303 -231
  64. package/packages/selector/src/runtime/config.ts +756 -642
  65. package/packages/selector/src/runtime/measurement.ts +436 -432
  66. package/packages/selector/src/runtime/monitor.ts +235 -0
  67. package/packages/selector/src/runtime/retrieve.ts +479 -457
  68. package/packages/selector/src/runtime/savings.ts +337 -0
  69. package/packages/selector/src/runtime/session-events.ts +30 -17
  70. package/packages/selector/src/runtime/summary-command.ts +127 -0
  71. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  72. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  73. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  74. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  75. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  76. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  77. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  78. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  79. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  80. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  81. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
  82. package/packages/selector/src/runtime/types.ts +365 -325
  83. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  84. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  85. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  86. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  87. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  88. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  89. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  90. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  91. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  92. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  93. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  94. package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
  95. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  96. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  97. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  98. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  99. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  100. package/packages/selector/tests/runtime/audit.spec.ts +275 -172
  101. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  102. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  103. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  104. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  105. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
  106. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  107. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  108. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  109. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  110. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  111. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  112. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  113. package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
  114. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  115. package/pnpm-workspace.yaml +66 -19
  116. package/scripts/capture-profile-baseline.mjs +42 -0
  117. package/scripts/generate-tokenizer-fixtures.py +81 -81
  118. package/scripts/generate-vision-fixtures.py +208 -208
  119. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  120. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  121. package/scripts/toolclass-corpus-replay.mjs +281 -273
  122. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  123. package/tests/TEST_INVENTORY.md +41 -42
  124. package/scripts/capture-profile-baseline.ts +0 -80
  125. package/tsconfig.scripts.json +0 -13
  126. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  127. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -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 = [
@@ -373,6 +1152,34 @@ function parseCodeSkeletonSettings(value) {
373
1152
  return { enabled };
374
1153
  }
375
1154
  /**
1155
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
1156
+ * section semantics: absent inherits the lossless `false` default, while a
1157
+ * present-but-invalid section is an explicitly invalid document.
1158
+ */
1159
+ function parseIntentSummarySettings(value) {
1160
+ if (value === void 0) return { enabled: false };
1161
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
1162
+ const keys = Object.keys(value);
1163
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
1164
+ const enabled = value.enabled;
1165
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
1166
+ return { enabled };
1167
+ }
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
+ /**
376
1183
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
377
1184
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
378
1185
  * codeSkeleton section semantics.
@@ -390,7 +1197,17 @@ function parsePresetOptionsSettings(value) {
390
1197
  "estimatorModel",
391
1198
  "estimatorBaseUrl",
392
1199
  "estimatorApiKey",
393
- "estimatorTimeoutMs"
1200
+ "estimatorTimeoutMs",
1201
+ "reviewMode",
1202
+ "reviewTimeoutTurns",
1203
+ "cacheHitDiscountAlpha",
1204
+ "reviewHighImpactTokens",
1205
+ "advisorMode",
1206
+ "advisorTimeoutMs",
1207
+ "advisorRefreshTurns",
1208
+ "advisorScoreThreshold",
1209
+ "advisorSampleLimit",
1210
+ "advisorMinTokens"
394
1211
  ]);
395
1212
  const unknown = Object.keys(value).find((key) => !allowed.has(key));
396
1213
  if (unknown !== void 0) throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`);
@@ -405,6 +1222,18 @@ function parsePresetOptionsSettings(value) {
405
1222
  }
406
1223
  const estimatorMode = value.estimatorMode;
407
1224
  if (estimatorMode !== void 0 && estimatorMode !== "" && estimatorMode !== "host" && estimatorMode !== "direct") throw new TypeError("Context-compression presetOptions.estimatorMode must be \"\", \"host\", or \"direct\"");
1225
+ const advisorMode = value.advisorMode;
1226
+ if (advisorMode !== void 0 && advisorMode !== "" && advisorMode !== "host" && advisorMode !== "direct") throw new TypeError("Context-compression presetOptions.advisorMode must be \"\", \"host\", or \"direct\"");
1227
+ const advisorTimeoutMs = value.advisorTimeoutMs;
1228
+ if (advisorTimeoutMs !== void 0 && (typeof advisorTimeoutMs !== "number" || !Number.isSafeInteger(advisorTimeoutMs) || advisorTimeoutMs < 100 || advisorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000");
1229
+ const advisorRefreshTurns = value.advisorRefreshTurns;
1230
+ if (advisorRefreshTurns !== void 0 && (typeof advisorRefreshTurns !== "number" || !Number.isSafeInteger(advisorRefreshTurns) || advisorRefreshTurns < 1)) throw new TypeError("Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1");
1231
+ const advisorScoreThreshold = value.advisorScoreThreshold;
1232
+ if (advisorScoreThreshold !== void 0 && (typeof advisorScoreThreshold !== "number" || !Number.isFinite(advisorScoreThreshold) || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) throw new TypeError("Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1");
1233
+ const advisorSampleLimit = value.advisorSampleLimit;
1234
+ if (advisorSampleLimit !== void 0 && (typeof advisorSampleLimit !== "number" || !Number.isSafeInteger(advisorSampleLimit) || advisorSampleLimit < 1 || advisorSampleLimit > 64)) throw new TypeError("Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64");
1235
+ const advisorMinTokens = value.advisorMinTokens;
1236
+ if (advisorMinTokens !== void 0 && (typeof advisorMinTokens !== "number" || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) throw new TypeError("Context-compression presetOptions.advisorMinTokens must be a positive integer");
408
1237
  const estimatorTimeoutMs = value.estimatorTimeoutMs;
409
1238
  if (estimatorTimeoutMs !== void 0 && (typeof estimatorTimeoutMs !== "number" || !Number.isSafeInteger(estimatorTimeoutMs) || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000");
410
1239
  for (const key of [
@@ -427,6 +1256,12 @@ function parsePresetOptionsSettings(value) {
427
1256
  if (value.estimatorBaseUrl !== void 0) result.estimatorBaseUrl = value.estimatorBaseUrl;
428
1257
  if (value.estimatorApiKey !== void 0) result.estimatorApiKey = value.estimatorApiKey;
429
1258
  if (estimatorTimeoutMs !== void 0) result.estimatorTimeoutMs = estimatorTimeoutMs;
1259
+ if (advisorMode !== void 0) result.advisorMode = advisorMode;
1260
+ if (advisorTimeoutMs !== void 0) result.advisorTimeoutMs = advisorTimeoutMs;
1261
+ if (advisorRefreshTurns !== void 0) result.advisorRefreshTurns = advisorRefreshTurns;
1262
+ if (advisorScoreThreshold !== void 0) result.advisorScoreThreshold = advisorScoreThreshold;
1263
+ if (advisorSampleLimit !== void 0) result.advisorSampleLimit = advisorSampleLimit;
1264
+ if (advisorMinTokens !== void 0) result.advisorMinTokens = advisorMinTokens;
430
1265
  return result;
431
1266
  }
432
1267
  /** Settings schema used by the user-facing profile selector. */
@@ -451,7 +1286,9 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
451
1286
  profile: "balanced",
452
1287
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
453
1288
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
454
- codeSkeleton: { enabled: false }
1289
+ codeSkeleton: { enabled: false },
1290
+ intentSummary: { enabled: false },
1291
+ monitorPanel: { enabled: false }
455
1292
  };
456
1293
  /**
457
1294
  * Parse one settings document with the persisted-section semantics: `undefined`
@@ -469,17 +1306,21 @@ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value)
469
1306
  if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
470
1307
  assertPlainDataTree(value);
471
1308
  const candidate = structuredClone(value);
472
- const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "presetOptions");
1309
+ const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
473
1310
  if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
474
1311
  assertPresentSection(candidate, "profile", isSupportedProfile);
475
1312
  assertPresentSection(candidate, "custom", isUsableCustomDocument);
476
1313
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
477
1314
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
1315
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
1316
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
478
1317
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
479
1318
  return {
480
1319
  ...contextCompressionSettingsInputSchema(candidate),
481
1320
  autoCompact,
482
1321
  codeSkeleton,
1322
+ intentSummary,
1323
+ monitorPanel,
483
1324
  ...presetOptions === void 0 ? {} : { presetOptions }
484
1325
  };
485
1326
  }).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
@@ -641,7 +1482,15 @@ const PRESET_OPTION_DEFAULTS = deepFreeze({
641
1482
  summaryLocator: true,
642
1483
  prefixStabilizer: true,
643
1484
  readState: true,
644
- estimator: { mode: "" }
1485
+ estimator: { mode: "" },
1486
+ advisor: {
1487
+ mode: "",
1488
+ timeoutMs: 8e3,
1489
+ refreshTurns: 8,
1490
+ scoreThreshold: .35,
1491
+ sampleLimit: 16,
1492
+ minTokens: 250
1493
+ }
645
1494
  });
646
1495
  /**
647
1496
  * Merge persisted presetOptions overrides over the tokenpilot-inspired
@@ -657,7 +1506,15 @@ function mergePresetOptions(overrides) {
657
1506
  summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
658
1507
  prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
659
1508
  readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
660
- estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode }
1509
+ estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
1510
+ advisor: {
1511
+ mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
1512
+ timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
1513
+ refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
1514
+ scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
1515
+ sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
1516
+ minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens
1517
+ }
661
1518
  });
662
1519
  }
663
1520
  /**
@@ -853,4 +1710,4 @@ function assertNonNegativeInteger(name, value) {
853
1710
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
854
1711
  }
855
1712
  //#endregion
856
- export { assertNever as _, PRUNE_MARKER as a, codePointLength as c, parseContextCompressionSettings as d, resolveConfig as f, resolveCustomPolicy as g, DEFAULT_CUSTOM_COMPRESSION_POLICY as h, DEFAULTS as i, isCompressionProfile as l, CustomCompressionPolicySchema as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, charsForTokens as o, resolvePolicy as p, ContextCompressionSettingsSchema as r, charsToTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isValidAutoCompactThresholdPercent as u, deepFreeze as v, COMPRESSION_PROFILES as y };
1713
+ export { getObservedIntentEnabled as A, priceOfficialDeepSeekUsage as B, isSessionOverrideAction as C, evaluateIntentGate as D, INTENT_GATE_GROWTH_TOKENS as E, recordRecertified as F, getSavingsLedger as H, recordScore as I, setSummaryOverride as L, invalidateOnTaskChange as M, observeIntentEnabled as N, getAdvisorState as O, recordIntentFold as P, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as R, estimateSavingsPricing as S, INTENT_GATE_FLOOR_FRACTION as T, resolveOfficialDeepSeekPrice as V, assertNever as _, PRUNE_MARKER as a, applySessionOverride as b, codePointLength as c, parseContextCompressionSettings as d, resolveConfig as f, resolveCustomPolicy as g, DEFAULT_CUSTOM_COMPRESSION_POLICY as h, DEFAULTS as i, getSummaryOverride as j, getLastIntentFold as k, isCompressionProfile as l, CustomCompressionPolicySchema as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, charsForTokens as o, resolvePolicy as p, ContextCompressionSettingsSchema as r, charsToTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isValidAutoCompactThresholdPercent as u, deepFreeze as v, observeContextUsage as w, buildMonitorSnapshot as x, COMPRESSION_PROFILES as y, decimalRateNanoUnits as z };